-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrefactor.sh
More file actions
executable file
·1399 lines (1145 loc) · 39.3 KB
/
Copy pathrefactor.sh
File metadata and controls
executable file
·1399 lines (1145 loc) · 39.3 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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# LINE Bot 失智症分析系統 - 修復版一鍵優化重構腳本
# 適用於 Replit 環境
set -e # 遇到錯誤立即停止
echo "🚀 LINE Bot 失智症分析系統 - 一鍵優化開始"
echo "=================================="
# 檢查當前環境
check_environment() {
echo "📋 檢查運行環境..."
# 檢查 Python 版本
python_version=$(python --version 2>&1 || python3 --version 2>&1)
echo "Python 版本: $python_version"
# 檢查記憶體使用(如果 psutil 可用)
python -c "
try:
import psutil
mem = psutil.virtual_memory()
print(f'📊 記憶體使用: {mem.percent:.1f}% ({mem.used/1024/1024:.0f}MB/{mem.total/1024/1024:.0f}MB)')
if mem.percent > 80:
print('⚠️ 記憶體使用過高,建議重啟 Replit')
except ImportError:
print('📊 記憶體監控模組未安裝')
" 2>/dev/null || echo "📊 無法檢查記憶體使用"
echo "✅ 環境檢查完成"
}
# 備份原始文件
backup_original() {
echo "💾 備份原始文件..."
if [[ ! -d "backup" ]]; then
mkdir backup
fi
# 備份主要文件
for file in *.py; do
if [[ -f "$file" ]]; then
cp "$file" "backup/${file}.$(date +%Y%m%d_%H%M%S).bak"
echo "備份: $file"
fi
done
echo "✅ 備份完成"
}
# 創建新的目錄結構
create_directory_structure() {
echo "📁 創建新目錄結構..."
# 創建主要目錄
directories=(
"api"
"api/core"
"api/modules"
"api/services"
"api/models"
"flex"
"flex/templates"
"flex/builders"
"flex/components"
"data"
"data/prompts"
"data/vectors"
"config"
"tests"
"scripts"
"logs"
)
for dir in "${directories[@]}"; do
mkdir -p "$dir"
touch "$dir/__init__.py" 2>/dev/null || true
echo "創建: $dir/"
done
echo "✅ 目錄結構創建完成"
}
# 創建配置文件
create_config_files() {
echo "⚙️ 創建配置文件..."
# config/settings.py
cat > config/settings.py << 'EOF'
from pydantic import BaseSettings, validator
from typing import Optional
import os
class Settings(BaseSettings):
# LINE Bot 設定
line_channel_access_token: str = ""
line_channel_secret: str = ""
# Google AI 設定
aistudio_api_key: str = ""
# 服務設定
api_port: int = 8000
webhook_port: int = 8002
debug: bool = False
# 安全設定
rate_limit_per_minute: int = 60
max_input_length: int = 1000
# Replit 最佳化
memory_limit_mb: int = 400
enable_memory_monitor: bool = True
@validator('max_input_length')
def validate_input_length(cls, v):
return min(v, 2000) # Replit 記憶體限制
class Config:
env_file = ".env"
case_sensitive = False
# 單例模式
settings = Settings()
EOF
# api/core/config.py
cat > api/core/config.py << 'EOF'
from config.settings import settings
export = settings
EOF
# data/prompts/m1_prompts.yaml
cat > data/prompts/m1_prompts.yaml << 'EOF'
system_prompt: |
你是一個專業的失智症早期警訊分析專家。請根據用戶描述的行為或症狀,
分析是否符合失智症十大警訊,並提供專業建議。
analysis_prompt: |
用戶描述:{user_input}
請分析此描述是否符合以下失智症十大警訊:
M1-01: 記憶力減退影響生活
M1-02: 計劃事情或解決問題有困難
M1-03: 無法勝任原本熟悉的事務
M1-04: 對時間地點感到混淆
M1-05: 有困難理解視覺影像和空間關係
M1-06: 言語表達或書寫出現困難
M1-07: 東西擺放錯亂且失去回頭尋找的能力
M1-08: 判斷力變差或減弱
M1-09: 從工作或社交活動中退出
M1-10: 情緒和個性的改變
請以 JSON 格式回應分析結果。
categories:
M1-01:
name: "記憶力減退影響生活"
keywords: ["忘記", "記不住", "重複問", "記憶", "健忘"]
EOF
echo "✅ 配置文件創建完成"
}
# 創建核心模組
create_core_modules() {
echo "🔧 創建核心模組..."
# api/core/security.py
cat > api/core/security.py << 'EOF'
import hmac
import hashlib
import base64
import re
from fastapi import HTTPException
from api.core.config import settings
def verify_line_signature(body: bytes, signature: str) -> bool:
"""驗證 LINE webhook 簽名"""
if not signature or not settings.line_channel_secret:
return True # 開發模式跳過驗證
hash_digest = hmac.new(
settings.line_channel_secret.encode('utf-8'),
body,
hashlib.sha256
).digest()
expected_signature = base64.b64encode(hash_digest).decode()
if not hmac.compare_digest(signature, expected_signature):
raise HTTPException(401, "Invalid LINE signature")
return True
def sanitize_input(user_input: str) -> str:
"""清理和驗證用戶輸入"""
if not user_input or not user_input.strip():
raise HTTPException(400, "輸入內容不能為空")
user_input = user_input.strip()
if len(user_input) > settings.max_input_length:
raise HTTPException(400, f"輸入內容過長,限制 {settings.max_input_length} 字元")
# 移除潛在危險字符但保留中文
user_input = re.sub(r'[<>"\'\&\|\;]', '', user_input)
return user_input
def check_memory_usage():
"""檢查記憶體使用(Replit 優化)"""
if not settings.enable_memory_monitor:
return
try:
import psutil
import gc
memory = psutil.virtual_memory()
if memory.percent > 85:
gc.collect() # 強制垃圾回收
print(f"⚠️ 記憶體使用過高: {memory.percent:.1f}%,已執行垃圾回收")
if memory.percent > 95:
raise HTTPException(503, "系統記憶體不足,請稍後再試")
except ImportError:
pass # psutil 不可用時跳過
EOF
# api/core/exceptions.py
cat > api/core/exceptions.py << 'EOF'
from fastapi import HTTPException
class AnalysisError(Exception):
"""分析錯誤"""
pass
class GeminiAPIError(Exception):
"""Gemini API 錯誤"""
pass
class FlexMessageError(Exception):
"""Flex Message 建構錯誤"""
pass
def handle_analysis_error(error: Exception) -> HTTPException:
"""統一錯誤處理"""
if isinstance(error, GeminiAPIError):
return HTTPException(503, "AI 分析服務暫時無法使用,請稍後再試")
elif isinstance(error, FlexMessageError):
return HTTPException(500, "回應格式建構失敗")
else:
return HTTPException(500, "系統處理錯誤,請稍後再試")
EOF
echo "✅ 核心模組創建完成"
}
# 創建分析模組
create_analysis_modules() {
echo "🧠 創建分析模組..."
# api/modules/base_analyzer.py
cat > api/modules/base_analyzer.py << 'EOF'
from abc import ABC, abstractmethod
from typing import Dict, Any, List
from pydantic import BaseModel
import yaml
from pathlib import Path
class AnalysisResult(BaseModel):
matched_categories: List[str] = []
category_name: str = ""
confidence: float = 0.0
severity: int = 1 # 1-5
user_description: str = ""
normal_aging: str = ""
warning_sign: str = ""
recommendations: List[str] = []
require_medical_attention: bool = False
disclaimer: str = "此分析僅供參考,請諮詢專業醫師進行正式評估"
class BaseAnalyzer(ABC):
def __init__(self, gemini_service=None):
self.gemini_service = gemini_service
self.module_name = self.__class__.__name__.replace('Analyzer', '').lower()
self.prompts = self._load_prompts()
def _load_prompts(self) -> Dict[str, Any]:
"""載入 Prompt 模板"""
try:
prompt_file = Path(f"data/prompts/{self.module_name}_prompts.yaml")
if prompt_file.exists():
with open(prompt_file, 'r', encoding='utf-8') as f:
return yaml.safe_load(f)
except Exception as e:
print(f"載入 prompt 失敗: {e}")
return {}
@abstractmethod
async def analyze(self, user_input: str) -> AnalysisResult:
"""分析用戶輸入"""
pass
def format_prompt(self, user_input: str, **kwargs) -> str:
"""格式化 Prompt"""
template = self.prompts.get('analysis_prompt', '')
return template.format(user_input=user_input, **kwargs)
EOF
# api/modules/m1_analyzer.py
cat > api/modules/m1_analyzer.py << 'EOF'
import json
import re
from typing import Dict, Any
from api.modules.base_analyzer import BaseAnalyzer, AnalysisResult
from api.core.exceptions import AnalysisError, GeminiAPIError
class M1Analyzer(BaseAnalyzer):
"""M1 失智症十大警訊分析器"""
WARNING_CATEGORIES = {
'M1-01': '記憶力減退影響生活',
'M1-02': '計劃事情或解決問題有困難',
'M1-03': '無法勝任原本熟悉的事務',
'M1-04': '對時間地點感到混淆',
'M1-05': '有困難理解視覺影像和空間關係',
'M1-06': '言語表達或書寫出現困難',
'M1-07': '東西擺放錯亂且失去回頭尋找的能力',
'M1-08': '判斷力變差或減弱',
'M1-09': '從工作或社交活動中退出',
'M1-10': '情緒和個性的改變'
}
async def analyze(self, user_input: str) -> AnalysisResult:
"""分析用戶輸入的失智症警訊"""
try:
# 格式化 prompt
prompt = self.format_prompt(user_input)
# 呼叫 Gemini API
if self.gemini_service and hasattr(self.gemini_service, 'configured') and self.gemini_service.configured:
response = await self.gemini_service.analyze(prompt)
return self._parse_gemini_response(response, user_input)
else:
# 備用:基於關鍵字的簡單分析
return self._keyword_analysis(user_input)
except Exception as e:
print(f"M1 分析錯誤: {e}")
# 發生錯誤時返回基本分析結果
return self._keyword_analysis(user_input)
def _parse_gemini_response(self, response: str, user_input: str) -> AnalysisResult:
"""解析 Gemini API 回應"""
try:
# 提取 JSON 部分
json_match = re.search(r'\{.*\}', response, re.DOTALL)
if json_match:
result_data = json.loads(json_match.group())
return AnalysisResult(**result_data)
else:
# JSON 解析失敗,使用備用分析
return self._keyword_analysis(user_input)
except json.JSONDecodeError:
return self._keyword_analysis(user_input)
def _keyword_analysis(self, user_input: str) -> AnalysisResult:
"""基於關鍵字的備用分析"""
# 簡化的關鍵字匹配邏輯
keywords_map = {
'M1-01': ['忘記', '記不住', '重複問', '記憶', '健忘'],
'M1-02': ['計劃', '解決', '困難', '想不出', '不會'],
'M1-03': ['不會', '做不到', '熟悉', '原本會'],
'M1-04': ['時間', '地點', '迷路', '混淆', '不知道'],
'M1-08': ['判斷', '決定', '選擇困難'],
'M1-10': ['情緒', '個性', '脾氣', '易怒', '憂鬱']
}
matched_categories = []
max_confidence = 0.3
for category, keywords in keywords_map.items():
if any(keyword in user_input for keyword in keywords):
matched_categories.append(category)
max_confidence = max(max_confidence, 0.6)
if not matched_categories:
matched_categories = ['M1-01'] # 預設分類
category_name = self.WARNING_CATEGORIES.get(matched_categories[0], '')
return AnalysisResult(
matched_categories=matched_categories,
category_name=category_name,
confidence=max_confidence,
severity=2,
user_description=user_input[:100] + ('...' if len(user_input) > 100 else ''),
normal_aging="隨著年齡增長,偶爾出現輕微的記憶問題是正常的",
warning_sign=f"觀察到的現象可能與 {category_name} 相關",
recommendations=[
"建議持續觀察相關症狀的變化",
"如症狀持續或加重,建議諮詢專業醫師",
"保持規律作息和適度運動"
],
require_medical_attention=max_confidence > 0.5
)
EOF
echo "✅ 分析模組創建完成"
}
# 創建服務層
create_services() {
echo "🔌 創建服務層..."
# api/services/gemini_service.py
cat > api/services/gemini_service.py << 'EOF'
try:
import google.generativeai as genai
GENAI_AVAILABLE = True
except ImportError:
GENAI_AVAILABLE = False
from api.core.config import settings
from api.core.exceptions import GeminiAPIError
import asyncio
class GeminiService:
def __init__(self):
if GENAI_AVAILABLE and settings.aistudio_api_key:
try:
genai.configure(api_key=settings.aistudio_api_key)
self.model = genai.GenerativeModel('gemini-pro')
self.configured = True
print("✅ Google Gemini 已配置")
except Exception as e:
self.configured = False
print(f"⚠️ Google Gemini 配置失敗: {e}")
else:
self.configured = False
if not GENAI_AVAILABLE:
print("⚠️ Google Generative AI 套件未安裝")
else:
print("⚠️ Google Gemini API Key 未設定")
async def analyze(self, prompt: str) -> str:
"""分析文本"""
if not self.configured:
raise GeminiAPIError("Gemini API 未配置")
try:
# 使用 asyncio 包裝同步 API
loop = asyncio.get_event_loop()
response = await loop.run_in_executor(
None,
lambda: self.model.generate_content(prompt)
)
return response.text
except Exception as e:
print(f"Gemini API 錯誤: {e}")
raise GeminiAPIError(f"API 呼叫失敗: {str(e)}")
def health_check(self) -> bool:
"""健康檢查"""
return self.configured
EOF
# api/services/analysis_service.py
cat > api/services/analysis_service.py << 'EOF'
from api.modules.m1_analyzer import M1Analyzer
from api.services.gemini_service import GeminiService
from api.core.security import sanitize_input, check_memory_usage
from api.core.exceptions import AnalysisError
class AnalysisService:
def __init__(self):
self.gemini_service = GeminiService()
self.analyzers = {
'm1': M1Analyzer(self.gemini_service)
}
async def analyze(self, module: str, user_input: str):
"""執行分析"""
# 記憶體檢查
check_memory_usage()
# 輸入清理
clean_input = sanitize_input(user_input)
# 取得分析器
analyzer = self.analyzers.get(module.lower())
if not analyzer:
raise AnalysisError(f"不支援的分析模組: {module}")
# 執行分析
result = await analyzer.analyze(clean_input)
return result
def get_available_modules(self):
"""取得可用模組"""
return list(self.analyzers.keys())
EOF
echo "✅ 服務層創建完成"
}
# 創建 Flex Message 系統
create_flex_system() {
echo "💬 創建 Flex Message 系統..."
# flex/builders/base_builder.py
cat > flex/builders/base_builder.py << 'EOF'
from typing import Dict, Any, List
class FlexBuilder:
def __init__(self):
self.message = {
"type": "flex",
"altText": "",
"contents": {
"type": "bubble",
"body": {
"type": "box",
"layout": "vertical",
"contents": []
}
}
}
def set_alt_text(self, text: str):
self.message["altText"] = text
return self
def add_header(self, title: str, subtitle: str = None):
header = {
"type": "text",
"text": title,
"weight": "bold",
"size": "xl",
"color": "#1DB446"
}
self.message["contents"]["body"]["contents"].append(header)
if subtitle:
subtitle_element = {
"type": "text",
"text": subtitle,
"size": "sm",
"color": "#666666",
"margin": "md"
}
self.message["contents"]["body"]["contents"].append(subtitle_element)
# 分隔線
separator = {
"type": "separator",
"margin": "xl"
}
self.message["contents"]["body"]["contents"].append(separator)
return self
def add_text_section(self, title: str, content: str, color: str = "#333333"):
section = {
"type": "box",
"layout": "vertical",
"margin": "lg",
"contents": [
{
"type": "text",
"text": title,
"weight": "bold",
"color": "#1DB446",
"margin": "md"
},
{
"type": "text",
"text": content,
"wrap": True,
"color": color,
"size": "sm",
"margin": "sm"
}
]
}
self.message["contents"]["body"]["contents"].append(section)
return self
def add_recommendations(self, recommendations: List[str]):
if not recommendations:
return self
rec_contents = []
for i, rec in enumerate(recommendations[:3]): # 限制3個建議
rec_contents.append({
"type": "text",
"text": f"{i+1}. {rec}",
"wrap": True,
"size": "sm",
"color": "#333333",
"margin": "sm"
})
section = {
"type": "box",
"layout": "vertical",
"margin": "lg",
"contents": [
{
"type": "text",
"text": "💡 建議事項",
"weight": "bold",
"color": "#1DB446",
"margin": "md"
}
] + rec_contents
}
self.message["contents"]["body"]["contents"].append(section)
return self
def add_footer(self):
footer = {
"type": "box",
"layout": "vertical",
"margin": "lg",
"contents": [
{
"type": "separator",
"margin": "md"
},
{
"type": "text",
"text": "⚠️ 此分析僅供參考,如有疑慮請諮詢專業醫師",
"wrap": True,
"color": "#888888",
"size": "xs",
"margin": "md"
}
]
}
self.message["contents"]["body"]["contents"].append(footer)
return self
def build(self) -> Dict[str, Any]:
return self.message
EOF
# flex/builders/m1_builder.py
cat > flex/builders/m1_builder.py << 'EOF'
from flex.builders.base_builder import FlexBuilder
from api.modules.base_analyzer import AnalysisResult
class M1FlexBuilder(FlexBuilder):
def build_analysis_result(self, result: AnalysisResult) -> dict:
# 設定替代文字
self.set_alt_text(f"失智症警訊分析:{result.category_name}")
# 標題
confidence_text = f"可信度: {result.confidence:.0%}"
self.add_header("🧠 失智症警訊分析", confidence_text)
# 用戶描述
if result.user_description:
self.add_text_section(
"🔸 描述內容",
result.user_description
)
# 分析結果
if result.category_name:
severity_emoji = ["", "🟢", "🟡", "🟠", "🔴", "🔴"][min(result.severity, 5)]
self.add_text_section(
f"{severity_emoji} 警訊類別",
f"{result.category_name}\n({', '.join(result.matched_categories)})"
)
# 正常老化對比
if result.normal_aging:
self.add_text_section(
"✅ 正常老化",
result.normal_aging,
"#2E7D32"
)
# 警訊說明
if result.warning_sign:
color = "#E65100" if result.require_medical_attention else "#F57C00"
self.add_text_section(
"⚠️ 警訊特徵",
result.warning_sign,
color
)
# 建議事項
self.add_recommendations(result.recommendations)
# 就醫提醒
if result.require_medical_attention:
self.add_text_section(
"🏥 重要提醒",
"建議盡快諮詢神經內科或精神科醫師進行詳細評估",
"#D32F2F"
)
# 免責聲明
self.add_footer()
return self.build()
def build_help_message(self) -> dict:
self.set_alt_text("失智症分析系統使用說明")
self.add_header("🤖 失智症分析助手", "使用說明")
self.add_text_section(
"📝 如何使用",
"直接描述觀察到的行為或症狀,例如:\n• 媽媽最近常重複問同樣的問題\n• 爸爸忘記回家的路\n• 奶奶不會用原本熟悉的家電"
)
self.add_text_section(
"🎯 分析範圍",
"本系統分析失智症十大警訊:\n• 記憶力問題\n• 計劃與解決問題困難\n• 熟悉事務執行困難\n• 時間地點混淆\n• 視覺空間問題等"
)
self.add_recommendations([
"詳細描述具體行為更有助於分析",
"持續記錄觀察到的變化",
"分析結果僅供參考,請諮詢專業醫師"
])
self.add_footer()
return self.build()
EOF
echo "✅ Flex Message 系統創建完成"
}
# 創建主程式
create_main_application() {
echo "🚀 創建主程式..."
# api/main.py
cat > api/main.py << 'EOF'
from fastapi import FastAPI, HTTPException, Request, Header
from fastapi.responses import JSONResponse
import json
import asyncio
from typing import Optional
from api.services.analysis_service import AnalysisService
from api.services.gemini_service import GeminiService
from api.core.security import verify_line_signature, check_memory_usage
from api.core.config import settings
from api.core.exceptions import handle_analysis_error
from flex.builders.m1_builder import M1FlexBuilder
# 初始化服務
app = FastAPI(
title="失智症分析 API",
description="LINE Bot 失智症早期警訊分析系統",
version="2.0.0"
)
analysis_service = AnalysisService()
flex_builder = M1FlexBuilder()
@app.get("/")
async def root():
return {"message": "失智症分析系統 API v2.0", "status": "running"}
@app.get("/health")
async def health_check():
"""健康檢查"""
try:
check_memory_usage()
gemini_status = analysis_service.gemini_service.health_check()
return {
"status": "healthy",
"gemini_configured": gemini_status,
"available_modules": analysis_service.get_available_modules()
}
except Exception as e:
return {"status": "unhealthy", "error": str(e)}
@app.post("/analyze/{module}")
async def analyze_input(module: str, request: Request):
"""分析用戶輸入"""
try:
body = await request.json()
user_input = body.get("user_input", "")
if not user_input:
raise HTTPException(400, "缺少 user_input 參數")
result = await analysis_service.analyze(module, user_input)
return result.dict()
except HTTPException:
raise
except Exception as e:
print(f"分析錯誤: {e}")
raise handle_analysis_error(e)
@app.post("/m1-flex")
async def m1_flex_analysis(request: Request):
"""M1 模組分析並回傳 Flex Message"""
try:
body = await request.json()
user_input = body.get("user_input", "")
if not user_input:
raise HTTPException(400, "缺少 user_input 參數")
# 執行分析
result = await analysis_service.analyze("m1", user_input)
# 建構 Flex Message
flex_message = flex_builder.build_analysis_result(result)
return {"flex_message": flex_message}
except HTTPException:
raise
except Exception as e:
print(f"M1 Flex 分析錯誤: {e}")
raise handle_analysis_error(e)
@app.post("/webhook")
async def line_webhook(
request: Request,
x_line_signature: Optional[str] = Header(None, alias="X-Line-Signature")
):
"""LINE Bot Webhook 端點"""
try:
body = await request.body()
# 驗證簽名(如果有設定)
if settings.line_channel_secret and x_line_signature:
verify_line_signature(body, x_line_signature)
# 解析請求
webhook_data = json.loads(body.decode('utf-8'))
events = webhook_data.get('events', [])
responses = []
for event in events:
if event.get('type') == 'message' and event.get('message', {}).get('type') == 'text':
response = await handle_line_message(event)
responses.append(response)
return {"responses": responses}
except HTTPException:
raise
except Exception as e:
print(f"Webhook 錯誤: {e}")
return JSONResponse(status_code=200, content={"status": "ok"})
async def handle_line_message(event):
"""處理 LINE 訊息事件"""
try:
user_message = event.get('message', {}).get('text', '').strip()
reply_token = event.get('replyToken')
if not user_message:
return {"error": "空訊息"}
# 特殊指令處理
if user_message.lower() in ['help', '幫助', '說明']:
flex_message = flex_builder.build_help_message()
return {
"replyToken": reply_token,
"messages": [flex_message]
}
# 一般分析
result = await analysis_service.analyze("m1", user_message)
flex_message = flex_builder.build_analysis_result(result)
return {
"replyToken": reply_token,
"messages": [flex_message]
}
except Exception as e:
print(f"處理 LINE 訊息錯誤: {e}")
# 回傳簡單錯誤訊息
return {
"replyToken": event.get('replyToken'),
"messages": [{
"type": "text",
"text": "抱歉,系統暫時無法處理您的請求,請稍後再試。"
}]
}
if __name__ == "__main__":
import uvicorn
print(f"🚀 啟動失智症分析 API 服務於端口 {settings.api_port}")
uvicorn.run(app, host="0.0.0.0", port=settings.api_port)
EOF
echo "✅ 主程式創建完成"
}
# 創建啟動腳本
create_startup_scripts() {
echo "📜 創建啟動腳本..."
# scripts/start_all.sh
cat > scripts/start_all.sh << 'EOF'
#!/bin/bash
echo "🚀 啟動失智症分析系統"
echo "======================"
# 檢查環境變數
if [[ -z "$LINE_CHANNEL_ACCESS_TOKEN" ]]; then
echo "⚠️ 警告: LINE_CHANNEL_ACCESS_TOKEN 未設定"
fi
if [[ -z "$AISTUDIO_API_KEY" ]]; then
echo "⚠️ 警告: AISTUDIO_API_KEY 未設定"
fi
# 記憶體檢查
python -c "
try:
import psutil
mem = psutil.virtual_memory()
print(f'📊 啟動前記憶體使用: {mem.percent:.1f}%')
if mem.percent > 70:
print('⚠️ 記憶體使用偏高,建議重啟 Replit')
except ImportError:
print('📊 記憶體監控模組未安裝')
" 2>/dev/null || echo "📊 無法檢查記憶體使用"
# 安裝依賴(如果需要)
if [[ -f "requirements.txt" ]]; then
echo "📦 檢查依賴套件..."
pip install -r requirements.txt --quiet
fi
# 啟動 API 服務
echo "🚀 啟動 API 服務..."
python -m uvicorn api.main:app --host 0.0.0.0 --port 8000 --reload &
API_PID=$!
# 等待服務啟動
sleep 3
# 健康檢查
echo "🔍 執行健康檢查..."
curl -s http://localhost:8000/health 2>/dev/null | python -m json.tool 2>/dev/null || echo "健康檢查: API 服務可能尚未完全啟動"
echo "✅ 系統啟動完成"
echo "📝 API 文件: http://localhost:8000/docs"
echo "🔧 管理介面: http://localhost:8000"
# 等待中斷信號
trap "echo '🛑 正在關閉服務...'; kill $API_PID 2>/dev/null; exit" INT TERM
wait $API_PID
EOF
chmod +x scripts/start_all.sh
# scripts/memory_monitor.sh
cat > scripts/memory_monitor.sh << 'EOF'
#!/bin/bash
echo "📊 記憶體監控工具 (按 Ctrl+C 停止)"
echo "===================================="
while true; do
python -c "
try:
import psutil
import datetime
import gc
mem = psutil.virtual_memory()
cpu = psutil.cpu_percent(interval=1)
now = datetime.datetime.now().strftime('%H:%M:%S')
print(f'[{now}] 記憶體: {mem.percent:.1f}% ({mem.used/1024/1024:.0f}MB/{mem.total/1024/1024:.0f}MB) CPU: {cpu:.1f}%')
if mem.percent > 85:
print('⚠️ 記憶體使用過高,執行垃圾回收...')
gc.collect()
if mem.percent > 95:
print('🚨 記憶體嚴重不足!')
except ImportError:
print('psutil 未安裝,無法監控記憶體')
exit(1)
except KeyboardInterrupt:
print('監控已停止')
exit(0)