ทำ PyThaiNLP API ด้วย Python Flask บน Heroku
โปรเจคนี้ชื่อว่า PyThaiAPI โดยจะนำตัวตัดคำของ PyThaiNLP มาสร้างเป็น REST API ด้วย Python Flask จากนั้นนำไป Deploy ให้ใช้กันได้แบบฟรี ๆ บน Heroku server
ไม่ขอเกริ่นมาก มาเริ่มดูวิธีทำกันเลย โดยจะมีทั้งหมด 5 ขั้นตอนดังนี้ได้แก่
- Set up the project
- Using PyThaiNLP
- Develop REST API using Flask
- Deploy the API using Heroku
- Using the PyThaiAPI
1. Set up the project
เริ่มต้นโปรเจคด้วย virtualenv และติดตั้ง dependencies จาก requirements.txt
pip install virtualenv
virtualenv venv
source venv/bin/activate
pip install -r requirements.txt
2. Using PyThaiNLP
ในโปรเจคนี้จะอ้างอิงจาก PyThaiNLP เวอร์ชั่น 2.1
Thai word segmentation
pythainlp.tokenize.word_tokenize()
โดยตัว word_tokenize จะมีการใส่ input params ดังนี้
- text: ข้อความที่ต้องการจะตัดคำ
- engine: ชื่อของ engine โดยมี newmm (dictionary-based, Maximum Matching + Thai Character Cluster) เป็นค่า default
- keep_whitespace: True/False ในการตัด whitespace
- ส่วน custom_dict จะไม่ได้ implement ใน tutorial นี้ครับ
สามารถเข้าไปดูวิธีใช้ word_tokenize เพิ่มเติมได้ที่ Link ข้างล่าง
3. Develop REST API using Flask
ขั้นตอนต่อไป คือการทำ REST API สำหรับการเรียกใช้ PyThaiNLP ผ่าน HTTP request
Directory Structure
+ pythaiapi
- __init__.py
- apis.py
- app.py
- Procfile
- requirements.txt
API ตัวนี้จะมีการออกแบบให้เรียกใช้ได้เหมือนกับ PyThaiNLP มากที่สุด โดยจะตั้ง endpoints และ params ดังนี้
Method: POST
Endpoint: /api/word_tokenize
Header: "Content-Type: application/json"
Params: ?engine=newmm&keep_whitespace=false
Body: {"text": "ทดสอบการตัดคำ"}
Procfile: เพื่อประกาศ command ในการ start app
web: gunicorn app:app --log-file -
โดยมีการกำหนด web:
ข้างหน้าเพื่อให้ process ไป attached ที่ HTTP routing stack ของ Heroku ในการรับ traffic และกำหนด gunicorn process ซึ่งเป็น “WSGI HTTP Server” ที่หน้าที่เป็นตัวกลางระหว่าง Web server เช่น Nginx และ application ของเรา (อ่านเพิ่มเติม python-guincorn)
4. Deploy the API using Heroku
Heroku คือ Cloud Application ที่เป็น Platform as a service (PaaS) ที่ช่วยให้ developers สามารถรันแอพพลิเคชั่นได้บนคลาวด์
เริ่มสร้าง Heroku app โดยไปที่ https://dashboard.heroku.com/ แล้ว Create new app จากนั้นไปที่ deploy tab ของ app เราเพื่อ push code ขึ้นไปรันบน cloud
ในที่นี้เราจะใช้วิธี Connect ผ่าน GitHub และใช้ Automatic deploys เมื่อเรา push code ไปที่ branch master
เมื่อ Deploy แล้วสามารถเข้าไปดู Build logs ได้ที่ Activity tab ก็จะขึ้นโชว์ logs หน้าตาประมาณนี้ โดยที่ https://pythaiapi.herokuapp.com/ คือ Domain ในการเรียกใช้ App เราได้แล้วนั่นเอง 🎉
-----> Launching...
Released v1
https://pythaiapi.herokuapp.com/ deployed to Heroku
5. Using the PyThaiAPI
ขั้นตอนสุดท้ายมาลองเรียก pythaiapi ผ่าน cURL command กัน
curl -X POST \
'https://pythaiapi.herokuapp.com/api/word_tokenize?engine=attacut' \
-H 'Content-Type: application/json' \
-d '{"text":"ทดสอบภาษาไทย"}' | json_pp
ก็จะได้ผลลัพธ์การตัดคำตามตัวอย่างข้างบน .. เพียงเท่านี้เราก็จะสามารถมี Backend services อื่น ๆ สามารถเรียกใช้ NLP engines ของ PyThaiNLP ได้ผ่าน REST API ครับ