Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,35 +6,6 @@ import os
|
|
| 6 |
import joblib
|
| 7 |
from model import DualStreamTransformer, ArcMarginProduct
|
| 8 |
|
| 9 |
-
css = """
|
| 10 |
-
.scroll-box {
|
| 11 |
-
height: 300px;
|
| 12 |
-
overflow-y: auto !important;
|
| 13 |
-
overflow-x: hidden !important;
|
| 14 |
-
display: block !important;
|
| 15 |
-
width: 100% !important;
|
| 16 |
-
max-width: 100% !important;
|
| 17 |
-
}
|
| 18 |
-
.scroll-box * {
|
| 19 |
-
max-width: 100% !important;
|
| 20 |
-
box-sizing: border-box !important;
|
| 21 |
-
}
|
| 22 |
-
.vertical-radio {
|
| 23 |
-
display: block !important;
|
| 24 |
-
width: 100% !important;
|
| 25 |
-
}
|
| 26 |
-
.vertical-radio .wrap {
|
| 27 |
-
display: flex !important;
|
| 28 |
-
flex-direction: column !important;
|
| 29 |
-
width: 100% !important;
|
| 30 |
-
min-width: 0 !important;
|
| 31 |
-
}
|
| 32 |
-
.vertical-radio .gradio-radio-item {
|
| 33 |
-
width: 100% !important;
|
| 34 |
-
white-space: normal !important;
|
| 35 |
-
word-break: break-all !important;
|
| 36 |
-
}
|
| 37 |
-
"""
|
| 38 |
|
| 39 |
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 40 |
FOLD = 5
|
|
@@ -49,28 +20,30 @@ if os.path.exists(MODEL_PATH):
|
|
| 49 |
model.load_state_dict(checkpoint['model'])
|
| 50 |
metric_fc.load_state_dict(checkpoint['fc'])
|
| 51 |
model.eval()
|
| 52 |
-
|
| 53 |
-
|
| 54 |
|
| 55 |
scaler_ccmq = joblib.load(f"scaler_ccmq_fold_{FOLD}.pkl")
|
| 56 |
scaler_osdi = joblib.load(f"scaler_osdi_fold_{FOLD}.pkl")
|
| 57 |
|
| 58 |
def analyze_and_predict(*all_answers):
|
| 59 |
-
|
|
|
|
|
|
|
| 60 |
ccmq_map = {"總是": 5, "經常": 4, "有時": 3, "很少": 2, "沒有": 1}
|
| 61 |
osdi_map = {"總是": 4, "經常": 3, "一半一半": 2, "偶而": 1, "完全不曾": 0}
|
| 62 |
|
| 63 |
-
print(f"--- 偵錯資訊:收到 {len(all_answers)} 題回答 ---")
|
| 64 |
-
|
| 65 |
try:
|
| 66 |
-
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
|
| 69 |
-
x2_raw = np.array([
|
| 70 |
|
| 71 |
|
| 72 |
x1_scaled = scaler_ccmq.transform(x1_raw)
|
| 73 |
x2_scaled = scaler_osdi.transform(x2_raw)
|
|
|
|
| 74 |
sx1 = torch.tensor(x1_scaled, dtype=torch.float32).to(DEVICE)
|
| 75 |
sx2 = torch.tensor(x2_scaled, dtype=torch.float32).to(DEVICE)
|
| 76 |
|
|
@@ -81,77 +54,75 @@ def analyze_and_predict(*all_answers):
|
|
| 81 |
pred_idx = torch.argmax(probs, dim=1).item()
|
| 82 |
conf = probs[0, pred_idx].item()
|
| 83 |
|
| 84 |
-
|
| 85 |
-
print(f"❌ 推論發生錯誤: {e}")
|
| 86 |
-
raise gr.Error(f"系統轉換異常,請重新整理頁面。錯誤原因: {str(e)}")
|
| 87 |
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
res_label = " 乾眼風險 (SJS/DES)" if pred_idx == 1 else " 正常/健康"
|
| 90 |
-
table_data = [[f"項
|
| 91 |
|
| 92 |
-
report_text = f"### 診斷結論:{res_label}\nAI 信心度:{conf:.2%}"
|
| 93 |
|
| 94 |
return (
|
| 95 |
-
gr.update(visible=False),
|
| 96 |
-
gr.update(visible=True),
|
| 97 |
-
f"### {res_label}",
|
| 98 |
-
|
| 99 |
-
{"
|
| 100 |
-
table_data,
|
| 101 |
None,
|
| 102 |
None
|
| 103 |
)
|
| 104 |
|
| 105 |
-
|
| 106 |
-
return [gr.update(visible=True), gr.update(visible=False), gr.update(selected=0)] + [None] * 34
|
| 107 |
-
|
| 108 |
with gr.Blocks() as demo:
|
| 109 |
gr.Markdown("# 中醫 AI 診斷系統")
|
| 110 |
|
| 111 |
with gr.Column(visible=True) as stage_1:
|
| 112 |
with gr.Tabs() as survey_tabs:
|
| 113 |
with gr.Tab("CCMQ 體質評估", id=0):
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
btn_next = gr.Button("下一步:填寫 OSDI", variant="primary")
|
| 118 |
|
| 119 |
with gr.Tab("OSDI 症狀評估", id=1):
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
all_osdi = [gr.Radio(["總是", "經常", "一半一半", "偶而", "完全不曾"], label=txt) for txt in osdi_labels]
|
| 123 |
|
| 124 |
with gr.Row():
|
| 125 |
-
back_btn = gr.Button("返回
|
| 126 |
-
submit_btn = gr.Button("
|
| 127 |
|
| 128 |
with gr.Column(visible=False) as stage_2:
|
| 129 |
-
gr.Markdown("##
|
| 130 |
with gr.Row():
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
with gr.Column(scale=1):
|
| 135 |
-
res_prob = gr.Label(label="預測信心機率")
|
| 136 |
res_title = gr.Markdown("### 結論")
|
| 137 |
-
res_desc = gr.Markdown("
|
| 138 |
-
|
| 139 |
plot_1 = gr.Plot(visible=False)
|
| 140 |
plot_2 = gr.Plot(visible=False)
|
| 141 |
finish_btn = gr.Button(" 重新開始", variant="secondary")
|
| 142 |
|
|
|
|
| 143 |
all_inputs = all_ccmq + all_osdi
|
| 144 |
btn_next.click(fn=lambda: gr.Tabs(selected=1), outputs=survey_tabs)
|
| 145 |
back_btn.click(fn=lambda: gr.Tabs(selected=0), outputs=survey_tabs)
|
| 146 |
-
back_to_edit.click(fn=lambda: (gr.update(visible=True), gr.update(visible=False)), outputs=[stage_1, stage_2])
|
| 147 |
|
|
|
|
| 148 |
submit_btn.click(
|
| 149 |
fn=analyze_and_predict,
|
| 150 |
inputs=all_inputs,
|
| 151 |
outputs=[stage_1, stage_2, res_title, res_desc, res_prob, res_table, plot_1, plot_2]
|
| 152 |
)
|
| 153 |
|
| 154 |
-
finish_btn.click(
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
if __name__ == "__main__":
|
|
|
|
| 157 |
demo.launch(theme=gr.themes.Soft())
|
|
|
|
| 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
|
|
|
|
| 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 |
|
| 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)
|
| 49 |
|
|
|
|
| 54 |
pred_idx = torch.argmax(probs, dim=1).item()
|
| 55 |
conf = probs[0, pred_idx].item()
|
| 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 |
+
# --- UI 介面 ---
|
|
|
|
|
|
|
| 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())
|