# FrailDMDeprescribe-Kor (프레일디엠디프리스크라이브코어)

**노인 당뇨 코호트의 노쇠 stratification · KDA 노인당뇨 target 완화 부합률 · SU/glargine deprescribing 워크플로 · outcome 추적을 한 화면에서 운영하는 standalone Streamlit 대시보드.**

- **도메인**: DM (노인당뇨 + frailty + deprescribing)
- **카테고리**: 웹기반 대시보드 (코호트 모니터링·KPI 추적)
- **빌드 날짜**: 2026-05-20
- **언어**: 한국어 UI / 영문 변수명

---

## ⚠️ 의학 디스클레이머

본 대시보드는 **연구·교육·quality improvement(QI) 보조용**이며, 실제 임상 의사결정은 담당 의사 판단 하에 이루어져야 합니다. 본 저장소에 포함된 데이터는 **합성 시뮬레이션 데이터**(`data/generate_synthetic.py`로 생성, seed=20260520)이며 실제 환자 데이터를 포함하지 않습니다. 외부 EMR 또는 환자 식별 정보와의 연동은 IRB 승인과 보안 검토를 거친 별도 배포 환경에서 수행해야 합니다.

---

## 핵심 기능 (5개)

1. **노쇠 다층 phenotype 패널** — K-FRAIL(5항목)·CFS(1~9)·K-MNA short form·ADL(Katz)·IADL(Lawton)·MMSE-K·polypharmacy를 통합하여 cohort를 robust / pre-frail / frail로 stratify하고 radar·box·pie로 시각화.
2. **KDA 노인당뇨 target 완화 부합률** — KDA 2023 / ADA 2025 Older Adults 기준 phenotype별 HbA1c band(robust 6.5~7.5% / pre-frail 7.5~8.0% / frail 7.5~8.5% / EoL <8.5%)를 자동 분류, overtreatment(lower 미만) 환자 flag.
3. **SU·인슐린 deprescribing 워크플로** — SU(glimepiride / glibenclamide / gliclazide) 및 NPH·glargine·detemir·degludec 사용자 중 deprescribing 후보(frail 또는 overtreatment) 식별, 단계(`candidate → recommended → tapering → completed`) funnel·heatmap 추적.
4. **저혈당·낙상·재입원 outcome 추적** — 12개월 outcome(중증 저혈당 ED·낙상·골절·재입원·사망)을 phenotype별 비교 + deprescribing 진행/미진행 그룹 before-after 표 + 저혈당 ED-free 곡선(lifelines KM; 미설치 시 내장 fallback).
5. **KDA·KGS·KAFM 가이드 호환 리포트 export** — 외래 QI 리포트(.docx · .txt 다운로드). 인용 가이드라인 source 자동 포함.

---

## 실행 방법

```bash
# 1) (옵션) 가상환경
python3 -m venv .venv && source .venv/bin/activate

# 2) 의존성 설치
pip install -r requirements.txt

# 3) 합성 데이터 생성 (n=360)
python3 data/generate_synthetic.py

# 4) Streamlit 대시보드 실행
streamlit run app.py
```

브라우저에서 `http://localhost:8501`을 열면 5개 탭이 표시된다.

> **오프라인 동작 보장**: 외부 네트워크/API 호출 없음. `lifelines` / `python-docx`는 누락되어도 대시보드 자체는 동작하며, 해당 기능만 fallback(내장 KM, txt 리포트) 처리.

---

## 디렉토리 구조

```
2026-05-20-1-frail-dm-deprescribe-kor/
├── README.md                  # 본 문서
├── CHANGELOG.md               # 변경 로그
├── QA.md                      # 검수 로그
├── requirements.txt           # 의존성
├── app.py                     # Streamlit 진입점
├── assets/
│   └── guidelines.json        # KDA/ADA/Beers/STOPP/KAFM/KGS 권고 라이브러리(한국어)
└── data/
    ├── generate_synthetic.py  # 합성 cohort 생성 스크립트 (seed=20260520, n=360)
    └── synthetic_frail_dm_cohort.csv  # 합성 데이터 (생성 후 산출)
```

### 합성 cohort 컬럼 요약

`patient_id, enroll_date, age, sex, phenotype, k_frail_*(5항목), k_frail_total, cfs, k_mna_short, adl_katz, iadl_lawton, mmse_k, cognition_ok, end_of_life, dm_duration_yr, polypharmacy_n, egfr_ml_min_173, hba1c_baseline_pct, hba1c_target_lower, hba1c_target_upper, overtreated_baseline, drugs, uses_sulfonylurea, sulfonylurea_drug, uses_insulin, insulin_drug, deprescribe_candidate, deprescribe_stage, hba1c_followup_pct, severe_hypo_ed_12mo, fall_12mo, fracture_12mo, readmission_12mo, death_12mo, time_to_event_days`

---

## 검수 체크리스트

- [x] `python3 -c "import ast; ast.parse(open('app.py').read())"` — 구문 OK
- [x] `python3 -c "import ast; ast.parse(open('data/generate_synthetic.py').read())"` — 구문 OK
- [x] `python3 data/generate_synthetic.py` — CSV 생성 OK
- [x] `python3 -c "import pandas as pd; df=pd.read_csv('data/synthetic_frail_dm_cohort.csv'); print(df.shape)"` — 로드 OK
- [x] `python3 -m py_compile app.py` — bytecode 컴파일 OK
- [x] `requirements.txt` 존재 (streamlit, pandas, numpy, plotly, lifelines, python-docx)
- [x] `assets/guidelines.json` JSON 파싱 OK
- [x] 의학 디스클레이머 README / app UI 양쪽 명시
- [x] 외부 네트워크/API 호출 없음 (코드 grep로 확인)

---

## 출처 (인용)

1. **대한당뇨병학회**. 당뇨병 진료지침 제8판(2023), 제15장 노인당뇨병.
2. American Diabetes Association. *Standards of Care in Diabetes – 2025*. Section 13. Older Adults. **Diabetes Care 2025;48(Suppl 1):S266-S282**.
3. By the American Geriatrics Society. **AGS Beers Criteria® 2023**. *J Am Geriatr Soc* 2023;71(7):2052-2081.
4. O'Mahony D et al. **STOPP/START criteria for potentially inappropriate prescribing in older people: version 3**. *Eur Geriatr Med* 2023;14(4):625-632.
5. 대한가정의학회·대한노인병학회. **노인 환자 다약제 처방 가이드라인** (2022 update).
6. Rockwood K et al. **Clinical Frailty Scale**. *CMAJ* 2005;174(5):489-495.
7. Morley JE et al. **A simple frailty questionnaire (FRAIL)**. *J Nutr Health Aging* 2012;16(7):601-608.
8. Kaiser MJ et al. **MNA short form**. *J Am Geriatr Soc* 2009;57(9):1734-1738.

---

## 로드맵 (포스트-MVP)

- EMR FHIR Observation/MedicationStatement 어댑터 (별도 보안 환경)
- 다기관 federated KPI 비교 (k-anonymity 보장)
- 한국어 NLP 기반 외래 차트 frailty signal 추출
- KDA 외래 QI 인증 지표 자동 매핑
