การแปลงข้อความให้เป็นเสียงพูด (Text to Speech: TTS) บน Windows 10

1.ตรวจสอบเสียงที่ติดตั้งมาในเครื่อง

เปิด Control Panel แล้วเลือก Speech Recognition

เลือก Text to Speech

ที่หน้าต่าง Speech Properties จะแสดงเสียงที่ติดตั้งอยู่ในเครื่อง

2.เขียน C# ด้วย .Net Framework 4.8

สร้างโปรเจ็กส์แบบ Console

Add Reference ชื่อ System.Speech Version 4.0.0.0

เพิ่มโค๊ด C#

using System.Speech.Synthesis;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            SpeechSynthesizer syn = new SpeechSynthesizer();
            syn.Speak("I love Thailand.");
        }
    }
}

เมื่อรันจะได้ยินเสียงละ

เปลี่ยนเสียงพูดเป็นของ Microsoft Zira Desktop

using System.Speech.Synthesis;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            SpeechSynthesizer syn = new SpeechSynthesizer();
            syn.SelectVoice("Microsoft Zira Desktop");
            syn.Speak("I love Thailand.");
        }
    }
}

ปรับความเร็วของเสียงพูด ค่าบวกยิ่งมากยิ่งพูดเร็ว ค่าลบยิ่งลดมากยิ่งพูดช้า

using System.Speech.Synthesis;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            SpeechSynthesizer syn = new SpeechSynthesizer();
            syn.SelectVoice("Microsoft Zira Desktop");
            syn.Rate = 1;  // -10 to 10
            syn.Speak("I love Thailand.");
        }
    }
}

Posted in C#

ติดตั้ง OpenSSH บน Windows

Install OpenSSH using Windows Settings

  1. Open Settings, select Apps > Apps & Features, then select Optional Features.
  2. Scan the list to see if the OpenSSH is already installed. If not, at the top of the page, select Add a feature, then:
  • Find OpenSSH Client, then click Install
  • Find OpenSSH Server, then click Install

แต่ถ้าเจอแค่ OpenSSH Client ไม่เจอ OpenSSH Server ให้ติดตั้งด้วย PowerShell

Install OpenSSH using PowerShell

To install OpenSSH using PowerShell, run PowerShell as an Administrator. To make sure that OpenSSH is available, run the following cmdlet:

Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*'

This should return the following output if neither are already installed:

Name  : OpenSSH.Client~~~~0.0.1.0
State : NotPresent

Name  : OpenSSH.Server~~~~0.0.1.0
State : NotPresent

Then, install the server or client components as needed:

# Install the OpenSSH Client
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0

# Install the OpenSSH Server
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

Both of these should return the following output:

Path          :
Online        : True
RestartNeeded : False

Start and configure OpenSSH Server

To start and configure OpenSSH Server for initial use, open PowerShell as an administrator, then run the following commands

# Start the sshd service
Start-Service sshd

# OPTIONAL but recommended:
Set-Service -Name sshd -StartupType 'Automatic'

# Confirm the Firewall rule is configured. It should be created automatically by setup. Run the following to verify
if (!(Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -ErrorAction SilentlyContinue | Select-Object Name, Enabled)) {
    Write-Output "Firewall Rule 'OpenSSH-Server-In-TCP' does not exist, creating it..."
    New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
} else {
    Write-Output "Firewall rule 'OpenSSH-Server-In-TCP' has been created and exists."
}

ติดตั้ง directus

เตรียมฐานข้อมูล

ที่ MySQL สร้างดาต้าเบส directus

CREATE SCHEMA `directus` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

สร้างโปรเจ็กส์ directus

สร้างโปรเจ็กส์ directus ชื่อ monospace

npx create-directus-project monospace

ถ้าเป็นการรันครั้งแรก จะถามว่าจะติดตั้ง package create-directus-project มั๊ย ให้ตอบ y

> npx create-directus-project monospace
Need to install the following packages:
  create-directus-project
Ok to proceed? (y)

เลือกดาต้าเบส

? Choose your database client
  PostgreSQL / Redshift
> MySQL / MariaDB / Aurora
  SQLite
  Microsoft SQL Server
  Oracle Database (Alpha)

ใส่รายละเอียดดาต้าเบส

? Database Host: 127.0.0.1
? Port: 3306
? Database Name: monospace
? Database User: jack
? Database Password: ************

สร้าง admin user

Create your first admin user:

? Email mr.phaisarn@gmail.com
? Password ************

Your project has been created at D:\Project\Directus\monospace.

The configuration can be found in D:\Project\Directus\monospace/.env

Start Directus by running:
  cd D:\Project\Directus\monospace
  npx directus start

config ต่างๆจะเก็บอยู่ในไฟล์ .env เช่น port ที่ใช้รัน , database connection

จะได้ไฟล์ package.json

{
  "name": "monospace",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "directus": "^9.0.0-rc.95",
    "mysql": "^2.18.1"
  }
}

ทดลองรัน

> cd D:\Project\Directus\monospace
> npx directus start

เปิด browser ไปที่ http://localhost:8055/

ติดตั้ง express generator

การติดตั้ง express generator

ติดตั้งครั้งเดียว ไม่ได้ขึ้นกับโปรเจ็กส์

npm install express-generator -g

ดู version

> express --version
4.16.1

ดู help

> express -h

  Usage: express [options] [dir]

  Options:

        --version        output the version number
    -e, --ejs            add ejs engine support
        --pug            add pug engine support
        --hbs            add handlebars engine support
    -H, --hogan          add hogan.js engine support
    -v, --view <engine>  add view <engine> support (dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
        --no-view        use static html instead of view engine
    -c, --css <engine>   add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
        --git            add .gitignore
    -f, --force          force on non-empty directory
    -h, --help           output usage information

-v, --view แสดง view engine ที่ใช้ได้ dust | ejs | hbs | hjs | jade | pug | twig | vash

ทดลองสร้างโปรเจ็กส์

สร้างโปรเจ็กส์ด้วย express generator โดยใช้ Pug

> express --view=pug myapp

   create : myapp\
   create : myapp\public\
   create : myapp\public\javascripts\
   create : myapp\public\images\
   create : myapp\public\stylesheets\
   create : myapp\public\stylesheets\style.css
   create : myapp\routes\
   create : myapp\routes\index.js
   create : myapp\routes\users.js
   create : myapp\views\
   create : myapp\views\error.pug
   create : myapp\views\index.pug
   create : myapp\views\layout.pug
   create : myapp\app.js
   create : myapp\package.json
   create : myapp\bin\
   create : myapp\bin\www

   change directory:
     > cd myapp

   install dependencies:
     > npm install

   run the app:
     > SET DEBUG=myapp:* & npm start

จะได้ไฟล์ package.json

{
  "name": "myapp",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "morgan": "~1.9.1",
    "pug": "2.0.0-beta11"
  }
}

เสร็จแล้วติดตั้ง dependencies:

> cd myapp
> npm install

สั่งรันโปรเจ็กส์บน MacOS or Linux

$ DEBUG=myapp:* npm start

สั่งรันโปรเจ็กส์บน Windows

> set DEBUG=myapp:* & npm start

ลองเปิด browser เข้าที่ http://localhost:3000/
จะเห็นข้อความ

Express
Welcome to Express

สร้างเว็บเซอร์เวอร์ด้วย Express

สร้างโฟลเดอร์ให้แอพชื่อ myapp

mkdir myapp
cd myapp

ใช้คำสั่ง npm init เพื่อสร้างไฟล์ package.json

> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (myapp)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\Project\node\myapp\package.json:

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes) y

จะได้ไฟล์ package.json

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

ติดตั้ง express ให้กับโปรเจ็กส์นี้

npm install express --save

ไฟล์ package.json จะเพิ่ม dependencies

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

สร้างไฟล์ server.js

var express = require('express')
var app = express()
 
app.get('/', function (req, res) {
    res.send('Hello World')
})
 
app.listen(3000)
console.log("Server running at port 3000");

หรือ

const express = require('express')
const app = express()
const port = 3000
 
app.get('/', (req, res) => res.send('Hello World!'))
 
app.listen(port, () => console.log(`App listening on port ${port}!`))

ทดลองรัน

> node server.js
Server running at port 3000

เปิด browser ไปที่ http://localhost:3000/
จะเห็นข้อความ Hello World

การใช้ Node.js เบื้องต้น

  1. การใช้ Node.js ทาง Terminal
  2. การใช้ Node.js จากไฟล์ที่พิมพ์คำสั่งไว้
  3. สร้างเว็บเซอร์เวอร์ แสดงข้อความ Hello World

1. การใช้ Node.js ทาง Terminal

เปิด command prompt แล้วเรียกใช้งาน node ด้วยคำสั่ง node

node

สั่งพิมพ์ออกหน้า console ด้วย console.log

> console.log("OK");
OK
undefined

สร้างฟังก์ชัน sayHi()

> function sayHi() {return "HI";}
undefined
> sayHi();
‘HI’
>

ทดลองบวกเลข

> 10 + 10
20

To exit, press Ctrl+C again or Ctrl+D or type .exit

2. การใช้ Node.js จากไฟล์ที่พิมพ์คำสั่งไว้

ทดสอบโดยการสร้างไฟล์ JavaScript ขึ้นมา เช่น test.js 

console.log("Hello Node.js");
 
function sayHi() {
    return "Hi!";
}
 
console.log(sayHi());

คำสั่งที่ใช้ให้ Node รันไฟล์ JavaScript คือ node [filename] เช่น

node test.js

จะได้ผลลัพธ์ดังนี้

Hello Node.js
Hi!

3. สร้างเว็บเซอร์เวอร์ แสดงข้อความ Hello World

สร้างไฟล์ชื่อ server.js

var http = require("http");
http.createServer(function (req, res) {
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end("Hello World\n");
}).listen(1337, "127.0.0.1");
 
console.log("Server running at http://127.0.0.1:1337/");

บรรทัดที่ 1 : require(‘http’) เป็นการ import module http ซึ่งเป็น module หลักของ Node.js
บรรทัดที่ 2 : createServer() เป็นการสร้าง Server ของ Node.js โดยรับ function ที่มี request และ response
บรรทัดที่ 3 : res.writeHead() เป็นการกำหนด Content Type
บรรทัดที่ 4 : res.end() เป็นการสิ้นสุด response และส่งคำว่า Hello World
บรรทัดที่ 5 : .listen(port, address) เป็นการกำหนด port และ address ของเว็บ Server (address เป็น optional)

ทำการสั่งรันบน command line ด้วยคำสั่ง

node server.js

จากนั้นเปิดเว็บบราวเซอร์ที่ http://localhost:1337/
จะเห็นข้อความ Hello World แสดงบนจอภาพ

การติดตั้ง Node.js บน Windows

หน้าเว็บหลัก Node.js https://nodejs.org/

เมื่อดาว์นโหลดจะได้ไฟล์ node-v14.18.0-x64.msi

เมื่อติดตั้งโปรแกรมจะอยู่ที่ C:\Program Files\nodejs\

การติดตั้งจะได้ node และ npm (Node Package Manager) ซึ่งเป็นตัวจัดการ package/module ต่างๆของ Node มาด้วย

ดูเวอร์ชันของ node

> node -v
v14.18.0

ดูเวอร์ชันของ npm

> npm -v
6.14.15

อัพเดท npm ให้เป็นเวอร์ชันล่าสุด

npm i npm@latest -g

เมื่อดูเวอร์ชันของ npm อีกทีจะได้เวอร์ชันล่าสุดละ

> npm -v
7.24.2

ตั้งแต่ npm 5.2.0 จะได้ npx (Node Package Execute) ติดตั้งมาด้วย

> npx -v
7.24.2

ดู config ของ npm

npm config ls

หรือต้องการดู config ทั้งหมด

npm config ls -l

ดูเสร็จแล้วถ้าจะกำหนดค่า config ให้ทำแบบนี้

> npm config set strict-ssl false
> npm config set ca=null

TypeScript

ติดตั้ง typescript

npm install -g typescript

ติดตั้ง typescript เวอร์ชันล่าสุด

npm install -g typescript@latest

ตรวจสอบเวอร์ชันของ typescript

> tsc -v
Version 4.4.3

ติดตั้ง SQL Server 2017 บน Ubuntu 18.04

Install SQL Server 2017

1.Import the public repository GPG keys:

wget -qO- https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -

2.Register the Microsoft SQL Server Ubuntu repository:

sudo add-apt-repository "$(wget -qO- https://packages.microsoft.com/config/ubuntu/18.04/mssql-server-2017.list)"

3.Run the following commands to install SQL Server:

sudo apt-get update
sudo apt-get install -y mssql-server

4.After the package installation finishes, run mssql-conf setup and follow the prompts to set the SA password and choose your edition.

sudo /opt/mssql/bin/mssql-conf setup

5.Once the configuration is done, verify that the service is running:

systemctl status mssql-server --no-pager

Install the SQL Server command-line tools

sudo apt install curl 

1.Import the public repository GPG keys.

curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -

2.Register the Microsoft Ubuntu repository.

curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list | sudo tee /etc/apt/sources.list.d/msprod.list

3.Update the sources list and run the installation command with the unixODBC developer package. For more information, see Install the Microsoft ODBC driver for SQL Server (Linux).

sudo apt-get update 
sudo apt-get install mssql-tools unixodbc-dev

4.Optional: Add /opt/mssql-tools/bin/ to your PATH environment variable in a bash shell.

echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
source ~/.bashrc

Connect locally

sqlcmd -S localhost -U SA -P '<YourPassword>'
SELECT Name from sys.Databases
GO

PyThaiNLP เบื้องต้น

การติดตั้ง

ติดตั้งปกติได้เวอร์ชัน 2.0.7

python -m pip install pythainlp

ติดตั้งด้วย --upgrade ได้เวอร์ชันล่าสุด (2.3.2)

python -m pip install --upgrade pythainlp

ติดตั้ง epitran

python -m pip install epitran

ตรวจสอบการติดตั้ง

import pythainlp
print(pythainlp.__version__)
2.3.2

Thai Characters

ตัวอักษร

import pythainlp
print(pythainlp.thai_characters)
print(len(pythainlp.thai_characters))
กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรลวศษสหฬอฮฤฦะัาำิีึืุูเแโใไๅํ็่้๊๋ฯฺๆ์ํ๎๏๚๛๐๑๒๓๔๕๖๗๘๙฿
88

พยัญชนะ

import pythainlp
print(pythainlp.thai_consonants)
print(len(pythainlp.thai_consonants))
กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรลวศษสหฬอฮ
44

ตัวเลข

import pythainlp
print(pythainlp.thai_digits)
print(len(pythainlp.thai_digits))
๐๑๒๓๔๕๖๗๘๙
10

การตรวจสอบ

import pythainlp
print("๔" in pythainlp.thai_characters)
print("๔" in pythainlp.thai_consonants)
print("๔" in pythainlp.thai_digits)
True
False
True

ตรวจสอบ Thai character ด้วย pythainlp.util

ตรวจสอบว่าใช่ตัวอักษรภาษาไทยหรือไม่

import pythainlp.util
print(pythainlp.util.isthai("๔"))
print(pythainlp.util.isthai("ก"))
print(pythainlp.util.isthai("(ก.พ.)"))
print(pythainlp.util.isthai("(ก.พ.)", ignore_chars=".()"))
True
True
False
True

counthai() returns proportion of Thai characters in the text. It will ignore non-alphabets by default.

import pythainlp.util
print(pythainlp.util.countthai("วันอาทิตย์ที่ 24 มีนาคม 2562"))
print(pythainlp.util.countthai("วันอาทิตย์ที่ 24 มีนาคม 2562", ignore_chars=""))
print(pythainlp.util.countthai("วันอาทิตย์ที่ 24 มีนาคม 2562", ignore_chars=" "))
100.0
67.85714285714286   # ตัวอักษรทั้งหมด/ตัวอักษรไทย (28/19=67.857)
76.0                # ตัวอักษรทั้งหมดยกเว้นช่องว่าง/ตัวอักษรไทย (25/19=76)
import pythainlp.util
print(pythainlp.util.countthai("อาทิตย์ 24"))
print(pythainlp.util.countthai("อาทิตย์ 24", ignore_chars=""))
print(pythainlp.util.countthai("อาทิตย์ 24", ignore_chars=" "))
100.0
70.0                # 10/7=70
77.77777777777779   #  9/7=77.777

การเรียงลำดับ list ภาษาไทย

from pythainlp.util import collate
thai_words = ["ค้อน", "กระดาษ", "กรรไกร", "ไข่", "ผ้าไหม"]
print(collate(thai_words))
print(collate(thai_words, reverse=True))
['กรรไกร', 'กระดาษ', 'ไข่', 'ค้อน', 'ผ้าไหม']
['ผ้าไหม', 'ค้อน', 'ไข่', 'กระดาษ', 'กรรไกร']

ถ้ามีภาษาอังกฤษ ภาษาอังกฤษจะมาก่อนภาษาไทย

from pythainlp.util import collate
thai_words = ["ค้อน", "กระดาษ", "กรรไกร", "ไข่", "ผ้าไหม", "Dog", "Cat"]
print(collate(thai_words))
print(collate(thai_words, reverse=True))
['Cat', 'Dog', 'กรรไกร', 'กระดาษ', 'ไข่', 'ค้อน', 'ผ้าไหม']
['ผ้าไหม', 'ค้อน', 'ไข่', 'กระดาษ', 'กรรไกร', 'Dog', 'Cat']

Date/Time Format

import datetime
from pythainlp.util import thai_strftime

fmt = "%Aที่ %-d %B พ.ศ. %Y เวลา %H:%M น. (%a %d-%b-%y)"
date = datetime.datetime(1976, 10, 6, 1, 40)

print(thai_strftime(date, fmt))
print(thai_strftime(date, "%d %b %y"))
print(thai_strftime(date, "%d %b %Y"))
วันพุธที่ 6 ตุลาคม พ.ศ. 2519 เวลา 01:40 น. (พ 06-ต.ค.-19)
06 ต.ค. 19
06 ต.ค. 2519