Download src/streamlit_app.py from moonicu/knn: direct link, hf CLI and curl.
- Browser
- Download file 19 kB
-
https://huggingface.co/spaces/moonicu/knn/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/moonicu/knn/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/moonicu/knn/resolve/main/src/streamlit_app.py
19 kB
| # KNN Prediction App (HF Spaces + Streamlit) | |
| # - λꡬλ μ¬μ© κ°λ₯ (λΉλ°λ²νΈ μμ) | |
| # - 첫 νλ©΄: μΈμ΄(ν/μ) + μμΈ‘ λͺ¨λ(μ°μ -ν, μ°μ -6κ°, μ°ν) μ ν | |
| # - 31κ° μ νλͺ© μμΈ‘ (thresholdλ model_thresholds_6feats.* μ°μ μ¬μ©) | |
| # - λͺ¨λΈ: LightGBM / XGBoost / RandomForest μ€ λ³΄μ ν κ²μ λͺ¨λ νμ | |
| # - "κ²°μ μ© λͺ¨λΈ(Decision model)" μ νμ λ°λΌ μκ³μΉ μ μ©νμ¬ Flag νκΈ° | |
| # - μ°μ 6κ° λͺ¨λμμλ μμ λ€μ΄λ‘λ μ 곡νμ§ μμ (μ°κ΅¬Β·κ²ν μ© μꡬμ¬ν λ°μ) | |
| import os | |
| import io | |
| import time | |
| from datetime import datetime | |
| import numpy as np | |
| import pandas as pd | |
| import streamlit as st | |
| # ----------------------------- | |
| # μ μ μ€μ | |
| # ----------------------------- | |
| st.set_page_config(page_title="KNN μμΈ‘ (Research/Review)", layout="wide") | |
| # μ μ₯λ λͺ¨λΈ λλ ν 리 루νΈ(κ° λͺ¨λλ³ νμ ν΄λ νμ©) | |
| MODEL_ROOT = "saved_models" | |
| # λͺ¨λΈ νμΌλͺ ν¨ν΄: best_{ModelName}_{target}.pkl | |
| MODEL_TYPES = ["LightGBM", "XGBoost", "RandomForest"] # νμ/νμ μμ | |
| # threshold νμΌ ν보 (λͺ¨λλ³ μ°μ μμ μ μ©) | |
| THRESH_FILES = { | |
| "pre_full": ["model_thresholds_full.csv", "model_thresholds_6feats.csv"], | |
| "pre_6": ["model_thresholds_6feats.csv"], | |
| "post": ["model_thresholds_post.csv", "model_thresholds_6feats.csv"] | |
| } | |
| # ----------------------------- | |
| # νμ λΌλ²¨(ν/μ) | |
| # ----------------------------- | |
| Y_LABEL_KO = { | |
| "resu":"μ΄κΈ° μμμ νμ μ 무","resuo":"μ΄κΈ° μμμ μ°μ","resup":"μ΄κΈ° μμμ μμ νκΈ°","resui":"μ΄κΈ° μμμ κΈ°λ μ½κ΄", | |
| "resuh":"μ΄κΈ° μμμ μ¬μ₯λ§μ¬μ§","resue":"μ΄κΈ° μμμ Epinephrine","resuc":"μ΄κΈ° μμμ CPAP", | |
| "rds":"μ μμ νΈν‘κ³€λμ¦νκ΅°","sft":"ννλ©΄νμ±μ μ¬μ©","sftw":"ννμ±μ μΆμ μ¦μ μ¬μ©", | |
| "als":"곡기λμΆμ¦νκ΅°","mph":"λλ νμΆν","ph":"νλλ§₯ κ³ νμ", | |
| "bpdyn":"κΈ°κ΄μ§νμ΄νμ±μ¦ μ¬λΆ(β₯mild BPD)","bpdm":"μ€λ±μ¦ κΈ°κ΄μ§νμ΄νμ±μ¦(β₯moderate BPD)", | |
| "pdad":"PDA μ½λ¬Ό μΉλ£","acl":"λλ§₯κ΄ κ²°μ°°μ ","lbp":"μ νμ", | |
| "ivh2":"λμ€λ΄μΆν (Gradeβ₯2)","ivh3":"μ€μ¦ λμ€λ΄μΆν (Gradeβ₯3)","pvl":"λ°±μ§μ°νμ¦", | |
| "seps":"ν¨νμ¦","ntet":"κ΄΄μ¬μ± μ₯μΌ","pmio":"λ§λ§μ¦ μμ ","eythtran":"μ νꡬ μν", | |
| "deathyn":"NICU μ μμ€ μ¬λ§","supyn":"ν΄μμ 보쑰 μ₯λΉ νμ" | |
| } | |
| Y_LABEL_EN = { | |
| "resu":"Resuscitation needed","resuo":"Oxygen","resup":"PPV","resui":"Intubation", | |
| "resuh":"Chest compression","resue":"Epinephrine","resuc":"CPAP", | |
| "rds":"RDS","sft":"Surfactant use","sftw":"Immediate surfactant", | |
| "als":"Air leak","mph":"Massive pulmonary hemorrhage","ph":"Pulmonary hypertension", | |
| "bpdyn":"β₯ Mild BPD","bpdm":"β₯ Moderate BPD", | |
| "pdad":"PDA medication","acl":"PDA ligation","lbp":"Hypotension", | |
| "ivh2":"IVH (β₯Grade 2)","ivh3":"IVH (β₯Grade 3)","pvl":"PVL", | |
| "seps":"Sepsis","ntet":"NEC","pmio":"ROP surgery","eythtran":"RBC transfusion", | |
| "deathyn":"In-hospital death","supyn":"Discharge support" | |
| } | |
| # μμμ κ΄λ ¨ κ·Έλ£Ή(νμ ꡬλΆμ©) | |
| RESUS_GROUP = {"resu","resuo","resup","resui","resuh","resue","resuc","sft","sftw"} | |
| # ----------------------------- | |
| # μ νΈ | |
| # ----------------------------- | |
| def _load_joblib(path: str): | |
| import joblib | |
| return joblib.load(path) | |
| def _read_thresholds_for_mode(mode_key: str) -> pd.DataFrame: | |
| """λͺ¨λλ³ ν보 νμΌμμ thresholdsλ₯Ό μ½μ΄μ¨λ€. (target, model, threshold) μ»¬λΌ νμ""" | |
| candidates = THRESH_FILES.get(mode_key, []) | |
| for fname in candidates: | |
| if os.path.exists(fname): | |
| try: | |
| df = pd.read_csv(fname) | |
| # νμ€ν | |
| cols = [c.lower() for c in df.columns] | |
| df.columns = cols | |
| # κΈ°λ 컬λΌλͺ : target, model, threshold | |
| if not {"target","model","threshold"} <= set(cols): | |
| continue | |
| # λͺ¨λΈλͺ νμ€ν(LightGBM/XGBoost/RandomForest) | |
| df["model"] = df["model"].replace({ | |
| "lgbm":"LightGBM","lightgbm":"LightGBM", | |
| "xgb":"XGBoost","xgboost":"XGBoost", | |
| "rf":"RandomForest","randomforest":"RandomForest" | |
| }) | |
| return df[["target","model","threshold"]].copy() | |
| except Exception: | |
| continue | |
| # μμΌλ©΄ λΉ DF λ°ν(κΈ°λ³Έ 0.5 μ¬μ©) | |
| return pd.DataFrame(columns=["target","model","threshold"]) | |
| def _discover_targets(mode_key: str, thresh_df: pd.DataFrame, models_dir: str) -> list: | |
| """threshold νμΌ λλ λͺ¨λΈ νμΌ μ‘΄μ¬λ₯Ό κΈ°λ°μΌλ‘ λμ νκΉ λͺ©λ‘(μ λ ¬) μμ±""" | |
| ts = set() | |
| if len(thresh_df): | |
| ts |= set(thresh_df["target"].astype(str).tolist()) | |
| # λͺ¨λΈ νμΌ μ€μΊ | |
| if os.path.isdir(models_dir): | |
| for fname in os.listdir(models_dir): | |
| if fname.startswith("best_") and fname.endswith(".pkl"): | |
| # best_{Model}_{target}.pkl | |
| try: | |
| without = fname.replace(".pkl","").split("best_")[1] | |
| model_name, target = without.split("_", 1) | |
| ts.add(target) | |
| except Exception: | |
| pass | |
| # κ·Έλλ λΉλ©΄, μ΅μ 27κ° κΈ°λ³Έ μ (κ³Όκ±° μ½λ)λ‘ μ±μ | |
| if not ts: | |
| ts = { | |
| "resu","resuo","resup","resui","resuh","resue","resuc","rds","sft","sftw","als","mph","ph", | |
| "bpdyn","bpdm","pdad","acl","lbp","ivh2","ivh3","pvl","seps","ntet","pmio","eythtran","deathyn","supyn" | |
| } | |
| return sorted(ts) | |
| def _model_dirs_for_mode(mode_key: str): | |
| """λͺ¨λλ³ λͺ¨λΈ λλ ν 리: μ°μ saved_models/{mode_key}, μμΌλ©΄ saved_models 루νΈ""" | |
| prefer = os.path.join(MODEL_ROOT, mode_key) | |
| if os.path.isdir(prefer): | |
| return prefer | |
| return MODEL_ROOT # fallback | |
| def _make_input_df(mode_key: str, values: dict, x_order: list) -> pd.DataFrame: | |
| row = [values[k] for k in x_order] | |
| return pd.DataFrame([row], columns=x_order) | |
| def _fmt_prob(p: float) -> str: | |
| if p is None: return "-" | |
| return f"{p*100:.1f}%" | |
| def _predict_proba(est, X) -> float | None: | |
| try: | |
| if hasattr(est, "predict_proba"): | |
| return float(est.predict_proba(X)[0, 1]) | |
| # νκ·/decision_function λ±μ μ¬κΈ°μλ μ¬μ© μ ν¨(λͺ¨λ λΆλ₯ κ°μ ) | |
| return None | |
| except Exception: | |
| return None | |
| # ----------------------------- | |
| # 0. μΈμ΄ & λͺ¨λ μ ν | |
| # ----------------------------- | |
| colA, colB = st.columns([1,2]) | |
| with colA: | |
| lang = st.radio("μΈμ΄ / Language", ["νκ΅μ΄","English"], horizontal=True) | |
| with colB: | |
| mode_label = "μμΈ‘ λͺ¨λ" if lang=="νκ΅μ΄" else "Prediction mode" | |
| mode = st.radio( | |
| mode_label, | |
| ["μ°μ μμΈ‘(ν)","μ°μ μμΈ‘(6κ°λ³μ)","μ°ν μμΈ‘"], | |
| horizontal=True | |
| ) | |
| # λ΄λΆ key | |
| mode_key = {"μ°μ μμΈ‘(ν)":"pre_full", "μ°μ μμΈ‘(6κ°λ³μ)":"pre_6", "μ°ν μμΈ‘":"post"}[mode] | |
| # ----------------------------- | |
| # 1. μ λ ₯ νΌ (λͺ¨λλ³) | |
| # ----------------------------- | |
| # μ°μ -ν(19κ°, x_columns μμ κ³ μ ) | |
| XORDER_PRE_FULL = [ | |
| 'mage','gran','parn','amni','mulg','bir','prep','dm','htn','chor', | |
| 'prom','ster','sterp','sterd','atbyn','delm','gad','sex','bwei' | |
| ] | |
| # μ°μ -6κ°(μμ νΌμ²) | |
| XORDER_PRE_6 = ['bwei','gad','mage','gran','chor','sterp'] | |
| # μ°ν(μμ: μ€μ νμ΅ μμμ λ§μΆ° μ‘°μ νμΈμ) | |
| XORDER_POST = ['gad','bwei','sex','apgar1','apgar5','temp0h','respsup','fio2_0h','ph_0h','be_0h'] | |
| # κ³΅ν΅ Label λμ°λ―Έ | |
| def L(ko, en): | |
| return ko if lang=="νκ΅μ΄" else en | |
| st.markdown("### " + L("μ λ ₯ κ°","Inputs")) | |
| values: dict = {} | |
| if mode_key in ("pre_full", "pre_6", "post"): | |
| # GAW, GAWD β GAD κ³μ°(μ£Ό*7 + μΌ β 'μΌμ' κΈ°μ€; νμ΅ μ€ν€λ§μ λ§μΆ° μ¬μ©) | |
| gaw = st.number_input(L("μμ μ£Όμ","Gestational Weeks"), 20, 50, 28) | |
| gawd = st.number_input(L("μμ μΌμ","Gestational Days"), 0, 6, 0) | |
| gad = gaw*7 + gawd # νμ΅μμ 'gad'κ° μΌμ κΈ°λ°μΌ λ. (μ£Ό.μΌ μμ κΈ°λ°μ΄λ©΄ μ¬κΈ° λ‘μ§ λ³κ²½) | |
| if mode_key in ("pre_full","pre_6"): | |
| # κ³΅ν΅ μ λ ₯ | |
| bwei = st.number_input(L("μΆμ μ²΄μ€ (g)","Birth weight (g)"), 200, 5000, 1000, step=10) | |
| sex = st.selectbox(L("μ±λ³","Sex"), [1,2,3], index=0, | |
| format_func=lambda x: {1:L("λ¨μ","Male"),2:L("μ¬μ","Female"),3:L("λ―ΈλΆλ₯","Ambiguous")}[x]) | |
| # μ°μ -ν μΆκ° νλͺ© | |
| if mode_key=="pre_full": | |
| values.update({ | |
| 'mage': st.number_input(L("μ°λͺ¨ λμ΄","Maternal age"), 15, 60, 33), | |
| 'gran': st.number_input(L("μμ λ ₯","Gravidity"), 0, 15, 1), | |
| 'parn': st.number_input(L("μΆμ°λ ₯","Parity"), 0, 10, 0), | |
| 'amni': st.selectbox(L("μμλ","Amniotic fluid"), [1,2,3,4], index=0, | |
| format_func=lambda v: {1:L("μ μ","Normal"),2:L("κ³Όμ","Oligo"),3:L("κ³Όλ€","Poly"),4:L("λͺ¨λ¦","Unknown")}[v]), | |
| 'mulg': st.selectbox(L("λ€ν μ 보","Multiplicity"), [1,2,3,4], index=0, | |
| format_func=lambda v: {1:"Singleton",2:"Twin",3:"Triplet",4:"Quad+"}[v]), | |
| 'bir' : st.selectbox(L("μΆμ μμ","Birth order"), [0,1,2,3,4], index=0, | |
| format_func=lambda v: {0:L("λ¨ν","Single"),1:"1st",2:"2nd",3:"3rd",4:"4th+"}[v]), | |
| 'prep': st.selectbox(L("μμ κ³Όμ ","Pregnancy type"), [1,2], index=0, | |
| format_func=lambda v: {1:L("μμ°μμ ","Natural"),2:"IVF"}[v]), | |
| 'dm' : st.selectbox(L("λΉλ¨","Diabetes"), [1,2,3], index=0, | |
| format_func=lambda v: {1:L("μμ","None"),2:"GDM",3:"Overt"}[v]), | |
| 'htn' : st.selectbox(L("κ³ νμ","Hypertension"), [1,2,3], index=0, | |
| format_func=lambda v: {1:L("μμ","None"),2:"PIH",3:L("λ§μ±","Chronic")}[v]), | |
| 'chor': st.selectbox(L("μ΅λͺ¨μλ§μΌ","Chorioamnionitis"), [1,2,3], index=0, | |
| format_func=lambda v: {1:L("μμ","No"),2:L("μμ","Yes"),3:L("λͺ¨λ¦","Unknown")}[v]), | |
| 'prom': st.selectbox(L("μ‘°κΈ° μλ§ νμ΄","PROM"), [1,2,3], index=0, | |
| format_func=lambda v: {1:L("μμ","No"),2:L("μμ","Yes"),3:L("λͺ¨λ¦","Unknown")}[v]), | |
| 'ster': st.selectbox(L("μ€ν λ‘μ΄λ μ¬μ©","Antenatal steroid"), [1,2,3], index=1, | |
| format_func=lambda v: {1:L("μμ","No"),2:L("μμ","Yes"),3:L("λͺ¨λ¦","Unknown")}[v]), | |
| 'sterp': st.selectbox(L("μ€ν λ‘μ΄λ μλ£ μ¬λΆ","Steroid completion"), [0,1,2,3], index=2, | |
| format_func=lambda v: {0:L("λ―Έν¬μ¬","None"),1:L("λ―Έμλ£","Incomplete"),2:L("μλ£","Complete"),3:L("λͺ¨λ¦","Unknown")}[v]), | |
| 'sterd': st.selectbox(L("μ€ν λ‘μ΄λ μ½μ ","Steroid type"), [0,1,2,3,4], index=0, | |
| format_func=lambda v: {0:L("λ―Έν¬μ¬","None"),1:"Dexa",2:"Beta",3:"Dexa+Beta",4:L("λͺ¨λ¦","Unknown")}[v]), | |
| 'atbyn': st.selectbox(L("νμμ μ¬μ©","Antibiotics"), [1,2], index=1, | |
| format_func=lambda v: {1:L("μμ","No"),2:L("μμ","Yes")}[v]), | |
| 'delm' : st.selectbox(L("λΆλ§ λ°©μ","Delivery mode"), [1,2], index=1, | |
| format_func=lambda v: {1:L("μ§μλΆλ§","Vaginal"),2:L("μ μμ κ°","Cesarean")}[v]), | |
| }) | |
| values['gad'] = float(gad) | |
| values['sex'] = int(sex) | |
| values['bwei'] = int(bwei) | |
| else: | |
| # μ°μ -6κ° | |
| values.update({ | |
| 'bwei': int(bwei), | |
| 'gad' : float(gad), | |
| 'mage': st.number_input(L("μ°λͺ¨ λμ΄","Maternal age"), 15, 60, 33), | |
| 'gran': st.number_input(L("μμ λ ₯","Gravidity"), 0, 15, 1), | |
| 'chor': st.selectbox(L("μ΅λͺ¨μλ§μΌ","Chorioamnionitis"), [0,1], index=0, | |
| format_func=lambda v: {0:L("μμ","No"),1:L("μμ","Yes")}[v]), | |
| 'sterp': st.selectbox(L("μ€ν λ‘μ΄λ λ°λ³΅(β₯2ν)","Repeated steroid (β₯2)"), [0,1], index=1, | |
| format_func=lambda v: {0:L("μλμ€","No"),1:L("μ","Yes")}[v]), | |
| }) | |
| elif mode_key=="post": | |
| # μ°ν μ λ ₯(νμμ λ§κ² κ΅μ²΄ κ°λ₯) | |
| bwei = st.number_input(L("μΆμ μ²΄μ€ (g)","Birth weight (g)"), 200, 5000, 1000, step=10) | |
| sex = st.selectbox(L("μ±λ³","Sex"), [1,2,3], index=0, | |
| format_func=lambda x: {1:L("λ¨μ","Male"),2:L("μ¬μ","Female"),3:L("λ―ΈλΆλ₯","Ambiguous")}[x]) | |
| values.update({ | |
| 'gad': float(gad), 'bwei': int(bwei), 'sex': int(sex), | |
| 'apgar1': st.number_input("Apgar 1", 0, 10, 5), | |
| 'apgar5': st.number_input("Apgar 5", 0, 10, 7), | |
| 'temp0h': st.number_input(L("체μ¨(0h)","Temp(0h)"), 30.0, 40.0, 36.5, step=0.1), | |
| 'respsup': st.selectbox(L("νΈν‘ μ§μ","Resp. support"), [0,1], index=1, | |
| format_func=lambda v: {0:L("μμ","No"),1:L("μμ","Yes")}[v]), | |
| 'fio2_0h': st.number_input("FiO2(0h)", 0.0, 1.0, 0.40, step=0.01), | |
| 'ph_0h' : st.number_input("pH(0h)", 6.5, 7.6, 7.25, step=0.01), | |
| 'be_0h' : st.number_input("Base excess(0h)", -30.0, 10.0, -6.0, step=0.1), | |
| }) | |
| # λͺ¨λλ³ x_order νμ | |
| X_ORDER = {"pre_full": XORDER_PRE_FULL, "pre_6": XORDER_PRE_6, "post": XORDER_POST}[mode_key] | |
| # ----------------------------- | |
| # 2. λͺ¨λΈ/μκ³μΉ λ‘λ | |
| # ----------------------------- | |
| thresh_df = _read_thresholds_for_mode(mode_key) | |
| thresh_map = {(str(r.target), str(r.model)): float(r.threshold) for r in thresh_df.itertuples()} if len(thresh_df) else {} | |
| models_dir = _model_dirs_for_mode(mode_key) | |
| targets = _discover_targets(mode_key, thresh_df, models_dir) | |
| # ----------------------------- | |
| # 3. μμΈ‘ μ΅μ (κ²°μ μ© λͺ¨λΈ) | |
| # ----------------------------- | |
| dec_label = L("κ²°μ μ© λͺ¨λΈ","Decision model") | |
| decision_model = st.selectbox(dec_label, ["Auto"] + MODEL_TYPES, index=0, | |
| help=L("Flag(μκ³μΉ λΉκ΅) μ°μΆμ μ¬μ©ν λͺ¨λΈμ κ³ λ¦ λλ€.", | |
| "Choose the model used to compute Flag via threshold.")) | |
| # ----------------------------- | |
| # 4. μμΈ‘ μ€ν | |
| # ----------------------------- | |
| run = st.button(L("μμΈ‘ μ€ν","Run prediction"), type="primary", use_container_width=True) | |
| def _load_model_if_exists(mdir, model_name, target): | |
| path = os.path.join(mdir, f"best_{model_name}_{target}.pkl") | |
| if os.path.exists(path): | |
| try: | |
| return _load_joblib(path) | |
| except Exception: | |
| return None | |
| return None | |
| def _decision_pick(probs_by_model: dict[str,float|None]) -> tuple[str|None, float|None]: | |
| """Auto λͺ¨λ: MODEL_TYPES μμλλ‘ μ‘΄μ¬νλ 첫 λͺ¨λΈμ μ ν""" | |
| for m in MODEL_TYPES: | |
| if m in probs_by_model and probs_by_model[m] is not None: | |
| return m, probs_by_model[m] | |
| return None, None | |
| if run: | |
| # μ λ ₯κ° β DataFrame | |
| try: | |
| X = _make_input_df(mode_key, values, X_ORDER) | |
| except KeyError as e: | |
| st.error(L(f"μ λ ₯ λλ½ λλ μλͺ»λ λ³μ: {e}","Missing or wrong input field: {e}")) | |
| st.stop() | |
| # κ° νκΉμ λν΄ 3κ° λͺ¨λΈ νλ₯ μ λͺ¨λ κ³μ° | |
| rows = [] | |
| for tgt in targets: | |
| # λͺ¨λΈ λ‘λ© | |
| ests = {m: _load_model_if_exists(models_dir, m, tgt) for m in MODEL_TYPES} | |
| # νλ₯ κ³μ° | |
| probs = {m: (_predict_proba(ests[m], X) if ests[m] is not None else None) for m in MODEL_TYPES} | |
| # κ²°μ μ© λͺ¨λΈ μ ν | |
| if decision_model == "Auto": | |
| pick_model, pick_prob = _decision_pick(probs) | |
| else: | |
| pick_model = decision_model | |
| pick_prob = probs.get(pick_model) | |
| # μκ³κ° (μμΌλ©΄ 0.5) | |
| thr = thresh_map.get((tgt, pick_model), 0.5) if pick_model else 0.5 | |
| flag = (pick_prob is not None) and (pick_prob >= thr) | |
| # νμ λΌλ²¨ | |
| y_name = (Y_LABEL_KO if lang=="νκ΅μ΄" else Y_LABEL_EN).get(tgt, tgt) | |
| rows.append({ | |
| "target": tgt, | |
| "Outcome": y_name, | |
| "LightGBM": _fmt_prob(probs["LightGBM"]), | |
| "XGBoost": _fmt_prob(probs["XGBoost"]), | |
| "RandomForest": _fmt_prob(probs["RandomForest"]), | |
| "DecisionModel": pick_model if pick_model else "-", | |
| "Threshold": f"{thr:.2f}" if pick_model else "-", | |
| "Flag": "β " if flag else "" | |
| }) | |
| # ν λΆλ¦¬(μμμ / ν©λ³μ¦) | |
| df = pd.DataFrame(rows) | |
| df_resus = df[df["target"].isin(RESUS_GROUP)].copy() | |
| df_comp = df[~df["target"].isin(RESUS_GROUP)].copy() | |
| # μ λ ¬(κ°λ μ±) | |
| df_resus = df_resus.sort_values("target") | |
| df_comp = df_comp.sort_values("target") | |
| st.markdown("### " + L("μ μμ μμμ κ΄λ ¨ μμΈ‘","Resuscitation predictions")) | |
| st.dataframe(df_resus.drop(columns=["target"]), use_container_width=True) | |
| st.markdown("### " + L("ν©λ³μ¦/μν μμΈ‘","Complication/Outcome predictions")) | |
| st.dataframe(df_comp.drop(columns=["target"]), use_container_width=True) | |
| # μ°μ 6κ° λͺ¨λ: μμ λ€μ΄λ‘λ μ 곡νμ§ μμ (μꡬμ¬ν) | |
| if mode_key != "pre_6": | |
| # νμ μ κ²°κ³Ό/λ©νλ§ ν¬ν¨ν μμ μ 곡(λ―Όκ° μ λ ₯ μ μ₯ μ ν¨) | |
| def _to_excel(pred_df: pd.DataFrame) -> bytes: | |
| from openpyxl import Workbook | |
| wb = Workbook() | |
| ws1 = wb.active; ws1.title = "Predictions" | |
| ws1.append([c for c in pred_df.columns if c!="target"]) | |
| for _, r in pred_df.drop(columns=["target"]).iterrows(): | |
| ws1.append(list(r.values)) | |
| # λ©ν | |
| ws2 = wb.create_sheet("Meta") | |
| ws2.append(["model_set", mode_key]) | |
| ws2.append(["created_at", datetime.now().strftime("%Y-%m-%d %H:%M")]) | |
| ws2.append(["threshold_file", next((f for f in THRESH_FILES.get(mode_key, []) if os.path.exists(f)), "N/A")]) | |
| bio = io.BytesIO(); wb.save(bio); bio.seek(0) | |
| return bio.getvalue() | |
| fname = f"KNN_Pred_{mode_key}_{datetime.now().strftime('%Y%m%d_%H%M')}.xlsx" | |
| st.download_button( | |
| L("μμ λ€μ΄λ‘λ","Download Excel"), | |
| data=_to_excel(df), | |
| file_name=fname, | |
| mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", | |
| use_container_width=True | |
| ) | |
| st.divider() | |
| st.caption(L( | |
| "β» λ³Έ λꡬλ μ°κ΅¬Β·κ²ν μ©μ λλ€. μλ£μ νλ¨μ λ체νμ§ μμΌλ©°, μμ μ¬μ© μ λ΄λΉ μλ£μ§μ κ²ν κ° νμν©λλ€.", | |
| "β» This tool is for research/review only. It does not replace clinical judgment." | |
| )) | |