---
# System prepended metadata

title: LINEBOT 機器學習
tags: [Python]

---

## 環境建置
#### 安裝line-bot 相依套件
```
$ pip install flask
$ pip3 uninstall line-bot-sdk ; pip3 install line-bot-sdk==2.4.2
$ pip3 list | grep line-bot-sdk
$ pip3 install line-bot-sdk
```
#### 下載ngrok
[下載 ngrok，啟動 ngrok 拿到 public IP](https://ngrok.com/download)

![image](https://hackmd.io/_uploads/HkbR34lhT.png)

```
$ choco install ngrok
$ ngrok config add-authtoken 2bOZ7jzXiLFty6tOu5N618DC420_5WXNFMAqihwzQP8ZcmuT
$ ngrok http 5000 # 開啟 port 5000
```

### Linebot 應聲蟲
```python!
from flask import Flask, request
from linebot import LineBotApi, WebhookHandler
from linebot.models import TextSendMessage   # 載入 TextSendMessage 模組
import json

app = Flask(__name__)

CHANNEL_SECRET = "4cbd4aa79f0b29b50a1a60bf4a7cc1fd"
CHANNEL_ACCESS_TOKEN = "eiASFhlCUqN0dprNRynpI3n6bQgUSS8rl+ZtqAcW8aMGc8hJwCQ8r7fSYjn4gKtFNIU9m+goG64S8sx94CX1Jg2fkp5vR9zaj1Q7mHr7TWuj3F4xQ4NAV4qUlr4BE2C3oG+TMzwlAPtfLP7eviatfgdB04t89/1O/w1cDnyilFU="

@app.route("/", methods=['GET'])
def home():
    return "Hi"

@app.route("/", methods=['POST'])
def linebot():
    body = request.get_data(as_text=True)
    json_data = json.loads(body)
    print(json_data)
    try:
        line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
        handler = WebhookHandler(CHANNEL_SECRET)
        signature = request.headers['X-Line-Signature']
        handler.handle(body, signature)
        tk = json_data['events'][0]['replyToken']         # 取得 reply token
        msg = json_data['events'][0]['message']['text']   # 取得使用者發送的訊息
        text_message = TextSendMessage(text = msg)#TextSendMessage(text=msg)          # 設定回傳同樣的訊息
        
        line_bot_api.reply_message(tk,text_message)       # 回傳訊息
    except Exception as e:
        print('error: ' + str(e))
    return 'OK'

app.run(port="5000")
```
成果：
![20240219_Evelyn_linebot](https://hackmd.io/_uploads/BkiPaSl2p.png)

### 將Linebot掛上openAI
```
$ pip3 install opencv-python #安裝openAI
```
ai模組檔
```python!
# ai.py
import os
import openai
openai.api_key = "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"

def chat(msg):
  completion = openai.chat.completions.create(
    model="gpt-4",
    messages=[
      {"role": "system", "content": "你是世界上最優秀的心理諮商師。"} ,
      {"role": "system", "content": "一律使用正體中文回答。"} ,
      {"role": "user", "content": msg}
    ]
  )

  return completion.choices[0].message.content
if __name__ == "__main__":
    print(chat("Hello"))
```
需要先執行ai檔，沒有錯誤訊息即可執行主程式

主程式：
```python!
from flask import Flask, request
from linebot import LineBotApi, WebhookHandler
from linebot.models import TextSendMessage   # 載入 TextSendMessage 模組
import json
from ai import chat

app = Flask(__name__)

CHANNEL_SECRET = "4cbd4aa79f0b29b50a1a60bf4a7cc1fd"
CHANNEL_ACCESS_TOKEN = "eiASFhlCUqN0dprNRynpI3n6bQgUSS8rl+ZtqAcW8aMGc8hJwCQ8r7fSYjn4gKtFNIU9m+goG64S8sx94CX1Jg2fkp5vR9zaj1Q7mHr7TWuj3F4xQ4NAV4qUlr4BE2C3oG+TMzwlAPtfLP7eviatfgdB04t89/1O/w1cDnyilFU="

@app.route("/", methods=['POST'])
def linebot():
    body = request.get_data(as_text=True)
    json_data = json.loads(body)
    print(json_data)
    try:
        line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
        handler = WebhookHandler(CHANNEL_SECRET)
        signature = request.headers['X-Line-Signature']
        handler.handle(body, signature)
        tk = json_data['events'][0]['replyToken']         # 取得 reply token
        msg = json_data['events'][0]['message']['text']   # 取得使用者發送的訊息
        text_message = TextSendMessage(text = chat(msg))#TextSendMessage(text=msg)          # 設定回傳同樣的訊息
        
        line_bot_api.reply_message(tk,text_message)       # 回傳訊息
    except Exception as e:
        print('error: ' + str(e))
    return 'OK'

app.run(port="5000")

```
1. 開啟 port 5000
2. 執行主程式
3. 前往LINEBOT--Webhook URL
![image](https://hackmd.io/_uploads/ry-4yYlnT.png)
![20240219_Evelyn_openai](https://hackmd.io/_uploads/ry6NyYe2p.png)

### 數位孿生

架構圖：
![image](https://hackmd.io/_uploads/rk9z09ghp.png)

1. 從圖檔或是 Camera 獲取圖片供給 Tensorflow 判斷
2. 判斷的結果儲存於 csv 檔中
3. 透過 LineBot 詢問工安狀況
4. LineBot 回答 N/M 次違規
5. 使用者判斷後，透過 LineBot 派送違規單


[於Transflow訓練模型](https://teachablemachine.withgoogle.com/train/image)

#### 安裝套件
```
$ sudo apt install unzip
$ pip3 install keras
$ pip3 install Pillow
$ pip3 install install opencv-python
```
Unzip model
```
$ unzip converted_keras.zip
```
主程式：
```python!
from flask import Flask, request
from linebot import LineBotApi, WebhookHandler
from linebot.models import TextSendMessage   # 載入 TextSendMessage 模組
import json
from llm import chat

app = Flask(__name__)

CHANNEL_SECRET = "4cbd4aa79f0b29b50a1a60bf4a7cc1fd"
CHANNEL_ACCESS_TOKEN = "eiASFhlCUqN0dprNRynpI3n6bQgUSS8rl+ZtqAcW8aMGc8hJwCQ8r7fSYjn4gKtFNIU9m+goG64S8sx94CX1Jg2fkp5vR9zaj1Q7mHr7TWuj3F4xQ4NAV4qUlr4BE2C3oG+TMzwlAPtfLP7eviatfgdB04t89/1O/w1cDnyilFU="

@app.route("/", methods=['POST'])
def linebot():
    body = request.get_data(as_text=True)
    json_data = json.loads(body)
    print(json_data)
    try:
        line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
        handler = WebhookHandler(CHANNEL_SECRET)
        signature = request.headers['X-Line-Signature']
        handler.handle(body, signature)
        tk = json_data['events'][0]['replyToken']         # 取得 reply token
        msg = json_data['events'][0]['message']['text']   # 取得使用者發送的訊息
        text_message = TextSendMessage(text = chat(msg))  # TextSendMessage(text=msg) # 設定回傳同樣的訊息
        
        line_bot_api.reply_message(tk,text_message)       # 回傳訊息
    except Exception as e:
        print('error: ' + str(e))
    return 'OK'

app.run(port="5000")
```