Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,6 +6,7 @@ import os
|
|
| 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"
|
|
@@ -19,22 +20,105 @@ if os.path.exists(MODEL_PATH):
|
|
| 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 |
|
|
|
|
| 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"
|
|
|
|
| 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 |
+
|
| 41 |
x1_scaled = scaler_ccmq.transform(np.array([x1_vals]))
|
| 42 |
x2_scaled = scaler_osdi.transform(np.array([x2_vals]))
|
| 43 |
|
| 44 |
+
|
| 45 |
+
sx1 = torch.tensor(x1_scaled, dtype=torch.float32).to(DEVICE)
|
| 46 |
+
sx2 = torch.tensor(x2_scaled, dtype=torch.float32).to(DEVICE)
|
| 47 |
+
|
| 48 |
+
with torch.no_grad():
|
| 49 |
+
feats = model(sx1, sx2)
|
| 50 |
+
logits = metric_fc.predict(feats)
|
| 51 |
+
probs = torch.softmax(logits, dim=1)
|
| 52 |
+
pred_idx = torch.argmax(probs, dim=1).item()
|
| 53 |
+
conf = probs[0, pred_idx].item()
|
| 54 |
+
|
| 55 |
+
print(f"DEBUG: Prediction successful! Pred: {pred_idx}")
|
| 56 |
+
except Exception as e:
|
| 57 |
+
print(f" Inference Error: {e}")
|
| 58 |
+
raise gr.Error(f"推論失敗: {str(e)}")
|
| 59 |
+
|
| 60 |
+
# 結論文字與表格
|
| 61 |
+
res_label = " 乾眼風險 (SJS/DES)" if pred_idx == 1 else "正常/健康"
|
| 62 |
+
table_data = [[f"項目 {i+1}", str(all_answers[i]), "已紀錄"] for i in range(len(all_answers))]
|
| 63 |
+
|
| 64 |
+
# 回傳給 outputs: [input_area, result_area, res_title, res_desc, res_prob, res_table]
|
| 65 |
+
return (
|
| 66 |
+
gr.update(visible=False),
|
| 67 |
+
gr.update(visible=True),
|
| 68 |
+
f"### 診斷結果:{res_label}",
|
| 69 |
+
f"**AI 信心度:{conf:.2%}**\n系統已完成多模態特徵提取(TCM + OSDI)。",
|
| 70 |
+
{"Risk": conf if pred_idx==1 else 1-conf, "Healthy": 1 - (conf if pred_idx==1 else 1-conf)},
|
| 71 |
+
table_data
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
with gr.Blocks(theme=gr.themes.Soft(), css=".scroll-box { height: 400px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; }") as demo:
|
| 76 |
+
gr.Markdown("# 中醫結合 AI 多模態診斷系統")
|
| 77 |
+
|
| 78 |
+
with gr.Column(visible=True) as input_area:
|
| 79 |
+
with gr.Row():
|
| 80 |
+
with gr.Column():
|
| 81 |
+
gr.Markdown("#### Step 1: CCMQ 體質辨識")
|
| 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 |
+
|
| 86 |
+
with gr.Column():
|
| 87 |
+
gr.Markdown("#### Step 2: OSDI 症狀量表")
|
| 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 |
+
submit_btn = gr.Button(" 提交診斷並生成報告", variant="primary", size="lg")
|
| 93 |
+
|
| 94 |
+
with gr.Column(visible=False) as result_area:
|
| 95 |
+
gr.Markdown("### AI 分析報告結果")
|
| 96 |
+
res_title = gr.Markdown("### 結論加載中...")
|
| 97 |
+
with gr.Row():
|
| 98 |
+
with gr.Column():
|
| 99 |
+
res_prob = gr.Label(label="預測機率分佈")
|
| 100 |
+
res_desc = gr.Markdown("正在分析數據...")
|
| 101 |
+
with gr.Column():
|
| 102 |
+
res_table = gr.Dataframe(headers=["項目", "回答", "狀態"], interactive=False)
|
| 103 |
+
|
| 104 |
+
finish_btn = gr.Button(" 重新開始", variant="secondary")
|
| 105 |
+
|
| 106 |
+
all_inputs = all_ccmq + all_osdi
|
| 107 |
+
|
| 108 |
+
submit_btn.click(
|
| 109 |
+
fn=analyze_and_predict,
|
| 110 |
+
inputs=all_inputs,
|
| 111 |
+
outputs=[input_area, result_area, res_title, res_desc, res_prob, res_table]
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
finish_btn.click(
|
| 115 |
+
fn=lambda: [gr.update(visible=True), gr.update(visible=False)] + ["沒有"]*24 + ["完全不曾"]*10,
|
| 116 |
+
outputs=[input_area, result_area] + all_inputs
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
if __name__ == "__main__":
|
| 121 |
+
demo.launch(ssr_mode=False)
|
| 122 |
sx1 = torch.tensor(x1_scaled, dtype=torch.float32).to(DEVICE)
|
| 123 |
sx2 = torch.tensor(x2_scaled, dtype=torch.float32).to(DEVICE)
|
| 124 |
|