PinHsuan commited on
Commit
f95ab6b
·
verified ·
1 Parent(s): 01c5338

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -9
app.py CHANGED
@@ -6,7 +6,6 @@ import os
6
  import joblib
7
  from model import DualStreamTransformer, ArcMarginProduct
8
 
9
-
10
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
  FOLD = 5
12
  MODEL_PATH = f"best_model_fold_{FOLD}.pt"
@@ -17,26 +16,105 @@ metric_fc = ArcMarginProduct(32, 2).to(DEVICE)
17
 
18
  if os.path.exists(MODEL_PATH):
19
  checkpoint = torch.load(MODEL_PATH, map_location=DEVICE)
20
- model.load_state_dict(checkpoint['model'])
21
- metric_fc.load_state_dict(checkpoint['fc'])
22
  model.eval()
23
- print(" Model loaded successfully")
24
 
25
  scaler_ccmq = joblib.load(f"scaler_ccmq_fold_{FOLD}.pkl")
26
  scaler_osdi = joblib.load(f"scaler_osdi_fold_{FOLD}.pkl")
27
 
28
  def analyze_and_predict(*all_answers):
29
-
30
- print(f"DEBUG: Received answers count = {len(all_answers)}")
31
-
32
  ccmq_map = {"總是": 5, "經常": 4, "有時": 3, "很少": 2, "沒有": 1}
33
  osdi_map = {"總是": 4, "經常": 3, "一半一半": 2, "偶而": 1, "完全不曾": 0}
34
 
35
  try:
36
-
37
  x1_vals = [ccmq_map.get(a, 1) for a in all_answers[:24]]
38
  x2_vals = [osdi_map.get(a, 0) for a in all_answers[24:34]]
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  x1_raw = np.array([x1_vals])
41
  x2_raw = np.array([x2_vals])
42
 
@@ -75,7 +153,7 @@ def analyze_and_predict(*all_answers):
75
  None
76
  )
77
 
78
- # --- UI 介面 ---
79
  with gr.Blocks() as demo:
80
  gr.Markdown("# 中醫 AI 診斷系統")
81
 
 
6
  import joblib
7
  from model import DualStreamTransformer, ArcMarginProduct
8
 
 
9
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10
  FOLD = 5
11
  MODEL_PATH = f"best_model_fold_{FOLD}.pt"
 
16
 
17
  if os.path.exists(MODEL_PATH):
18
  checkpoint = torch.load(MODEL_PATH, map_location=DEVICE)
19
+ model.load_state_dict(checkpoint['model'], strict=False)
20
+ metric_fc.load_state_dict(checkpoint['fc'], strict=False)
21
  model.eval()
22
+
23
 
24
  scaler_ccmq = joblib.load(f"scaler_ccmq_fold_{FOLD}.pkl")
25
  scaler_osdi = joblib.load(f"scaler_osdi_fold_{FOLD}.pkl")
26
 
27
  def analyze_and_predict(*all_answers):
 
 
 
28
  ccmq_map = {"總是": 5, "經常": 4, "有時": 3, "很少": 2, "沒有": 1}
29
  osdi_map = {"總是": 4, "經常": 3, "一半一半": 2, "偶而": 1, "完全不曾": 0}
30
 
31
  try:
 
32
  x1_vals = [ccmq_map.get(a, 1) for a in all_answers[:24]]
33
  x2_vals = [osdi_map.get(a, 0) for a in all_answers[24:34]]
34
 
35
+ x1_scaled = scaler_ccmq.transform(np.array([x1_vals]))
36
+ x2_scaled = scaler_osdi.transform(np.array([x2_vals]))
37
+
38
+ sx1 = torch.tensor(x1_scaled, dtype=torch.float32).to(DEVICE)
39
+ sx2 = torch.tensor(x2_scaled, dtype=torch.float32).to(DEVICE)
40
+
41
+ with torch.no_grad():
42
+ feats = model(sx1, sx2)
43
+ logits = metric_fc.predict(feats)
44
+ probs = torch.softmax(logits, dim=1)
45
+ pred_idx = torch.argmax(probs, dim=1).item()
46
+ conf = probs[0, pred_idx].item()
47
+ except Exception as e:
48
+ raise gr.Error(f"推論出錯: {e}")
49
+
50
+ res_label = " 乾眼風險 (SJS/DES)" if pred_idx == 1 else " 正常/健康"
51
+ table_data = [[f"項目 {i+1}", str(all_answers[i]), "OK"] for i in range(len(all_answers))]
52
+
53
+
54
+ return (
55
+ gr.update(visible=False),
56
+ gr.update(visible=True),
57
+ f"### {res_label}",
58
+ f"AI 推論成功!診斷信心度為 {conf:.2%}。分析已整合 CCMQ 體質與 OSDI 臨床特徵。",
59
+ {"Risk": conf if pred_idx==1 else 1-conf, "Healthy": 1 - (conf if pred_idx==1 else 1-conf)},
60
+ table_data
61
+ )
62
+
63
+ with gr.Blocks(css=".scroll-box { height: 400px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; }") as demo:
64
+ gr.Markdown("# 中醫 AI 多模態診斷系統")
65
+
66
+
67
+ with gr.Column(visible=True) as input_area:
68
+ with gr.Row():
69
+ with gr.Column():
70
+ gr.Markdown("#### Step 1: CCMQ 體質量表")
71
+ with gr.Group(elem_classes="scroll-box"):
72
+ ccmq_labels = ["惡寒惡風", "自汗", "胸悶腹脹","咽喉痰梗感","多愁善感","易受驚","面部暗沉","黑眼圈","健忘","唇色暗","身熱、面熱","膚乾口乾","唇紅","便祕","兩顴紅","眼乾澀","四肢冷","惡寒、腰膝冷","飲冷腹瀉","口苦口臭","帶下色黃/下陰潮濕","鼻塞流涕","變天咳喘","過敏"]
73
+ all_ccmq = [gr.Radio(["總是", "經常", "有時", "很少", "沒有"], label=f"{i+1}. {txt}", value="沒有") for i, txt in enumerate(ccmq_labels)]
74
+
75
+ with gr.Column():
76
+ gr.Markdown("#### Step 2: OSDI 症狀量表")
77
+ with gr.Group(elem_classes="scroll-box"):
78
+ osdi_labels = ["1. 對光敏感", "2. 眼睛疼痛", "3. 視線模糊", "4. 視力減退", "5. 閱讀限制", "6. 夜間駕駛", "7. 電腦操作", "8. 觀看電視", "9. 刮風不適", "10. 空調不適"]
79
+ all_osdi = [gr.Radio(["總是", "經常", "一半一半", "偶而", "完全不曾"], label=txt, value="完全不曾") for txt in osdi_labels]
80
+
81
+ submit_btn = gr.Button("提交診斷並生成報告", variant="primary", size="lg")
82
+
83
+
84
+ with gr.Column(visible=False) as result_area:
85
+ gr.Markdown("### AI 診斷分析報告")
86
+ res_title = gr.Markdown("### 結論加載中...")
87
+ with gr.Row():
88
+ with gr.Column():
89
+ res_prob = gr.Label(label="預測機率分佈")
90
+ res_desc = gr.Markdown("報告詳情...")
91
+ with gr.Column():
92
+ res_table = gr.Dataframe(headers=["項目", "回答", "狀態"], interactive=False)
93
+
94
+ reset_btn = gr.Button("重新開始測驗", variant="secondary")
95
+
96
+ all_inputs = all_ccmq + all_osdi
97
+
98
+ submit_btn.click(
99
+ fn=analyze_and_predict,
100
+ inputs=all_inputs,
101
+ outputs=[input_area, result_area, res_title, res_desc, res_prob, res_table]
102
+ )
103
+
104
+ reset_btn.click(
105
+ fn=lambda: [gr.update(visible=True), gr.update(visible=False)] + ["沒有"]*24 + ["完全不曾"]*10,
106
+ outputs=[input_area, result_area] + all_inputs
107
+ )
108
+
109
+ if __name__ == "__main__":
110
+
111
+ demo.launch(
112
+ ssr_mode=False,
113
+ show_api=False,
114
+ quiet=True
115
+ ) x1_vals = [ccmq_map.get(a, 1) for a in all_answers[:24]]
116
+ x2_vals = [osdi_map.get(a, 0) for a in all_answers[24:34]]
117
+
118
  x1_raw = np.array([x1_vals])
119
  x2_raw = np.array([x2_vals])
120
 
 
153
  None
154
  )
155
 
156
+
157
  with gr.Blocks() as demo:
158
  gr.Markdown("# 中醫 AI 診斷系統")
159