Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,6 +7,7 @@ import gradio as gr
|
|
| 7 |
import os
|
| 8 |
import joblib
|
| 9 |
from model import DualStreamTransformer, ArcMarginProduct
|
|
|
|
| 10 |
css = """
|
| 11 |
.scroll-box {
|
| 12 |
height: 300px;
|
|
@@ -36,11 +37,14 @@ css = """
|
|
| 36 |
word-break: break-all !important;
|
| 37 |
}
|
| 38 |
"""
|
|
|
|
|
|
|
| 39 |
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 40 |
FOLD = 5
|
| 41 |
MODEL_PATH = f"best_model_fold_{FOLD}.pt"
|
| 42 |
|
| 43 |
-
|
|
|
|
| 44 |
metric_fc = ArcMarginProduct(32, 2).to(DEVICE)
|
| 45 |
|
| 46 |
if os.path.exists(MODEL_PATH):
|
|
@@ -53,25 +57,22 @@ if os.path.exists(MODEL_PATH):
|
|
| 53 |
scaler_ccmq = joblib.load(f"scaler_ccmq_fold_{FOLD}.pkl")
|
| 54 |
scaler_osdi = joblib.load(f"scaler_osdi_fold_{FOLD}.pkl")
|
| 55 |
|
| 56 |
-
|
| 57 |
def analyze_and_predict(*all_answers):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
ccmq_map = {"總是": 5, "經常": 4, "有時": 3, "很少": 2, "沒有": 1}
|
| 59 |
osdi_map = {"總是": 4, "經常": 3, "一半一半": 2, "偶而": 1, "完全不曾": 0}
|
| 60 |
|
| 61 |
ccmq_ans = all_answers[:24]
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
if any(a is None for a in all_answers):
|
| 65 |
-
missing_indices = [i+1 for i, a in enumerate(all_answers) if a is None]
|
| 66 |
-
print(f"DEBUG - 未填寫題目索引: {missing_indices}")
|
| 67 |
-
raise gr.Error(f"還有題目沒填完喔!未填索引: {missing_indices}")
|
| 68 |
|
| 69 |
x1_raw = np.array([[ccmq_map[a] for a in ccmq_ans]])
|
| 70 |
-
x2_raw = np.array([[osdi_map[a] for a in
|
| 71 |
|
| 72 |
x1_scaled = scaler_ccmq.transform(x1_raw)
|
| 73 |
x2_scaled = scaler_osdi.transform(x2_raw)
|
| 74 |
-
|
| 75 |
sx1 = torch.tensor(x1_scaled, dtype=torch.float32).to(DEVICE)
|
| 76 |
sx2 = torch.tensor(x2_scaled, dtype=torch.float32).to(DEVICE)
|
| 77 |
|
|
@@ -82,34 +83,32 @@ def analyze_and_predict(*all_answers):
|
|
| 82 |
pred_idx = torch.argmax(probs, dim=1).item()
|
| 83 |
conf = probs[0, pred_idx].item()
|
| 84 |
|
|
|
|
| 85 |
plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei', 'DejaVu Sans']
|
| 86 |
plt.rcParams['axes.unicode_minus'] = False
|
| 87 |
-
|
| 88 |
fig, ax = plt.subplots(figsize=(6, 4))
|
| 89 |
-
|
| 90 |
-
sns.barplot(x=[conf if i == pred_idx else 1-conf for i in range(2)], y=labels, palette="viridis", ax=ax)
|
| 91 |
ax.set_title(f"AI 診斷信心度: {conf:.2%}")
|
| 92 |
|
| 93 |
-
table_data = [[f"
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
return (
|
| 98 |
gr.update(visible=False),
|
| 99 |
-
gr.update(visible=True),
|
| 100 |
-
f"### {res_label}",
|
| 101 |
-
|
| 102 |
-
{"風險機率": conf if pred_idx==1 else 1-conf, "健康程度": 1 - (conf if pred_idx==1 else 1-conf)},
|
| 103 |
-
table_data,
|
| 104 |
-
fig,
|
| 105 |
-
fig
|
| 106 |
)
|
| 107 |
|
| 108 |
def reset_system():
|
| 109 |
-
return [gr.update(visible=True), gr.update(visible=False), gr.update(selected=0)] + [None] *
|
| 110 |
|
| 111 |
with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
|
| 112 |
-
gr.Markdown("# 中醫AI診斷系統")
|
| 113 |
|
| 114 |
with gr.Column(visible=True) as stage_1:
|
| 115 |
with gr.Tabs() as survey_tabs:
|
|
@@ -117,40 +116,43 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
|
|
| 117 |
with gr.Group(elem_classes="scroll-box"):
|
| 118 |
ccmq_labels = ["惡寒惡風", "自汗", "胸悶腹脹","咽喉痰梗感","多愁善感","易受驚","面部暗沉","黑眼圈","健忘","唇色暗","身熱、面熱","膚乾口乾","唇紅","便祕","兩顴紅","眼乾澀","四肢冷","惡寒、腰膝冷","飲冷腹瀉","口苦口臭","帶下色黃/下陰潮濕","鼻塞流涕","變天咳喘","過敏"]
|
| 119 |
all_ccmq = [gr.Radio(["總是", "經常", "有時", "很少", "沒有"], label=f"{i+1}. {txt}") for i, txt in enumerate(ccmq_labels)]
|
| 120 |
-
btn_next = gr.Button("下一步
|
| 121 |
|
| 122 |
with gr.Tab("OSDI 症狀評估", id=1):
|
| 123 |
with gr.Group(elem_classes="scroll-box"):
|
| 124 |
osdi_labels = ["1. 對光敏感", "2. 眼睛疼痛", "3. 視線模糊", "4. 視力減退", "5. 閱讀限制", "6. 夜間駕駛", "7. 電腦操作", "8. 觀看電視", "9. 刮風不適", "10. 空調不適"]
|
| 125 |
-
# 注意:這裡使用列表生成式,避免變數名稱重複覆蓋
|
| 126 |
all_osdi = [gr.Radio(["總是", "經常", "一半一半", "偶而", "完全不曾"], label=txt) for txt in osdi_labels]
|
|
|
|
| 127 |
with gr.Row():
|
| 128 |
back_to_ccmq = gr.Button("返回 CCMQ")
|
| 129 |
-
submit_btn = gr.Button("
|
| 130 |
|
| 131 |
with gr.Column(visible=False) as stage_2:
|
| 132 |
-
gr.Markdown("##
|
| 133 |
with gr.Row():
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
|
|
|
| 137 |
res_prob = gr.Label(label="預測機率")
|
| 138 |
res_title = gr.Markdown("### 診斷結果")
|
| 139 |
-
res_desc = gr.Markdown("
|
| 140 |
plot_1 = gr.Plot()
|
| 141 |
plot_2 = gr.Plot()
|
| 142 |
-
finish_btn = gr.Button("結束並重新開始",
|
| 143 |
-
|
| 144 |
|
| 145 |
all_inputs = all_ccmq + all_osdi
|
|
|
|
| 146 |
btn_next.click(fn=lambda: gr.Tabs(selected=1), outputs=survey_tabs)
|
| 147 |
back_to_ccmq.click(fn=lambda: gr.Tabs(selected=0), outputs=survey_tabs)
|
| 148 |
back_to_edit.click(fn=lambda: (gr.update(visible=True), gr.update(visible=False)), outputs=[stage_1, stage_2])
|
|
|
|
| 149 |
submit_btn.click(
|
| 150 |
fn=analyze_and_predict,
|
| 151 |
inputs=all_inputs,
|
| 152 |
outputs=[stage_1, stage_2, res_title, res_desc, res_prob, res_table, plot_1, plot_2]
|
| 153 |
)
|
|
|
|
| 154 |
finish_btn.click(fn=reset_system, outputs=[stage_1, stage_2, survey_tabs] + all_inputs)
|
| 155 |
|
| 156 |
if __name__ == "__main__":
|
|
|
|
| 7 |
import os
|
| 8 |
import joblib
|
| 9 |
from model import DualStreamTransformer, ArcMarginProduct
|
| 10 |
+
|
| 11 |
css = """
|
| 12 |
.scroll-box {
|
| 13 |
height: 300px;
|
|
|
|
| 37 |
word-break: break-all !important;
|
| 38 |
}
|
| 39 |
"""
|
| 40 |
+
|
| 41 |
+
|
| 42 |
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 43 |
FOLD = 5
|
| 44 |
MODEL_PATH = f"best_model_fold_{FOLD}.pt"
|
| 45 |
|
| 46 |
+
|
| 47 |
+
model = DualStreamTransformer(feat_num_1=24, feat_num_2=10, d_model=32).to(DEVICE)
|
| 48 |
metric_fc = ArcMarginProduct(32, 2).to(DEVICE)
|
| 49 |
|
| 50 |
if os.path.exists(MODEL_PATH):
|
|
|
|
| 57 |
scaler_ccmq = joblib.load(f"scaler_ccmq_fold_{FOLD}.pkl")
|
| 58 |
scaler_osdi = joblib.load(f"scaler_osdi_fold_{FOLD}.pkl")
|
| 59 |
|
|
|
|
| 60 |
def analyze_and_predict(*all_answers):
|
| 61 |
+
|
| 62 |
+
if any(a is None for a in all_answers):
|
| 63 |
+
missing = [i+1 for i, a in enumerate(all_answers) if a is None]
|
| 64 |
+
raise gr.Error(f"還有題目沒填完!索引:{missing}")
|
| 65 |
ccmq_map = {"總是": 5, "經常": 4, "有時": 3, "很少": 2, "沒有": 1}
|
| 66 |
osdi_map = {"總是": 4, "經常": 3, "一半一半": 2, "偶而": 1, "完全不曾": 0}
|
| 67 |
|
| 68 |
ccmq_ans = all_answers[:24]
|
| 69 |
+
osdi_ans = all_answers[24:34] # 確保只取 10 題
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
x1_raw = np.array([[ccmq_map[a] for a in ccmq_ans]])
|
| 72 |
+
x2_raw = np.array([[osdi_map[a] for a in osdi_ans]])
|
| 73 |
|
| 74 |
x1_scaled = scaler_ccmq.transform(x1_raw)
|
| 75 |
x2_scaled = scaler_osdi.transform(x2_raw)
|
|
|
|
| 76 |
sx1 = torch.tensor(x1_scaled, dtype=torch.float32).to(DEVICE)
|
| 77 |
sx2 = torch.tensor(x2_scaled, dtype=torch.float32).to(DEVICE)
|
| 78 |
|
|
|
|
| 83 |
pred_idx = torch.argmax(probs, dim=1).item()
|
| 84 |
conf = probs[0, pred_idx].item()
|
| 85 |
|
| 86 |
+
|
| 87 |
plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei', 'DejaVu Sans']
|
| 88 |
plt.rcParams['axes.unicode_minus'] = False
|
|
|
|
| 89 |
fig, ax = plt.subplots(figsize=(6, 4))
|
| 90 |
+
sns.barplot(x=[conf if i == pred_idx else 1-conf for i in range(2)], y=["健康", "風險"], palette="viridis", ax=ax)
|
|
|
|
| 91 |
ax.set_title(f"AI 診斷信心度: {conf:.2%}")
|
| 92 |
|
| 93 |
+
table_data = [[f"問卷項目 {i+1}", all_answers[i], "OK"] for i in range(len(all_answers))]
|
| 94 |
+
res_label = "🔴 乾眼風險 (SJS/DES)" if pred_idx == 1 else "🟢 正常/健康"
|
| 95 |
+
|
|
|
|
| 96 |
return (
|
| 97 |
gr.update(visible=False),
|
| 98 |
+
gr.update(visible=True),
|
| 99 |
+
f"### {res_label}",
|
| 100 |
+
"分析報告:系統已根據您的中醫體質與西醫症狀完成多模態融合計算。",
|
| 101 |
+
{"風險機率": conf if pred_idx==1 else 1-conf, "健康程度": 1 - (conf if pred_idx==1 else 1-conf)},
|
| 102 |
+
table_data,
|
| 103 |
+
fig,
|
| 104 |
+
fig
|
| 105 |
)
|
| 106 |
|
| 107 |
def reset_system():
|
| 108 |
+
return [gr.update(visible=True), gr.update(visible=False), gr.update(selected=0)] + [None] * 34
|
| 109 |
|
| 110 |
with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
|
| 111 |
+
gr.Markdown("# 中醫 AI 診斷系統")
|
| 112 |
|
| 113 |
with gr.Column(visible=True) as stage_1:
|
| 114 |
with gr.Tabs() as survey_tabs:
|
|
|
|
| 116 |
with gr.Group(elem_classes="scroll-box"):
|
| 117 |
ccmq_labels = ["惡寒惡風", "自汗", "胸悶腹脹","咽喉痰梗感","多愁善感","易受驚","面部暗沉","黑眼圈","健忘","唇色暗","身熱、面熱","膚乾口乾","唇紅","便祕","兩顴紅","眼乾澀","四肢冷","惡寒、腰膝冷","飲冷腹瀉","口苦口臭","帶下色黃/下陰潮濕","鼻塞流涕","變天咳喘","過敏"]
|
| 118 |
all_ccmq = [gr.Radio(["總是", "經常", "有時", "很少", "沒有"], label=f"{i+1}. {txt}") for i, txt in enumerate(ccmq_labels)]
|
| 119 |
+
btn_next = gr.Button("下一步", variant="primary")
|
| 120 |
|
| 121 |
with gr.Tab("OSDI 症狀評估", id=1):
|
| 122 |
with gr.Group(elem_classes="scroll-box"):
|
| 123 |
osdi_labels = ["1. 對光敏感", "2. 眼睛疼痛", "3. 視線模糊", "4. 視力減退", "5. 閱讀限制", "6. 夜間駕駛", "7. 電腦操作", "8. 觀看電視", "9. 刮風不適", "10. 空調不適"]
|
|
|
|
| 124 |
all_osdi = [gr.Radio(["總是", "經常", "一半一半", "偶而", "完全不曾"], label=txt) for txt in osdi_labels]
|
| 125 |
+
|
| 126 |
with gr.Row():
|
| 127 |
back_to_ccmq = gr.Button("返回 CCMQ")
|
| 128 |
+
submit_btn = gr.Button("🚀 生成分析報告", variant="primary")
|
| 129 |
|
| 130 |
with gr.Column(visible=False) as stage_2:
|
| 131 |
+
gr.Markdown("## 診斷報告結果")
|
| 132 |
with gr.Row():
|
| 133 |
+
with gr.Column(scale=1):
|
| 134 |
+
res_table = gr.Dataframe(headers=["項目", "回答", "狀態"], interactive=False)
|
| 135 |
+
back_to_edit = gr.Button("修改問卷")
|
| 136 |
+
with gr.Column(scale=1):
|
| 137 |
res_prob = gr.Label(label="預測機率")
|
| 138 |
res_title = gr.Markdown("### 診斷結果")
|
| 139 |
+
res_desc = gr.Markdown("報告說明")
|
| 140 |
plot_1 = gr.Plot()
|
| 141 |
plot_2 = gr.Plot()
|
| 142 |
+
finish_btn = gr.Button("結束並重新開始", variant="secondary")
|
|
|
|
| 143 |
|
| 144 |
all_inputs = all_ccmq + all_osdi
|
| 145 |
+
|
| 146 |
btn_next.click(fn=lambda: gr.Tabs(selected=1), outputs=survey_tabs)
|
| 147 |
back_to_ccmq.click(fn=lambda: gr.Tabs(selected=0), outputs=survey_tabs)
|
| 148 |
back_to_edit.click(fn=lambda: (gr.update(visible=True), gr.update(visible=False)), outputs=[stage_1, stage_2])
|
| 149 |
+
|
| 150 |
submit_btn.click(
|
| 151 |
fn=analyze_and_predict,
|
| 152 |
inputs=all_inputs,
|
| 153 |
outputs=[stage_1, stage_2, res_title, res_desc, res_prob, res_table, plot_1, plot_2]
|
| 154 |
)
|
| 155 |
+
|
| 156 |
finish_btn.click(fn=reset_system, outputs=[stage_1, stage_2, survey_tabs] + all_inputs)
|
| 157 |
|
| 158 |
if __name__ == "__main__":
|