-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegrated_m1_m2_api.py
More file actions
383 lines (343 loc) · 12.7 KB
/
Copy pathintegrated_m1_m2_api.py
File metadata and controls
383 lines (343 loc) · 12.7 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
from fastapi import FastAPI, Request, HTTPException
from pydantic import BaseModel
import uvicorn
import os
from datetime import datetime
from m1_m2_integrated_rag import M1M2RAGEngine
# FastAPI 應用
app = FastAPI(
title="M1+M2 整合 RAG API",
description="支援失智症警訊(M1) + 病程階段分析(M2)",
version="2.1.0"
)
# 全域引擎
integrated_engine = None
@app.on_event("startup")
async def startup():
global integrated_engine
print("🚀 啟動 M1+M2 整合引擎...")
api_key = os.getenv('AISTUDIO_API_KEY')
integrated_engine = M1M2RAGEngine(api_key)
print("✅ M1+M2 整合 API 啟動成功")
class UserInput(BaseModel):
user_input: str
@app.get("/")
def root():
return {
"message": "M1+M2 整合 RAG API",
"version": "2.1.0",
"features": [
"🚨 M1: 失智症十大警訊識別",
"🏥 M2: 病程階段分析",
"🔍 智能語義檢索",
"📊 信心度評估"
],
"modules": {
"M1": "失智症警訊檢測",
"M2": "病程階段分析"
},
"total_chunks": len(integrated_engine.chunks) if integrated_engine else 0
}
@app.get("/health")
def health():
if not integrated_engine:
return {"status": "error", "message": "引擎未初始化"}
# 統計模組分布
m1_chunks = [c for c in integrated_engine.chunks if c.get("module_id") == "M1"]
m2_chunks = [c for c in integrated_engine.chunks if c.get("module_id") == "M2"]
return {
"status": "healthy",
"timestamp": datetime.now().isoformat(),
"engine_info": {
"total_chunks": len(integrated_engine.chunks),
"m1_chunks": len(m1_chunks),
"m2_chunks": len(m2_chunks),
"vocabulary_size": len(integrated_engine.vocabulary)
},
"capabilities": [
"warning_sign_detection",
"stage_analysis",
"semantic_search",
"confidence_scoring"
]
}
@app.post("/m1-flex")
def analyze_with_flex(request: UserInput):
"""主要分析端點 - 整合 M1+M2 功能"""
if not integrated_engine:
return {"error": "引擎未初始化"}
try:
# 使用整合引擎進行分析
result = integrated_engine.analyze_with_stage_detection(request.user_input)
# 生成增強版 Flex Message
flex_message = create_enhanced_flex_message(result, request.user_input)
return {
"flex_message": flex_message,
"analysis_data": result,
"enhanced": True,
"version": "2.1.0",
"timestamp": datetime.now().isoformat()
}
except Exception as e:
return {
"error": str(e),
"flex_message": create_error_flex_message(),
"enhanced": False
}
@app.post("/api/v1/analyze")
def detailed_analysis(request: UserInput):
"""詳細分析端點 - 返回完整分析資料"""
if not integrated_engine:
raise HTTPException(status_code=503, detail="引擎未初始化")
try:
result = integrated_engine.analyze_with_stage_detection(request.user_input)
return {
"query": request.user_input,
"analysis": result,
"modules_used": get_modules_used(result),
"timestamp": datetime.now().isoformat()
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
def get_modules_used(result):
"""分析使用了哪些模組"""
retrieved_chunks = result.get("retrieved_chunks", [])
modules = {}
for chunk in retrieved_chunks:
module_id = chunk.get("module_id", "unknown")
if module_id not in modules:
modules[module_id] = {
"count": 0,
"avg_similarity": 0,
"chunks": []
}
modules[module_id]["count"] += 1
modules[module_id]["chunks"].append({
"chunk_id": chunk.get("chunk_id"),
"title": chunk.get("title"),
"similarity": chunk.get("similarity_score", 0)
})
# 計算平均相似度
for module_id, info in modules.items():
if info["chunks"]:
avg_sim = sum(c["similarity"] for c in info["chunks"]) / len(info["chunks"])
info["avg_similarity"] = round(avg_sim, 4)
return modules
def create_enhanced_flex_message(result, user_input):
"""創建增強版 Flex Message(包含 M1+M2 資訊)"""
# 基本資訊
warning_code = result.get("matched_warning_code", "M1-GENERAL")
symptom_title = result.get("symptom_title", "需要關注的症狀")
confidence = result.get("confidence_level", "medium")
# M2 階段資訊
stage_info = result.get("stage_detection", {})
detected_stage = stage_info.get("detected_stage", "需要評估")
stage_confidence = stage_info.get("confidence", 0)
# 信心度顏色
confidence_colors = {
"high": "#28a745",
"medium": "#ffc107",
"low": "#dc3545"
}
confidence_color = confidence_colors.get(confidence, "#6c757d")
return {
"type": "flex",
"altText": f"失智症分析:{symptom_title}",
"contents": {
"type": "bubble",
"size": "kilo",
"header": {
"type": "box",
"layout": "vertical",
"contents": [{
"type": "text",
"text": "🧠 M1+M2 整合分析",
"weight": "bold",
"size": "lg",
"color": "#ffffff"
}],
"backgroundColor": "#005073",
"paddingAll": "15dp"
},
"body": {
"type": "box",
"layout": "vertical",
"contents": [
# 症狀標題
{
"type": "text",
"text": symptom_title,
"weight": "bold",
"size": "md",
"color": "#005073",
"wrap": True
},
{
"type": "separator",
"margin": "md"
},
# 使用者描述
{
"type": "box",
"layout": "vertical",
"margin": "md",
"contents": [
{
"type": "text",
"text": "📝 您的描述",
"size": "sm",
"weight": "bold",
"color": "#666666"
},
{
"type": "text",
"text": user_input,
"size": "sm",
"wrap": True,
"margin": "xs"
}
]
},
# M1 警訊分析
{
"type": "box",
"layout": "vertical",
"margin": "md",
"contents": [
{
"type": "text",
"text": f"🚨 警訊識別:{warning_code}",
"size": "sm",
"weight": "bold",
"color": "#dc3545"
},
{
"type": "text",
"text": f"信心程度:{confidence.upper()}",
"size": "xs",
"color": confidence_color,
"margin": "xs"
}
]
},
# M2 階段分析(如果有)
{
"type": "box",
"layout": "vertical",
"margin": "md",
"contents": [
{
"type": "text",
"text": f"🏥 病程階段:{detected_stage}",
"size": "sm",
"weight": "bold",
"color": "#007bff"
},
{
"type": "text",
"text": f"階段信心:{stage_confidence:.2f}",
"size": "xs",
"color": "#666666",
"margin": "xs"
}
]
} if stage_info else {
"type": "text",
"text": "🔍 未檢測到明確階段特徵",
"size": "xs",
"color": "#999999",
"margin": "md"
},
# 建議行動
{
"type": "box",
"layout": "vertical",
"margin": "lg",
"contents": [
{
"type": "text",
"text": "💡 建議行動",
"weight": "bold",
"size": "sm",
"color": "#005073"
},
{
"type": "text",
"text": result.get("action_suggestion", "建議諮詢專業醫療人員進行評估"),
"size": "xs",
"wrap": True,
"margin": "xs",
"color": "#666666"
}
]
}
],
"paddingAll": "15dp"
},
"footer": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "button",
"style": "secondary",
"height": "sm",
"action": {
"type": "message",
"label": "了解更多",
"text": f"請告訴我更多關於{detected_stage}失智症的資訊"
},
"flex": 1
},
{
"type": "button",
"style": "primary",
"height": "sm",
"action": {
"type": "uri",
"label": "專業諮詢",
"uri": "https://www.tada2002.org.tw/"
},
"flex": 1,
"margin": "sm"
}
],
"paddingAll": "15dp"
}
}
}
def create_error_flex_message():
"""錯誤時的 Flex Message"""
return {
"type": "flex",
"altText": "系統暫時無法分析",
"contents": {
"type": "bubble",
"body": {
"type": "box",
"layout": "vertical",
"contents": [{
"type": "text",
"text": "😅 分析服務暫時無法使用,請稍後再試。",
"wrap": True,
"size": "md"
}]
}
}
}
@app.get("/test")
def test_endpoint():
"""測試端點"""
return {
"message": "M1+M2 整合 API 測試",
"engine_ready": integrated_engine is not None,
"version": "2.1.0"
}
if __name__ == "__main__":
print("🚀 啟動 M1+M2 整合 RAG API...")
print("📋 功能:")
print(" 🚨 M1: 失智症警訊識別")
print(" 🏥 M2: 病程階段分析")
print(" 🔍 智能語義檢索")
print(" 📊 信心度評估")
uvicorn.run(app, host="0.0.0.0", port=8003, log_level="info")