File size: 3,039 Bytes
e08e848
 
3fe3d6e
 
c1788ff
 
 
3fe3d6e
e08e848
3fe3d6e
e08e848
 
 
3fe3d6e
9396632
3fe3d6e
 
e08e848
 
 
9396632
3fe3d6e
 
9396632
 
3fe3d6e
c1788ff
3fe3d6e
 
 
 
 
 
 
 
 
 
9396632
 
3fe3d6e
e08e848
 
 
3fe3d6e
e08e848
3fe3d6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e08e848
3fe3d6e
e08e848
3fe3d6e
e08e848
3fe3d6e
e08e848
3fe3d6e
e08e848
 
9396632
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import os
import threading
import uvicorn
from fastapi import FastAPI, Request, HTTPException, Header
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage
from model import classify_esi  # นำเข้าโมเดลสำหรับจัดอันดับ ESI

# Load environment variables
LINE_ACCESS_TOKEN = os.getenv("LINE_ACCESS_TOKEN")
LINE_CHANNEL_SECRET = os.getenv("LINE_CHANNEL_SECRET")

# Initialize FastAPI
app = FastAPI()

# Initialize LINE SDK
line_bot_api = LineBotApi(LINE_ACCESS_TOKEN)
handler = WebhookHandler(LINE_CHANNEL_SECRET)

@app.get("/")
async def root():
    return {"message": "Triage Bot is running for the ER of San Pa Tong Hospital!"}

@app.post("/webhook")
async def webhook(request: Request, x_line_signature: str = Header(None)):
    if not x_line_signature:
        raise HTTPException(status_code=400, detail="Missing X-Line-Signature")

    body = await request.body()
    body_text = body.decode("utf-8")

    try:
        handler.handle(body_text, x_line_signature)
    except InvalidSignatureError:
        raise HTTPException(status_code=400, detail="Invalid signature")

    return {"status": "OK"}

# Event handler for messages
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    user_message = event.message.text
    esi_level = classify_esi(user_message)  # ใช้โมเดล AI วิเคราะห์ ESI

    # แปลงระดับ ESI เป็นคำแนะนำ
    response_text = get_triage_response(esi_level)

    # ใช้ threading เพื่อให้ bot ตอบกลับทันที
    threading.Thread(target=reply_message, args=(event.reply_token, response_text)).start()

def reply_message(reply_token, message):
    try:
        line_bot_api.reply_message(reply_token, TextSendMessage(text=message))
    except Exception as e:
        print(f"Error sending reply: {e}")

def get_triage_response(esi_level):
    """
    รับค่า ESI (1-5) และแปลงเป็นข้อความแนะนำให้ผู้ป่วย
    """
    if esi_level in [1, 2]:
        return "🚑 อาการของคุณรุนแรง ควรรีบไปห้องฉุกเฉินทันที!"
    elif esi_level == 3:
        return "🏥 คุณควรพบแพทย์เร็วที่สุดเพื่อตรวจสอบเพิ่มเติม"
    elif esi_level in [4, 5]:
        return "😊 อาการของคุณสามารถรอพบแพทย์ที่ OPD ในวันพรุ่งนี้เช้าได้"
    else:
        return "❓ ไม่สามารถประเมินได้ กรุณาลองอธิบายอาการให้ละเอียดขึ้น"

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)