import gradio as gr import torch import numpy as np import joblib from model import CNN DEVICE = torch.device('cpu') class DummyModel(torch.nn.Module): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) negative_slope, hidden_dim, n_layers, channels = 0.2, 4, 1, 3 self.model = CNN(input_dim=12, hidden_dim=hidden_dim, n_layers=n_layers, negative_slope=negative_slope,\ channels=channels, DEVICE=DEVICE).to(DEVICE) self.model.load_state_dict(torch.load("./model_fold_1.pkl", map_location=DEVICE)) self.model.eval() self.scaler = joblib.load("./scaler_fold_1.pkl") def forward(self, x): x = self.scaler.transform(x) prob = self.model.predict_proba(x) return prob model = DummyModel() # 2. 定义预测函数 def predict_risk(age, gender, phys_limit_score, symp_stab_score, \ symp_freq_score, symp_bur_score, tot_symp_score, self_eff_score, \ qol_score, soc_limit_score, overall_sum_score, clin_sum_score): # 数据预处理:将输入转换为 Tensor features = [float(age), float(gender), float(phys_limit_score), float(symp_stab_score), \ float(symp_freq_score), float(symp_bur_score), float(tot_symp_score), float(self_eff_score), \ float(qol_score), float(soc_limit_score), float(overall_sum_score), float(clin_sum_score)] input_data = np.array([features]) with torch.no_grad(): output = model(input_data)[0] risk_score = output.item() # 格式化输出结果 risk_percentage = f"{risk_score * 100:.2f}%" if risk_score > 0.5: result_text = f"High Risk (Probability: {risk_percentage})" color = "red" else: result_text = f"low Risk (Probability: {risk_percentage})" color = "green" return result_text iface = gr.Interface( fn=predict_risk, inputs=[ gr.Slider(30, 100, step=1, label="age (30-100)"), gr.Radio(["1", "2"], label="gender (1=male, 2=female)", value="1"), gr.Number(label="phys_limit_score (0-100)", value=50, minimum=0, maximum=100), gr.Radio(["0", "25", "50", "75", "100"], label="symp_stab_score (0-100)", value="50"), gr.Number(label="symp_freq_score (0-100)", value=50, minimum=0, maximum=100), gr.Number(label="symp_bur_score (0-100)", value=50, minimum=0, maximum=100), gr.Number(label="tot_symp_score (0-100)", value=50, minimum=0, maximum=100), gr.Number(label="self_eff_score (0-100)", value=50, minimum=0, maximum=100), gr.Number(label="qol_score (0-100)", value=50, minimum=0, maximum=100), gr.Number(label="soc_limit_score (0-100)", value=50, minimum=0, maximum=100), gr.Number(label="overall_sum_score (0-100)", value=50, minimum=0, maximum=100), gr.Number(label="clin_sum_score (0-100)", value=50, minimum=0, maximum=100), ], outputs=gr.Textbox(label="Sudden cardiac death risk"), title="KCCQ_SCD_Risk_Calculator", description="Enter your physiological indicators to predict health risks.", theme="default" ) # 启动 iface.launch()