PinHsuan commited on
Commit
d95eecf
·
verified ·
1 Parent(s): f283a81

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -65
app.py CHANGED
@@ -20,29 +20,20 @@ if os.path.exists(MODEL_PATH):
20
  model.load_state_dict(checkpoint['model'], strict=False)
21
  metric_fc.load_state_dict(checkpoint['fc'], strict=False)
22
  model.eval()
23
- print("Model weights loaded successfully.")
24
-
25
 
26
  scaler_ccmq = joblib.load(f"scaler_ccmq_fold_{FOLD}.pkl")
27
  scaler_osdi = joblib.load(f"scaler_osdi_fold_{FOLD}.pkl")
28
 
29
-
30
  def analyze_and_predict(*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
-
43
-
44
- x1_scaled = scaler_ccmq.transform(x1_raw)
45
- x2_scaled = scaler_osdi.transform(x2_raw)
46
 
47
  sx1 = torch.tensor(x1_scaled, dtype=torch.float32).to(DEVICE)
48
  sx2 = torch.tensor(x2_scaled, dtype=torch.float32).to(DEVICE)
@@ -56,73 +47,79 @@ def analyze_and_predict(*all_answers):
56
 
57
  print(f"DEBUG: Prediction successful! Pred: {pred_idx}")
58
 
59
- except Exception as e:
60
- print(f" ERROR in inference: {e}")
61
- raise gr.Error(f"計算出錯:{str(e)}")
62
 
63
- res_label = " 乾眼風險 (SJS/DES)" if pred_idx == 1 else " 正常/健康"
64
- table_data = [[f"項目 {i+1}", str(all_answers[i]), "已紀錄"] for i in range(len(all_answers))]
65
-
 
 
 
66
 
67
- return (
68
- gr.update(visible=False),
69
- gr.update(visible=True),
70
- f"### {res_label}",
71
- f"根據雙流 Transformer 模型分析,您的信心度為 {conf:.2%}。這代表系統觀察到您的中醫體質與眼表症狀具備相關特徵。",
72
- {"Risk": conf if pred_idx==1 else 1-conf, "Healthy": 1 - (conf if pred_idx==1 else 1-conf)},
73
- table_data,
74
- None,
75
- None
76
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
 
79
- with gr.Blocks() as demo:
80
- gr.Markdown("# 中醫 AI 診斷系統")
81
-
82
- with gr.Column(visible=True) as stage_1:
83
- with gr.Tabs() as survey_tabs:
84
- with gr.Tab("CCMQ 體質評估", id=0):
85
- ccmq_labels = ["惡寒惡風", "自汗", "胸悶腹脹","咽喉痰梗感","多愁善感","易受驚","面部暗沉","黑眼圈","健忘","唇色暗","身熱、面熱","膚乾口乾","唇紅","便祕","兩顴紅","眼乾澀","四肢冷","惡寒、腰膝冷","飲冷腹瀉","口苦口臭","帶下色黃/下陰潮濕","鼻塞流涕","變天咳喘","過敏"]
86
- all_ccmq = [gr.Radio(["總是", "經常", "有時", "很少", "沒有"], label=f"{i+1}. {txt}", value="沒有") for i, txt in enumerate(ccmq_labels)]
87
- btn_next = gr.Button("下一步", variant="primary")
88
-
89
- with gr.Tab("OSDI 症狀評估", id=1):
90
- osdi_labels = ["1. 對光敏感", "2. 眼睛疼痛", "3. 視線模糊", "4. 視力減退", "5. 閱讀限制", "6. 夜間駕駛", "7. 電腦操作", "8. 觀看電視", "9. 刮風不適", "10. 空調不適"]
91
- all_osdi = [gr.Radio(["總是", "經常", "一半一半", "偶而", "完全不曾"], label=txt, value="完全不曾") for txt in osdi_labels]
92
-
93
- with gr.Row():
94
- back_btn = gr.Button("返回")
95
- submit_btn = gr.Button("生成診斷報告", variant="primary")
96
-
97
- with gr.Column(visible=False) as stage_2:
98
- gr.Markdown("## 診斷報告結果")
99
- with gr.Row():
100
- res_table = gr.Dataframe(headers=["項目", "回答", "狀態"], interactive=False)
101
- with gr.Column():
102
- res_prob = gr.Label(label="分析機率")
103
- res_title = gr.Markdown("### 結論")
104
- res_desc = gr.Markdown("分析中...")
105
- plot_1 = gr.Plot(visible=False)
106
- plot_2 = gr.Plot(visible=False)
107
- finish_btn = gr.Button(" 重新開始", variant="secondary")
108
-
109
-
110
  all_inputs = all_ccmq + all_osdi
111
  btn_next.click(fn=lambda: gr.Tabs(selected=1), outputs=survey_tabs)
112
  back_btn.click(fn=lambda: gr.Tabs(selected=0), outputs=survey_tabs)
113
 
114
-
115
  submit_btn.click(
116
  fn=analyze_and_predict,
117
  inputs=all_inputs,
118
- outputs=[stage_1, stage_2, res_title, res_desc, res_prob, res_table, plot_1, plot_2]
119
  )
120
 
121
- finish_btn.click(
122
- fn=lambda: [gr.update(visible=True), gr.update(visible=False), gr.update(selected=0)] + ["沒有"]*24 + ["完全不曾"]*10,
123
- outputs=[stage_1, stage_2, survey_tabs] + all_inputs
 
124
  )
125
 
126
  if __name__ == "__main__":
127
-
128
- demo.launch(theme=gr.themes.Soft())
 
20
  model.load_state_dict(checkpoint['model'], strict=False)
21
  metric_fc.load_state_dict(checkpoint['fc'], strict=False)
22
  model.eval()
 
 
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)
 
47
 
48
  print(f"DEBUG: Prediction successful! Pred: {pred_idx}")
49
 
 
 
 
50
 
51
+ if pred_idx == 1:
52
+ res_label = "正常 / 健康"
53
+ elif pred_idx == 0:
54
+ res_label = "乾眼風險 (DES)"
55
+ else:
56
+ res_label = "修格蘭氏症風險 (SJS)"
57
 
58
+ prob_dict = {
59
+ "健康": probs[0, 0].item(),
60
+ "乾眼 (DES)": probs[0, 1].item(),
61
+ "修格蘭氏 (SJS)": probs[0, 2].item()
62
+ }
63
+
64
+ return (
65
+ f"## 診斷結果:{res_label}",
66
+ f"**分析完成**:AI 信心度為 **{conf:.2%}**。本系統整合了中醫 24 項體質特徵與西醫 10 項 OSDI 症狀進行多模態計算。",
67
+ {"Risk": conf if pred_idx==1 else 1-conf, "Healthy": 1 - (conf if pred_idx==1 else 1-conf)}
68
+ )
69
+
70
+ except Exception as e:
71
+ print(f"Error: {e}")
72
+ return f"### 計算出錯", str(e), {}
73
+
74
+ with gr.Blocks(theme=gr.themes.Soft(), css=".scroll-box { height: 400px; overflow-y: auto; border: 1px solid #ddd; padding: 15px; border-radius: 8px; }") as demo:
75
+ gr.Markdown("# 中西醫 AI 診斷系統")
76
+
77
+ with gr.Row():
78
+ with gr.Column(scale=2):
79
+ gr.Markdown("### 第一步:填寫問卷")
80
+ with gr.Tabs() as survey_tabs:
81
+ with gr.Tab("CCMQ 體質評估", id=0):
82
+ with gr.Group(elem_classes="scroll-box"):
83
+ ccmq_labels = ["惡寒惡風", "自汗", "胸悶腹脹","咽喉痰梗感","多愁善感","易受驚","面部暗沉","黑眼圈","健忘","唇色暗","身熱、面熱","膚乾口乾","唇紅","便祕","兩顴紅","眼乾澀","四肢冷","惡寒、腰膝冷","飲冷腹瀉","口苦口臭","帶下色黃/下陰潮濕","鼻塞流涕","變天咳喘","過敏"]
84
+ all_ccmq = [gr.Radio(["總是", "經常", "有時", "很少", "沒有"], label=f"{i+1}. {txt}", value="沒有") for i, txt in enumerate(ccmq_labels)]
85
+ btn_next = gr.Button("下一步:填寫 OSDI")
86
+
87
+ with gr.Tab("OSDI 症狀評估", id=1):
88
+ with gr.Group(elem_classes="scroll-box"):
89
+ osdi_labels = ["1. 對光敏感", "2. 眼睛疼痛", "3. 視線模糊", "4. 視力減退", "5. 閱讀限制", "6. 夜間駕駛", "7. 電腦操作", "8. 觀看電視", "9. 刮風不適", "10. 空調不適"]
90
+ all_osdi = [gr.Radio(["總是", "經常", "一半一半", "偶而", "完全不曾"], label=txt, value="完全不曾") for txt in osdi_labels]
91
+
92
+ with gr.Row():
93
+ back_btn = gr.Button("返回")
94
+ submit_btn = gr.Button("🚀 生成分析報告", variant="primary")
95
+
96
+
97
+ with gr.Column(scale=1):
98
+ gr.Markdown("### 第二步:AI 診斷結果")
99
+ res_title = gr.Markdown("### 點擊按鈕開始分析")
100
+ res_desc = gr.Markdown("請先完成左側問卷並點擊「生成分析報告」。")
101
+ res_prob = gr.Label(label="模��信心分佈")
102
+
103
+ gr.Markdown("---")
104
+ reset_btn = gr.Button("🏁 清除重新開始")
105
 
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  all_inputs = all_ccmq + all_osdi
108
  btn_next.click(fn=lambda: gr.Tabs(selected=1), outputs=survey_tabs)
109
  back_btn.click(fn=lambda: gr.Tabs(selected=0), outputs=survey_tabs)
110
 
111
+
112
  submit_btn.click(
113
  fn=analyze_and_predict,
114
  inputs=all_inputs,
115
+ outputs=[res_title, res_desc, res_prob]
116
  )
117
 
118
+
119
+ reset_btn.click(
120
+ fn=lambda: ["### 點擊按鈕開始分析", "請先完成左側問卷。", {}] + ["沒有"]*24 + ["完全不曾"]*10,
121
+ outputs=[res_title, res_desc, res_prob] + all_inputs
122
  )
123
 
124
  if __name__ == "__main__":
125
+ demo.launch(ssr_mode=False)