# 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"} # ----------------------------- # 유틸 # ----------------------------- @st.cache_resource(show_spinner=False) 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." ))