diff --git a/.gitignore b/.gitignore index 61edce2..b778a07 100644 --- a/.gitignore +++ b/.gitignore @@ -101,10 +101,16 @@ models/embeddings/* !models/gguf/.gitkeep # Large External Datasets & User Uploads +Database/ +database/ +*.xls +*.xlsx data/icd10/*.txt data/icd10/*.xml data/samples/*.pdf !data/samples/.gitkeep !data/icd10/.gitkeep !data/icd10/sample_hospital_icd.csv +# Search Index Artifacts +data/indexes/* !data/indexes/.gitkeep diff --git a/README.md b/README.md index e4d6428..704ef51 100644 --- a/README.md +++ b/README.md @@ -272,88 +272,141 @@ Agentic_ICD_Code_Matcher/ ## 6. Installation & Environment Setup -### Prerequisites -- **Operating System**: Windows 10/11, macOS, or Linux (Ubuntu 22.04+) -- **Python**: Version `3.13+` (recommended: `3.13.x`) -- **System Memory**: Minimum 8 GB RAM (16 GB recommended for 7B GGUF models) -- **Disk Space**: ~500 MB for base dependencies, ~4 GB for GGUF model weights +### 🚀 Automated Quick-Start Installers (Windows & Linux) + +The repository provides cross-platform installer scripts that automate the entire setup: +- Creates a clean Python virtual environment (`env`) +- Upgrades `pip`, `setuptools`, and `wheel` +- Installs all dependencies from `requirements.txt` +- Configures `.env` from `.env.example` +- Detects the local `Database/` folder (ICD-10-CM, ICD-O, CPT) and builds/verifies FAISS & BM25 search indexes + +> [!IMPORTANT] +> **Strict Separation of Concerns**: The installer scripts **only** install and configure the environment. They **do not** start the application. Use the dedicated runner scripts to start the app. + +#### Windows (Batch or PowerShell): +```cmd +:: Using Command Prompt (Batch) +install.bat +``` +or +```powershell +# Using PowerShell +.\install.ps1 +``` + +#### Linux / macOS: +```bash +chmod +x install.sh run.sh +./install.sh +``` --- -### Step 1: Clone the Repository +### 🏃 Dedicated Runners (Windows & Linux) + +Once installed, use the runner script to start the interface: + +#### Windows: +```cmd +:: Launch Streamlit Web UI (Default) +run.bat + +:: Or launch in PowerShell +.\run.ps1 + +:: Launch FastAPI REST Service +run.bat --api +:: Or in PowerShell: .\run.ps1 -Api +``` + +#### Linux / macOS: ```bash +:: Launch Streamlit Web UI +./run.sh + +:: Launch FastAPI REST Service +./run.sh --api +``` + +--- + +### Manual Setup (Alternative) + +```bash +# Clone the repository git clone https://github.com/AbhinavEliac/Agentic_ICD_Code_Matcher.git cd Agentic_ICD_Code_Matcher -``` ---- - -### Step 2: Create and Activate Virtual Environment - -**Windows (PowerShell):** -```powershell +# Create virtual environment python -m venv env -.\env\Scripts\Activate.ps1 -``` -**Linux / macOS:** -```bash -python3 -m venv env +# Activate (Windows) +.\env\Scripts\activate +# Activate (Linux/macOS) source env/bin/activate -``` ---- - -### Step 3: Install Dependencies -```bash -pip install --upgrade pip +# Install dependencies +pip install --upgrade pip setuptools wheel pip install -r requirements.txt -``` ---- - -### Step 4: Configure Environment Variables -Copy the example environment configuration: -```bash +# Copy environment template cp .env.example .env ``` -Key settings in `.env`: -```ini -# Environment -ENVIRONMENT=development -LOG_LEVEL=INFO - -# Concurrency -MAX_BATCH_CONCURRENCY=10 -LLM_MAX_CONCURRENCY=1 - -# Local Retrieval Paths -ICD_DATA_PATH=./data/icd10/sample_hospital_icd.csv -INDEX_DIR=./data/indexes - -# Offline Model Paths -GGUF_MODEL_PATH=./models/gguf/mistral-7b-instruct-v0.2.Q4_K_M.gguf -EMBEDDING_MODEL_PATH=./models/embeddings/bge-small-en-v1.5 -ALLOW_MODEL_DOWNLOAD=false - -# Persistence -DATABASE_URL=sqlite:///./data/medical_coding.db -``` --- -## 7. Dataset Ingestion & Offline Indexing +## 7. Local Database & Authoritative Multi-System Matching -The repository comes pre-packaged with verified sample indexes in `data/indexes/` so you can test immediately. To build or re-index your own hospital ICD catalog (CSV, TSV, or CMS text format): +The engine performs zero-hallucination vector and semantic matching against authoritative medical coding workbooks located in the local `Database/` directory (`Database_1.xls` / `Database_2.xlsx`): +- **ICD-10-CM**: 74,700+ authoritative clinical diagnosis codes +- **ICD-O**: 800+ oncology / morphology codes (`^M[89][0-9]{3}`) +- **CPT**: 7,700+ current procedural terminology codes +- **Privacy & Security**: The `Database/` directory is strictly kept in local storage and is ignored in version control (`.gitignore`) with zero remote exposure. -```bash -python scripts/index_icd.py --source data/icd10/sample_hospital_icd.csv --output data/indexes +### Standardized Structured JSON Output Format + +For every matched condition, the engine outputs deterministic structured JSON adhering strictly to: + +```json +{ + "code": "I50.21", + "description": "Acute systolic (congestive) heart failure", + "role": "PRIMARY", + "acuity": "ACUTE", + "certainty": "CONFIRMED", + "evidence_quote": "Patient presented with acute decompensated systolic heart failure.", + "confidence_score": 0.96, + "is_terminal_billable": true, + "icd10cm": "I50.21", + "icdo": null, + "cpt": null +} ``` -Options: -- `--source`: Path to raw CSV/TXT containing columns `code`, `description`, `billable`, `excludes1` -- `--output`: Destination directory for FAISS vector index and BM25 caches -- `--force-fast-embeddings`: Generates deterministic fast local embeddings without downloading neural weights +If an oncology morphology or procedure is matched, the corresponding `icdo` or `cpt` field is populated with the authoritative local code (or `null` if not matched): + +```json +{ + "code": "C50.911", + "description": "Malignant neoplasm of unspecified site of right female breast", + "role": "PRIMARY", + "acuity": "UNSPECIFIED", + "certainty": "CONFIRMED", + "evidence_quote": "Biopsy confirmed right breast infiltrating duct carcinoma.", + "confidence_score": 0.94, + "is_terminal_billable": true, + "icd10cm": "C50.911", + "icdo": "M8500.3", + "cpt": "19120" +} +``` + +### Building & Re-indexing Search Indexes +```bash +python scripts/index_icd.py --force-fast-embeddings +``` +The indexing script automatically checks for `Database/Database_2.xlsx`, ingests all sheets, and serializes the BM25 and FAISS vector index artifacts directly into `data/indexes/`. --- diff --git a/data/indexes/bm25_index.pkl b/data/indexes/bm25_index.pkl deleted file mode 100644 index a411785..0000000 Binary files a/data/indexes/bm25_index.pkl and /dev/null differ diff --git a/data/indexes/faiss.index b/data/indexes/faiss.index deleted file mode 100644 index 427ee3d..0000000 Binary files a/data/indexes/faiss.index and /dev/null differ diff --git a/data/indexes/faiss_records.json b/data/indexes/faiss_records.json deleted file mode 100644 index 793b565..0000000 --- a/data/indexes/faiss_records.json +++ /dev/null @@ -1,750 +0,0 @@ -{ - "dimension": 384, - "total_records": 25, - "records": [ - { - "code": "I50.21", - "description": "Acute systolic heart failure", - "unformatted_code": "I5021", - "short_description": "Acute systolic heart failure", - "long_description": "Acute systolic heart failure", - "is_valid_billable": true, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Acute congestive heart failure with systolic dysfunction", - "Acute systolic ventricular failure" - ], - "exclusion_terms": [ - "Combined systolic and diastolic heart failure (I50.4-)" - ], - "synonyms": [ - "acute systolic HF", - "acute decompensated systolic heart failure", - "HFrEF acute", - "acute systolic cardiac failure" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I50.22", - "description": "Chronic systolic heart failure", - "unformatted_code": "I5022", - "short_description": "Chronic systolic heart failure", - "long_description": "Chronic systolic heart failure", - "is_valid_billable": true, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Chronic congestive heart failure with systolic dysfunction" - ], - "exclusion_terms": [ - "Combined systolic and diastolic heart failure (I50.4-)" - ], - "synonyms": [ - "chronic systolic HF", - "compensated systolic heart failure", - "chronic HFrEF" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I50.23", - "description": "Acute on chronic systolic heart failure", - "unformatted_code": "I5023", - "short_description": "Acute on chronic systolic heart failure", - "long_description": "Acute on chronic systolic heart failure", - "is_valid_billable": true, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Acute exacerbation of chronic systolic congestive heart failure" - ], - "exclusion_terms": [ - "Combined systolic and diastolic heart failure (I50.4-)" - ], - "synonyms": [ - "acute on chronic systolic HF", - "acute decompensation of chronic HFrEF", - "acute exacerbation of chronic systolic heart failure" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I50.31", - "description": "Acute diastolic heart failure", - "unformatted_code": "I5031", - "short_description": "Acute diastolic heart failure", - "long_description": "Acute diastolic heart failure", - "is_valid_billable": true, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Acute congestive heart failure with diastolic dysfunction", - "Acute diastolic ventricular failure" - ], - "exclusion_terms": [ - "Combined systolic and diastolic heart failure (I50.4-)" - ], - "synonyms": [ - "acute diastolic HF", - "HFpEF acute", - "acute decompensated diastolic heart failure" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I50.32", - "description": "Chronic diastolic heart failure", - "unformatted_code": "I5032", - "short_description": "Chronic diastolic heart failure", - "long_description": "Chronic diastolic heart failure", - "is_valid_billable": true, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Chronic congestive heart failure with diastolic dysfunction" - ], - "exclusion_terms": [ - "Combined systolic and diastolic heart failure (I50.4-)" - ], - "synonyms": [ - "chronic diastolic HF", - "HFpEF chronic", - "chronic diastolic heart failure" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I50.33", - "description": "Acute on chronic diastolic heart failure", - "unformatted_code": "I5033", - "short_description": "Acute on chronic diastolic heart failure", - "long_description": "Acute on chronic diastolic heart failure", - "is_valid_billable": true, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Acute exacerbation of chronic diastolic congestive heart failure" - ], - "exclusion_terms": [ - "Combined systolic and diastolic heart failure (I50.4-)" - ], - "synonyms": [ - "acute on chronic diastolic HF", - "acute exacerbation of HFpEF" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I50.9", - "description": "Heart failure unspecified", - "unformatted_code": "I509", - "short_description": "Heart failure unspecified", - "long_description": "Heart failure unspecified", - "is_valid_billable": true, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Congestive heart failure NOS", - "Cardiac, heart or myocardial failure NOS" - ], - "exclusion_terms": [ - "Neonatal cardiac failure (P29.0)" - ], - "synonyms": [ - "HF", - "CHF", - "heart failure", - "congestive heart failure", - "cardiac decompensation" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I50", - "description": "Heart failure category header", - "unformatted_code": "I50", - "short_description": "Heart failure category header", - "long_description": "Heart failure category header", - "is_valid_billable": false, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Heart failure categories and definitions" - ], - "exclusion_terms": [], - "synonyms": [ - "heart failure parent category" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "E11.9", - "description": "Type 2 diabetes mellitus without complications", - "unformatted_code": "E119", - "short_description": "Type 2 diabetes mellitus without complications", - "long_description": "Type 2 diabetes mellitus without complications", - "is_valid_billable": true, - "chapter": null, - "category": "E11", - "inclusion_terms": [ - "Diabetes mellitus type 2 NOS", - "Non-insulin-dependent diabetes NOS" - ], - "exclusion_terms": [ - "Gestational diabetes (O24.4-)", - "Type 1 diabetes mellitus (E10.-)" - ], - "synonyms": [ - "T2DM", - "DM2", - "type 2 diabetes", - "diabetes type II", - "non-insulin dependent diabetes" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "E11.65", - "description": "Type 2 diabetes mellitus with hyperglycemia", - "unformatted_code": "E1165", - "short_description": "Type 2 diabetes mellitus with hyperglycemia", - "long_description": "Type 2 diabetes mellitus with hyperglycemia", - "is_valid_billable": true, - "chapter": null, - "category": "E11", - "inclusion_terms": [ - "Type 2 diabetes mellitus with poor glycemic control" - ], - "exclusion_terms": [], - "synonyms": [ - "T2DM with hyperglycemia", - "uncontrolled type 2 diabetes", - "elevated blood sugar in T2DM" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "E11.21", - "description": "Type 2 diabetes mellitus with diabetic nephropathy", - "unformatted_code": "E1121", - "short_description": "Type 2 diabetes mellitus with diabetic nephropathy", - "long_description": "Type 2 diabetes mellitus with diabetic nephropathy", - "is_valid_billable": true, - "chapter": null, - "category": "E11", - "inclusion_terms": [ - "Type 2 diabetes mellitus with intercapillary glomerulosclerosis" - ], - "exclusion_terms": [], - "synonyms": [ - "diabetic kidney disease type 2", - "diabetic nephropathy", - "T2DM nephropathy" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I10", - "description": "Essential primary hypertension", - "unformatted_code": "I10", - "short_description": "Essential primary hypertension", - "long_description": "Essential primary hypertension", - "is_valid_billable": true, - "chapter": null, - "category": "I10", - "inclusion_terms": [ - "High blood pressure", - "Arterial hypertension" - ], - "exclusion_terms": [ - "Hypertensive heart disease (I11.-)", - "Hypertensive renal disease (I12.-)" - ], - "synonyms": [ - "HTN", - "primary hypertension", - "high blood pressure", - "arterial HTN", - "essential HTN" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "N18.3", - "description": "Chronic kidney disease stage 3", - "unformatted_code": "N183", - "short_description": "Chronic kidney disease stage 3", - "long_description": "Chronic kidney disease stage 3", - "is_valid_billable": true, - "chapter": null, - "category": "N18", - "inclusion_terms": [ - "Moderate chronic kidney disease", - "CKD stage 3" - ], - "exclusion_terms": [ - "Acute kidney failure (N17.-)" - ], - "synonyms": [ - "CKD 3", - "CKD stage III", - "stage 3 chronic kidney disease", - "moderate renal impairment" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "N18.4", - "description": "Chronic kidney disease stage 4", - "unformatted_code": "N184", - "short_description": "Chronic kidney disease stage 4", - "long_description": "Chronic kidney disease stage 4", - "is_valid_billable": true, - "chapter": null, - "category": "N18", - "inclusion_terms": [ - "Severe chronic kidney disease", - "CKD stage 4" - ], - "exclusion_terms": [ - "Acute kidney failure (N17.-)" - ], - "synonyms": [ - "CKD 4", - "CKD stage IV", - "severe chronic kidney disease", - "severe renal insufficiency" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "N18.9", - "description": "Chronic kidney disease unspecified", - "unformatted_code": "N189", - "short_description": "Chronic kidney disease unspecified", - "long_description": "Chronic kidney disease unspecified", - "is_valid_billable": true, - "chapter": null, - "category": "N18", - "inclusion_terms": [ - "Chronic renal disease", - "Chronic renal failure NOS" - ], - "exclusion_terms": [ - "Acute kidney failure (N17.-)" - ], - "synonyms": [ - "CKD", - "chronic kidney disease", - "chronic renal disease", - "chronic kidney failure" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "N17.9", - "description": "Acute kidney injury unspecified", - "unformatted_code": "N179", - "short_description": "Acute kidney injury unspecified", - "long_description": "Acute kidney injury unspecified", - "is_valid_billable": true, - "chapter": null, - "category": "N17", - "inclusion_terms": [ - "Acute renal failure NOS", - "Acute kidney injury NOS" - ], - "exclusion_terms": [ - "Chronic kidney disease (N18.-)" - ], - "synonyms": [ - "AKI", - "acute kidney injury", - "acute renal failure", - "ARF", - "renal insufficiency acute" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I48.0", - "description": "Paroxysmal atrial fibrillation", - "unformatted_code": "I480", - "short_description": "Paroxysmal atrial fibrillation", - "long_description": "Paroxysmal atrial fibrillation", - "is_valid_billable": true, - "chapter": null, - "category": "I48", - "inclusion_terms": [ - "Paroxysmal AF" - ], - "exclusion_terms": [], - "synonyms": [ - "paroxysmal AFib", - "intermittent atrial fibrillation", - "paroxysmal AF" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I48.91", - "description": "Unspecified atrial fibrillation", - "unformatted_code": "I4891", - "short_description": "Unspecified atrial fibrillation", - "long_description": "Unspecified atrial fibrillation", - "is_valid_billable": true, - "chapter": null, - "category": "I48", - "inclusion_terms": [ - "Atrial fibrillation NOS", - "Auricular fibrillation" - ], - "exclusion_terms": [], - "synonyms": [ - "AFib", - "AF", - "atrial fibrillation", - "auricular fibrillation" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "J18.9", - "description": "Pneumonia unspecified organism", - "unformatted_code": "J189", - "short_description": "Pneumonia unspecified organism", - "long_description": "Pneumonia unspecified organism", - "is_valid_billable": true, - "chapter": null, - "category": "J18", - "inclusion_terms": [ - "Pneumonia NOS" - ], - "exclusion_terms": [ - "Aspiration pneumonia (J69.0)", - "Viral pneumonia (J12.-)" - ], - "synonyms": [ - "PNA", - "pneumonia", - "lung infection", - "community acquired pneumonia NOS", - "CAP" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "J44.1", - "description": "Chronic obstructive pulmonary disease with acute exacerbation", - "unformatted_code": "J441", - "short_description": "Chronic obstructive pulmonary disease with acute exacerbation", - "long_description": "Chronic obstructive pulmonary disease with acute exacerbation", - "is_valid_billable": true, - "chapter": null, - "category": "J44", - "inclusion_terms": [ - "Decompensated COPD", - "COPD with acute exacerbation" - ], - "exclusion_terms": [], - "synonyms": [ - "acute COPD exacerbation", - "AECOPD", - "acute exacerbation of chronic obstructive bronchitis" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "J44.9", - "description": "Chronic obstructive pulmonary disease unspecified", - "unformatted_code": "J449", - "short_description": "Chronic obstructive pulmonary disease unspecified", - "long_description": "Chronic obstructive pulmonary disease unspecified", - "is_valid_billable": true, - "chapter": null, - "category": "J44", - "inclusion_terms": [ - "Chronic obstructive pulmonary disease NOS", - "Chronic bronchitis NOS" - ], - "exclusion_terms": [ - "Asthma (J45.-)" - ], - "synonyms": [ - "COPD", - "chronic obstructive lung disease", - "COLD" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "A41.9", - "description": "Sepsis unspecified organism", - "unformatted_code": "A419", - "short_description": "Sepsis unspecified organism", - "long_description": "Sepsis unspecified organism", - "is_valid_billable": true, - "chapter": null, - "category": "A41", - "inclusion_terms": [ - "Septicemia NOS", - "Sepsis NOS" - ], - "exclusion_terms": [ - "Severe sepsis (R65.2-)", - "Septic shock (R65.21)" - ], - "synonyms": [ - "sepsis", - "blood poisoning", - "septicemia", - "systemic infection" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "K21.9", - "description": "Gastro-esophageal reflux disease without esophagitis", - "unformatted_code": "K219", - "short_description": "Gastro-esophageal reflux disease without esophagitis", - "long_description": "Gastro-esophageal reflux disease without esophagitis", - "is_valid_billable": true, - "chapter": null, - "category": "K21", - "inclusion_terms": [ - "Acid reflux", - "GERD NOS" - ], - "exclusion_terms": [], - "synonyms": [ - "GERD", - "gastroesophageal reflux", - "acid reflux", - "reflux esophagitis" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I21.9", - "description": "Acute myocardial infarction unspecified", - "unformatted_code": "I219", - "short_description": "Acute myocardial infarction unspecified", - "long_description": "Acute myocardial infarction unspecified", - "is_valid_billable": true, - "chapter": null, - "category": "I21", - "inclusion_terms": [ - "Heart attack NOS", - "Myocardial infarction NOS" - ], - "exclusion_terms": [ - "Subsequent myocardial infarction (I22.-)" - ], - "synonyms": [ - "MI", - "AMI", - "acute MI", - "acute myocardial infarction", - "heart attack" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I21.09", - "description": "ST elevation myocardial infarction involving anterior wall", - "unformatted_code": "I2109", - "short_description": "ST elevation myocardial infarction involving anterior wall", - "long_description": "ST elevation myocardial infarction involving anterior wall", - "is_valid_billable": true, - "chapter": null, - "category": "I21", - "inclusion_terms": [ - "Transmural anterior myocardial infarction" - ], - "exclusion_terms": [], - "synonyms": [ - "anterior STEMI", - "STEMI anterior wall", - "acute anterior MI" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - } - ] -} \ No newline at end of file diff --git a/data/indexes/icd_catalog.json b/data/indexes/icd_catalog.json deleted file mode 100644 index ee8a2fc..0000000 --- a/data/indexes/icd_catalog.json +++ /dev/null @@ -1,760 +0,0 @@ -{ - "records": [ - { - "code": "I50.21", - "description": "Acute systolic heart failure", - "unformatted_code": "I5021", - "short_description": "Acute systolic heart failure", - "long_description": "Acute systolic heart failure", - "is_valid_billable": true, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Acute congestive heart failure with systolic dysfunction", - "Acute systolic ventricular failure" - ], - "exclusion_terms": [ - "Combined systolic and diastolic heart failure (I50.4-)" - ], - "synonyms": [ - "acute systolic HF", - "acute decompensated systolic heart failure", - "HFrEF acute", - "acute systolic cardiac failure" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I50.22", - "description": "Chronic systolic heart failure", - "unformatted_code": "I5022", - "short_description": "Chronic systolic heart failure", - "long_description": "Chronic systolic heart failure", - "is_valid_billable": true, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Chronic congestive heart failure with systolic dysfunction" - ], - "exclusion_terms": [ - "Combined systolic and diastolic heart failure (I50.4-)" - ], - "synonyms": [ - "chronic systolic HF", - "compensated systolic heart failure", - "chronic HFrEF" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I50.23", - "description": "Acute on chronic systolic heart failure", - "unformatted_code": "I5023", - "short_description": "Acute on chronic systolic heart failure", - "long_description": "Acute on chronic systolic heart failure", - "is_valid_billable": true, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Acute exacerbation of chronic systolic congestive heart failure" - ], - "exclusion_terms": [ - "Combined systolic and diastolic heart failure (I50.4-)" - ], - "synonyms": [ - "acute on chronic systolic HF", - "acute decompensation of chronic HFrEF", - "acute exacerbation of chronic systolic heart failure" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I50.31", - "description": "Acute diastolic heart failure", - "unformatted_code": "I5031", - "short_description": "Acute diastolic heart failure", - "long_description": "Acute diastolic heart failure", - "is_valid_billable": true, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Acute congestive heart failure with diastolic dysfunction", - "Acute diastolic ventricular failure" - ], - "exclusion_terms": [ - "Combined systolic and diastolic heart failure (I50.4-)" - ], - "synonyms": [ - "acute diastolic HF", - "HFpEF acute", - "acute decompensated diastolic heart failure" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I50.32", - "description": "Chronic diastolic heart failure", - "unformatted_code": "I5032", - "short_description": "Chronic diastolic heart failure", - "long_description": "Chronic diastolic heart failure", - "is_valid_billable": true, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Chronic congestive heart failure with diastolic dysfunction" - ], - "exclusion_terms": [ - "Combined systolic and diastolic heart failure (I50.4-)" - ], - "synonyms": [ - "chronic diastolic HF", - "HFpEF chronic", - "chronic diastolic heart failure" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I50.33", - "description": "Acute on chronic diastolic heart failure", - "unformatted_code": "I5033", - "short_description": "Acute on chronic diastolic heart failure", - "long_description": "Acute on chronic diastolic heart failure", - "is_valid_billable": true, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Acute exacerbation of chronic diastolic congestive heart failure" - ], - "exclusion_terms": [ - "Combined systolic and diastolic heart failure (I50.4-)" - ], - "synonyms": [ - "acute on chronic diastolic HF", - "acute exacerbation of HFpEF" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I50.9", - "description": "Heart failure unspecified", - "unformatted_code": "I509", - "short_description": "Heart failure unspecified", - "long_description": "Heart failure unspecified", - "is_valid_billable": true, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Congestive heart failure NOS", - "Cardiac, heart or myocardial failure NOS" - ], - "exclusion_terms": [ - "Neonatal cardiac failure (P29.0)" - ], - "synonyms": [ - "HF", - "CHF", - "heart failure", - "congestive heart failure", - "cardiac decompensation" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I50", - "description": "Heart failure category header", - "unformatted_code": "I50", - "short_description": "Heart failure category header", - "long_description": "Heart failure category header", - "is_valid_billable": false, - "chapter": null, - "category": "I50", - "inclusion_terms": [ - "Heart failure categories and definitions" - ], - "exclusion_terms": [], - "synonyms": [ - "heart failure parent category" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "E11.9", - "description": "Type 2 diabetes mellitus without complications", - "unformatted_code": "E119", - "short_description": "Type 2 diabetes mellitus without complications", - "long_description": "Type 2 diabetes mellitus without complications", - "is_valid_billable": true, - "chapter": null, - "category": "E11", - "inclusion_terms": [ - "Diabetes mellitus type 2 NOS", - "Non-insulin-dependent diabetes NOS" - ], - "exclusion_terms": [ - "Gestational diabetes (O24.4-)", - "Type 1 diabetes mellitus (E10.-)" - ], - "synonyms": [ - "T2DM", - "DM2", - "type 2 diabetes", - "diabetes type II", - "non-insulin dependent diabetes" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "E11.65", - "description": "Type 2 diabetes mellitus with hyperglycemia", - "unformatted_code": "E1165", - "short_description": "Type 2 diabetes mellitus with hyperglycemia", - "long_description": "Type 2 diabetes mellitus with hyperglycemia", - "is_valid_billable": true, - "chapter": null, - "category": "E11", - "inclusion_terms": [ - "Type 2 diabetes mellitus with poor glycemic control" - ], - "exclusion_terms": [], - "synonyms": [ - "T2DM with hyperglycemia", - "uncontrolled type 2 diabetes", - "elevated blood sugar in T2DM" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "E11.21", - "description": "Type 2 diabetes mellitus with diabetic nephropathy", - "unformatted_code": "E1121", - "short_description": "Type 2 diabetes mellitus with diabetic nephropathy", - "long_description": "Type 2 diabetes mellitus with diabetic nephropathy", - "is_valid_billable": true, - "chapter": null, - "category": "E11", - "inclusion_terms": [ - "Type 2 diabetes mellitus with intercapillary glomerulosclerosis" - ], - "exclusion_terms": [], - "synonyms": [ - "diabetic kidney disease type 2", - "diabetic nephropathy", - "T2DM nephropathy" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I10", - "description": "Essential primary hypertension", - "unformatted_code": "I10", - "short_description": "Essential primary hypertension", - "long_description": "Essential primary hypertension", - "is_valid_billable": true, - "chapter": null, - "category": "I10", - "inclusion_terms": [ - "High blood pressure", - "Arterial hypertension" - ], - "exclusion_terms": [ - "Hypertensive heart disease (I11.-)", - "Hypertensive renal disease (I12.-)" - ], - "synonyms": [ - "HTN", - "primary hypertension", - "high blood pressure", - "arterial HTN", - "essential HTN" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "N18.3", - "description": "Chronic kidney disease stage 3", - "unformatted_code": "N183", - "short_description": "Chronic kidney disease stage 3", - "long_description": "Chronic kidney disease stage 3", - "is_valid_billable": true, - "chapter": null, - "category": "N18", - "inclusion_terms": [ - "Moderate chronic kidney disease", - "CKD stage 3" - ], - "exclusion_terms": [ - "Acute kidney failure (N17.-)" - ], - "synonyms": [ - "CKD 3", - "CKD stage III", - "stage 3 chronic kidney disease", - "moderate renal impairment" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "N18.4", - "description": "Chronic kidney disease stage 4", - "unformatted_code": "N184", - "short_description": "Chronic kidney disease stage 4", - "long_description": "Chronic kidney disease stage 4", - "is_valid_billable": true, - "chapter": null, - "category": "N18", - "inclusion_terms": [ - "Severe chronic kidney disease", - "CKD stage 4" - ], - "exclusion_terms": [ - "Acute kidney failure (N17.-)" - ], - "synonyms": [ - "CKD 4", - "CKD stage IV", - "severe chronic kidney disease", - "severe renal insufficiency" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "N18.9", - "description": "Chronic kidney disease unspecified", - "unformatted_code": "N189", - "short_description": "Chronic kidney disease unspecified", - "long_description": "Chronic kidney disease unspecified", - "is_valid_billable": true, - "chapter": null, - "category": "N18", - "inclusion_terms": [ - "Chronic renal disease", - "Chronic renal failure NOS" - ], - "exclusion_terms": [ - "Acute kidney failure (N17.-)" - ], - "synonyms": [ - "CKD", - "chronic kidney disease", - "chronic renal disease", - "chronic kidney failure" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "N17.9", - "description": "Acute kidney injury unspecified", - "unformatted_code": "N179", - "short_description": "Acute kidney injury unspecified", - "long_description": "Acute kidney injury unspecified", - "is_valid_billable": true, - "chapter": null, - "category": "N17", - "inclusion_terms": [ - "Acute renal failure NOS", - "Acute kidney injury NOS" - ], - "exclusion_terms": [ - "Chronic kidney disease (N18.-)" - ], - "synonyms": [ - "AKI", - "acute kidney injury", - "acute renal failure", - "ARF", - "renal insufficiency acute" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I48.0", - "description": "Paroxysmal atrial fibrillation", - "unformatted_code": "I480", - "short_description": "Paroxysmal atrial fibrillation", - "long_description": "Paroxysmal atrial fibrillation", - "is_valid_billable": true, - "chapter": null, - "category": "I48", - "inclusion_terms": [ - "Paroxysmal AF" - ], - "exclusion_terms": [], - "synonyms": [ - "paroxysmal AFib", - "intermittent atrial fibrillation", - "paroxysmal AF" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I48.91", - "description": "Unspecified atrial fibrillation", - "unformatted_code": "I4891", - "short_description": "Unspecified atrial fibrillation", - "long_description": "Unspecified atrial fibrillation", - "is_valid_billable": true, - "chapter": null, - "category": "I48", - "inclusion_terms": [ - "Atrial fibrillation NOS", - "Auricular fibrillation" - ], - "exclusion_terms": [], - "synonyms": [ - "AFib", - "AF", - "atrial fibrillation", - "auricular fibrillation" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "J18.9", - "description": "Pneumonia unspecified organism", - "unformatted_code": "J189", - "short_description": "Pneumonia unspecified organism", - "long_description": "Pneumonia unspecified organism", - "is_valid_billable": true, - "chapter": null, - "category": "J18", - "inclusion_terms": [ - "Pneumonia NOS" - ], - "exclusion_terms": [ - "Aspiration pneumonia (J69.0)", - "Viral pneumonia (J12.-)" - ], - "synonyms": [ - "PNA", - "pneumonia", - "lung infection", - "community acquired pneumonia NOS", - "CAP" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "J44.1", - "description": "Chronic obstructive pulmonary disease with acute exacerbation", - "unformatted_code": "J441", - "short_description": "Chronic obstructive pulmonary disease with acute exacerbation", - "long_description": "Chronic obstructive pulmonary disease with acute exacerbation", - "is_valid_billable": true, - "chapter": null, - "category": "J44", - "inclusion_terms": [ - "Decompensated COPD", - "COPD with acute exacerbation" - ], - "exclusion_terms": [], - "synonyms": [ - "acute COPD exacerbation", - "AECOPD", - "acute exacerbation of chronic obstructive bronchitis" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "J44.9", - "description": "Chronic obstructive pulmonary disease unspecified", - "unformatted_code": "J449", - "short_description": "Chronic obstructive pulmonary disease unspecified", - "long_description": "Chronic obstructive pulmonary disease unspecified", - "is_valid_billable": true, - "chapter": null, - "category": "J44", - "inclusion_terms": [ - "Chronic obstructive pulmonary disease NOS", - "Chronic bronchitis NOS" - ], - "exclusion_terms": [ - "Asthma (J45.-)" - ], - "synonyms": [ - "COPD", - "chronic obstructive lung disease", - "COLD" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "A41.9", - "description": "Sepsis unspecified organism", - "unformatted_code": "A419", - "short_description": "Sepsis unspecified organism", - "long_description": "Sepsis unspecified organism", - "is_valid_billable": true, - "chapter": null, - "category": "A41", - "inclusion_terms": [ - "Septicemia NOS", - "Sepsis NOS" - ], - "exclusion_terms": [ - "Severe sepsis (R65.2-)", - "Septic shock (R65.21)" - ], - "synonyms": [ - "sepsis", - "blood poisoning", - "septicemia", - "systemic infection" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "K21.9", - "description": "Gastro-esophageal reflux disease without esophagitis", - "unformatted_code": "K219", - "short_description": "Gastro-esophageal reflux disease without esophagitis", - "long_description": "Gastro-esophageal reflux disease without esophagitis", - "is_valid_billable": true, - "chapter": null, - "category": "K21", - "inclusion_terms": [ - "Acid reflux", - "GERD NOS" - ], - "exclusion_terms": [], - "synonyms": [ - "GERD", - "gastroesophageal reflux", - "acid reflux", - "reflux esophagitis" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I21.9", - "description": "Acute myocardial infarction unspecified", - "unformatted_code": "I219", - "short_description": "Acute myocardial infarction unspecified", - "long_description": "Acute myocardial infarction unspecified", - "is_valid_billable": true, - "chapter": null, - "category": "I21", - "inclusion_terms": [ - "Heart attack NOS", - "Myocardial infarction NOS" - ], - "exclusion_terms": [ - "Subsequent myocardial infarction (I22.-)" - ], - "synonyms": [ - "MI", - "AMI", - "acute MI", - "acute myocardial infarction", - "heart attack" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - }, - { - "code": "I21.09", - "description": "ST elevation myocardial infarction involving anterior wall", - "unformatted_code": "I2109", - "short_description": "ST elevation myocardial infarction involving anterior wall", - "long_description": "ST elevation myocardial infarction involving anterior wall", - "is_valid_billable": true, - "chapter": null, - "category": "I21", - "inclusion_terms": [ - "Transmural anterior myocardial infarction" - ], - "exclusion_terms": [], - "synonyms": [ - "anterior STEMI", - "STEMI anterior wall", - "acute anterior MI" - ], - "source_metadata": { - "source": "sample_hospital_icd.csv", - "file_path": "data\\icd10\\sample_hospital_icd.csv" - }, - "excludes1": [], - "excludes2": [], - "code_first": [], - "use_additional": [] - } - ], - "stats": { - "total_records": 25, - "valid_billable_count": 24, - "non_billable_count": 1, - "unique_categories_count": 11, - "duplicates_dropped": 0, - "malformed_dropped": 0, - "total_inclusion_terms": 40, - "total_exclusion_terms": 21, - "total_synonyms": 91, - "format_type": "tabular" - } -} \ No newline at end of file diff --git a/data/indexes/index_stats.json b/data/indexes/index_stats.json deleted file mode 100644 index dd162f0..0000000 --- a/data/indexes/index_stats.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "total_records": 25, - "valid_billable_count": 24, - "non_billable_count": 1, - "unique_categories_count": 11, - "duplicates_dropped": 0, - "malformed_dropped": 0, - "total_inclusion_terms": 40, - "total_exclusion_terms": 21, - "total_synonyms": 91, - "format_type": "tabular" -} \ No newline at end of file diff --git a/install.bat b/install.bat new file mode 100644 index 0000000..efcfd76 --- /dev/null +++ b/install.bat @@ -0,0 +1,98 @@ +@echo off +setlocal enabledelayedexpansion + +echo =============================================================================== +echo Local ICD-10-CM / ICD-O / CPT Coding Engine - Installation Setup (Windows) +echo =============================================================================== +echo. + +:: 1. Check Python installation +where python >nul 2>nul +if %ERRORLEVEL% neq 0 ( + echo [ERROR] Python is not found on your PATH. + echo Please install Python 3.10+ (recommend 3.10-3.13) and ensure "Add Python to PATH" is checked. + exit /b 1 +) + +for /f "tokens=*" %%i in ('python --version 2^>^&1') do set PYTHON_VERSION=%%i +echo [*] Detected: %PYTHON_VERSION% + +:: 2. Create Virtual Environment +set "VENV_DIR=env" +if not exist "%VENV_DIR%\Scripts\python.exe" ( + echo [*] Creating virtual environment in .\%VENV_DIR% ... + python -m venv %VENV_DIR% + if %ERRORLEVEL% neq 0 ( + echo [ERROR] Failed to create virtual environment. + exit /b 1 + ) + echo [*] Virtual environment created successfully. +) else ( + echo [*] Virtual environment already exists at .\%VENV_DIR%. +) + +:: 3. Upgrade pip and core packaging tools +echo [*] Upgrading pip, setuptools, and wheel... +"%VENV_DIR%\Scripts\python.exe" -m pip install --upgrade pip setuptools wheel >nul 2>nul + +:: 4. Install Dependencies +echo [*] Installing required packages from requirements.txt... +echo (This may take a few minutes depending on network speed) +"%VENV_DIR%\Scripts\python.exe" -m pip install -r requirements.txt +if %ERRORLEVEL% neq 0 ( + echo [ERROR] Failed to install dependencies from requirements.txt. + exit /b 1 +) +echo [*] Dependencies installed successfully. + +:: 5. Set up Environment Variables (.env) +if not exist ".env" ( + if exist ".env.example" ( + echo [*] Initializing .env configuration from .env.example... + copy /y ".env.example" ".env" >nul + ) else ( + echo [*] Creating default .env configuration... + ( + echo APP_ENV=production + echo LOG_LEVEL=INFO + echo ICD_DATABASE_DIR=./Database + echo ICD_DATASET_PATH=./data/icd10/sample_hospital_icd.csv + echo FAISS_INDEX_DIR=./data/indexes + echo SQLITE_DB_PATH=./data/warehouse/encounters.db + echo EMBEDDING_DEVICE=cpu + ) > ".env" + ) + echo [*] Environment file .env created. +) else ( + echo [*] Existing .env file detected. Keeping existing configuration. +) + +:: 6. Ensure required directories exist +if not exist "data\indexes" mkdir data\indexes +if not exist "data\warehouse" mkdir data\warehouse +if not exist "data\uploads" mkdir data\uploads + +:: 7. Build/Verify Local Search Indexes +echo [*] Checking local medical coding database and search indices... +"%VENV_DIR%\Scripts\python.exe" scripts\index_icd.py --force-fast-embeddings +if %ERRORLEVEL% neq 0 ( + echo [WARNING] Index initialization completed with warnings. Application will load on demand. +) else ( + echo [*] Authoritative search indexes verified and ready. +) + +echo. +echo =============================================================================== +echo INSTALLATION COMPLETED SUCCESSFULLY! +echo =============================================================================== +echo. +echo The application and environment are fully configured. +echo To launch the web application, run: +echo run.bat +echo or: +echo run.ps1 +echo. +echo For FastAPI backend mode, run: +echo run.bat --api +echo. +exit /b 0 diff --git a/install.ps1 b/install.ps1 new file mode 100644 index 0000000..d56e34a --- /dev/null +++ b/install.ps1 @@ -0,0 +1,93 @@ +# PowerShell Installation Script for Windows +$ErrorActionPreference = "Stop" + +Write-Host "===============================================================================" -ForegroundColor Cyan +Write-Host " Local ICD-10-CM / ICD-O / CPT Coding Engine - Installation Setup (PowerShell)" -ForegroundColor Cyan +Write-Host "===============================================================================" -ForegroundColor Cyan +Write-Host "" + +# 1. Check Python +try { + $pythonVersion = python --version 2>&1 + Write-Host "[*] Detected: $pythonVersion" -ForegroundColor Green +} catch { + Write-Host "[ERROR] Python is not found on your PATH." -ForegroundColor Red + Write-Host "Please install Python 3.10+ (recommend 3.10-3.13) and ensure 'Add Python to PATH' is checked." -ForegroundColor Yellow + exit 1 +} + +# 2. Virtual Environment +$venvPath = Join-Path $PSScriptRoot "env" +$venvPython = Join-Path $venvPath "Scripts\python.exe" + +if (-not (Test-Path $venvPython)) { + Write-Host "[*] Creating virtual environment in .\env ..." -ForegroundColor Cyan + python -m venv $venvPath + Write-Host "[*] Virtual environment created successfully." -ForegroundColor Green +} else { + Write-Host "[*] Virtual environment already exists at .\env." -ForegroundColor Yellow +} + +# 3. Upgrade pip +Write-Host "[*] Upgrading pip, setuptools, and wheel..." -ForegroundColor Cyan +& $venvPython -m pip install --upgrade pip setuptools wheel --quiet + +# 4. Install Dependencies +Write-Host "[*] Installing required packages from requirements.txt..." -ForegroundColor Cyan +& $venvPython -m pip install -r (Join-Path $PSScriptRoot "requirements.txt") +Write-Host "[*] Dependencies installed successfully." -ForegroundColor Green + +# 5. Environment Config +$envFile = Join-Path $PSScriptRoot ".env" +$envExample = Join-Path $PSScriptRoot ".env.example" +if (-not (Test-Path $envFile)) { + if (Test-Path $envExample) { + Write-Host "[*] Initializing .env configuration from .env.example..." -ForegroundColor Cyan + Copy-Item -Path $envExample -Destination $envFile + } else { + Write-Host "[*] Creating default .env configuration..." -ForegroundColor Cyan + @" +APP_ENV=production +LOG_LEVEL=INFO +ICD_DATABASE_DIR=./Database +ICD_DATASET_PATH=./data/icd10/sample_hospital_icd.csv +FAISS_INDEX_DIR=./data/indexes +SQLITE_DB_PATH=./data/warehouse/encounters.db +EMBEDDING_DEVICE=cpu +"@ | Out-File -FilePath $envFile -Encoding utf8 + } + Write-Host "[*] Environment file .env created." -ForegroundColor Green +} else { + Write-Host "[*] Existing .env file detected." -ForegroundColor Yellow +} + +# 6. Ensure Directories +@("data/indexes", "data/warehouse", "data/uploads") | ForEach-Object { + $dir = Join-Path $PSScriptRoot $_ + if (-not (Test-Path $dir)) { + New-Item -ItemType Directory -Path $dir -Force | Out-Null + } +} + +# 7. Build/Verify Indexes +Write-Host "[*] Checking local medical coding database and search indices..." -ForegroundColor Cyan +$indexScript = Join-Path $PSScriptRoot "scripts\index_icd.py" +try { + & $venvPython $indexScript --force-fast-embeddings + Write-Host "[*] Authoritative search indexes verified and ready." -ForegroundColor Green +} catch { + Write-Host "[WARNING] Index initialization completed with warnings. Application will load on demand." -ForegroundColor Yellow +} + +Write-Host "" +Write-Host "===============================================================================" -ForegroundColor Cyan +Write-Host " INSTALLATION COMPLETED SUCCESSFULLY!" -ForegroundColor Green +Write-Host "===============================================================================" -ForegroundColor Cyan +Write-Host "To launch the web application, run:" -ForegroundColor White +Write-Host " .\run.ps1" -ForegroundColor Yellow +Write-Host "or:" -ForegroundColor White +Write-Host " .\run.bat" -ForegroundColor Yellow +Write-Host "" +Write-Host "For FastAPI backend mode, run:" -ForegroundColor White +Write-Host " .\run.ps1 -Api" -ForegroundColor Yellow +Write-Host "" diff --git a/install.sh b/install.sh new file mode 100644 index 0000000..dacd1a6 --- /dev/null +++ b/install.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# Linux / macOS Installation Script +set -e + +echo "===============================================================================" +echo " Local ICD-10-CM / ICD-O / CPT Coding Engine - Installation Setup (Linux)" +echo "===============================================================================" +echo "" + +# 1. Check Python +PYTHON_BIN="" +if command -v python3 &>/dev/null; then + PYTHON_BIN="python3" +elif command -v python &>/dev/null; then + PYTHON_BIN="python" +else + echo "[ERROR] Python 3 was not found on your PATH." + echo "Please install Python 3.10+ (e.g., sudo apt install python3 python3-venv python3-pip)" + exit 1 +fi + +PY_VER=$($PYTHON_BIN --version 2>&1) +echo "[*] Detected: $PY_VER" + +# 2. Virtual Environment +VENV_DIR="env" +if [ ! -f "$VENV_DIR/bin/python" ]; then + echo "[*] Creating virtual environment in ./$VENV_DIR ..." + $PYTHON_BIN -m venv "$VENV_DIR" + echo "[*] Virtual environment created successfully." +else + echo "[*] Virtual environment already exists at ./$VENV_DIR." +fi + +# 3. Upgrade pip +echo "[*] Upgrading pip, setuptools, and wheel..." +"$VENV_DIR/bin/python" -m pip install --upgrade pip setuptools wheel --quiet + +# 4. Install Dependencies +echo "[*] Installing required packages from requirements.txt..." +"$VENV_DIR/bin/python" -m pip install -r requirements.txt +echo "[*] Dependencies installed successfully." + +# 5. Environment Config +if [ ! -f ".env" ]; then + if [ -f ".env.example" ]; then + echo "[*] Initializing .env configuration from .env.example..." + cp .env.example .env + else + echo "[*] Creating default .env configuration..." + cat < .env +APP_ENV=production +LOG_LEVEL=INFO +ICD_DATABASE_DIR=./Database +ICD_DATASET_PATH=./data/icd10/sample_hospital_icd.csv +FAISS_INDEX_DIR=./data/indexes +SQLITE_DB_PATH=./data/warehouse/encounters.db +EMBEDDING_DEVICE=cpu +EOF + fi + echo "[*] Environment file .env created." +else + echo "[*] Existing .env file detected." +fi + +# 6. Ensure Directories +mkdir -p data/indexes data/warehouse data/uploads + +# 7. Build/Verify Indexes +echo "[*] Checking local medical coding database and search indices..." +"$VENV_DIR/bin/python" scripts/index_icd.py --force-fast-embeddings || { + echo "[WARNING] Index initialization completed with warnings. Application will load on demand." +} + +echo "" +echo "===============================================================================" +echo " INSTALLATION COMPLETED SUCCESSFULLY!" +echo "===============================================================================" +echo "To launch the web application, run:" +echo " ./run.sh" +echo "" +echo "For FastAPI backend mode, run:" +echo " ./run.sh --api" +echo "" diff --git a/requirements.txt b/requirements.txt index be3cbfc..e4f89a5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -39,6 +39,8 @@ rank-bm25 scikit-learn numpy pandas +openpyxl +xlrd # ============================================================ # PDF / DOCUMENT / OCR PROCESSING diff --git a/run.bat b/run.bat new file mode 100644 index 0000000..4615a9c --- /dev/null +++ b/run.bat @@ -0,0 +1,33 @@ +@echo off +setlocal + +set "VENV_DIR=env" + +if not exist "%VENV_DIR%\Scripts\activate.bat" ( + echo [ERROR] Virtual environment not found at .\%VENV_DIR%. + echo Please run the installer first: + echo install.bat + exit /b 1 +) + +call "%VENV_DIR%\Scripts\activate.bat" + +if not exist ".env" ( + if exist ".env.example" ( + copy /y ".env.example" ".env" >nul + ) +) + +set PYTHONPATH=%CD%\src;%PYTHONPATH% + +if "%1"=="--api" ( + echo =============================================================================== + echo Starting FastAPI Medical Coding Service on http://127.0.0.1:8000 + echo =============================================================================== + python -m uvicorn medical_coding.api.app:app --host 0.0.0.0 --port 8000 --reload +) else ( + echo =============================================================================== + echo Starting Streamlit Medical Coding Workspace on http://localhost:8501 + echo =============================================================================== + streamlit run app.py +) diff --git a/run.ps1 b/run.ps1 new file mode 100644 index 0000000..aebe90a --- /dev/null +++ b/run.ps1 @@ -0,0 +1,34 @@ +# PowerShell Run Script for Windows +param ( + [switch]$Api +) + +$ErrorActionPreference = "Stop" + +$venvPath = Join-Path $PSScriptRoot "env" +$venvPython = Join-Path $venvPath "Scripts\python.exe" +$venvActivate = Join-Path $venvPath "Scripts\Activate.ps1" + +if (-not (Test-Path $venvActivate)) { + Write-Host "[ERROR] Virtual environment not found at .\env." -ForegroundColor Red + Write-Host "Please run the installer first:" -ForegroundColor Yellow + Write-Host " .\install.ps1" -ForegroundColor Yellow + exit 1 +} + +# Activate environment in current PowerShell session +& $venvActivate + +$env:PYTHONPATH = (Join-Path $PSScriptRoot "src") + +if ($Api) { + Write-Host "===============================================================================" -ForegroundColor Cyan + Write-Host " Starting FastAPI Medical Coding Service on http://127.0.0.1:8000" -ForegroundColor Green + Write-Host "===============================================================================" -ForegroundColor Cyan + & $venvPython -m uvicorn medical_coding.api.app:app --host 0.0.0.0 --port 8000 --reload +} else { + Write-Host "===============================================================================" -ForegroundColor Cyan + Write-Host " Starting Streamlit Medical Coding Workspace on http://localhost:8501" -ForegroundColor Green + Write-Host "===============================================================================" -ForegroundColor Cyan + & (Join-Path $venvPath "Scripts\streamlit.exe") run (Join-Path $PSScriptRoot "app.py") +} diff --git a/run.sh b/run.sh new file mode 100644 index 0000000..ec38050 --- /dev/null +++ b/run.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Linux / macOS Run Script +set -e + +VENV_DIR="env" + +if [ ! -f "$VENV_DIR/bin/activate" ]; then + echo "[ERROR] Virtual environment not found at ./$VENV_DIR." + echo "Please run the installer first:" + echo " ./install.sh" + exit 1 +fi + +source "$VENV_DIR/bin/activate" + +if [ ! -f ".env" ]; then + if [ -f ".env.example" ]; then + cp .env.example .env + fi +fi + +export PYTHONPATH="$(pwd)/src:$PYTHONPATH" + +if [ "$1" = "--api" ]; then + echo "===============================================================================" + echo " Starting FastAPI Medical Coding Service on http://127.0.0.1:8000" + echo "===============================================================================" + python -m uvicorn medical_coding.api.app:app --host 0.0.0.0 --port 8000 --reload +else + echo "===============================================================================" + echo " Starting Streamlit Medical Coding Workspace on http://localhost:8501" + echo "===============================================================================" + streamlit run app.py +fi diff --git a/scripts/index_icd.py b/scripts/index_icd.py index 0ad6ef6..a1f08ea 100644 --- a/scripts/index_icd.py +++ b/scripts/index_icd.py @@ -175,14 +175,26 @@ def demonstrate_sample_retrieval(hybrid_retriever: HybridICDRetriever) -> None: def main() -> None: + settings = get_settings() + db_wb = settings.get_database_workbook_path() + default_data_path = ( + str(db_wb) + if (db_wb and db_wb.exists()) + else ( + str(settings.icd_dataset_path) + if settings.icd_dataset_path.exists() + else "./data/icd10/sample_hospital_icd.csv" + ) + ) + parser = argparse.ArgumentParser( - description="Index hospital-supplied local ICD-10-CM dataset into BM25 and FAISS." + description="Index hospital-supplied local ICD-10-CM / ICD-O / CPT database into BM25 and FAISS." ) parser.add_argument( "--data-path", type=str, - default="./data/icd10/sample_hospital_icd.csv", - help="Path to hospital ICD-10 source file (CSV, TSV, JSON, or CMS TXT).", + default=default_data_path, + help="Path to hospital ICD/CPT source file (Excel, CSV, TSV, JSON, or CMS TXT).", ) parser.add_argument( "--output-dir", diff --git a/src/medical_coding/agents/ranker.py b/src/medical_coding/agents/ranker.py index 2a7b1fc..0025d19 100644 --- a/src/medical_coding/agents/ranker.py +++ b/src/medical_coding/agents/ranker.py @@ -354,11 +354,29 @@ class CandidateRankingAgent(BaseAgent): decision = parsed.get("decision", "ACCEPTED" if code_str else "ABSTAINED") abstention_reason = parsed.get("abstention_reason") + matching_cand = next((c for c in candidates if c.code == code_str), None) + cand_system = getattr(matching_cand, "coding_system", None) if matching_cand else "ICD-10-CM" + icd10cm_val = code_str if cand_system == "ICD-10-CM" else None + icdo_val = code_str if cand_system == "ICD-O" else None + cpt_val = code_str if cand_system == "CPT" else None + + for c in candidates: + c_sys = getattr(c, "coding_system", None) + if c_sys == "ICD-10-CM" and not icd10cm_val: + icd10cm_val = c.code + elif c_sys == "ICD-O" and not icdo_val: + icdo_val = c.code + elif c_sys == "CPT" and not cpt_val: + cpt_val = c.code + return RankedSelection( diagnosis_id=diag_id, raw_term=raw_term, selected_code=code_str, selected_description=desc_str, + selected_icd10cm=icd10cm_val, + selected_icdo=icdo_val, + selected_cpt=cpt_val, ranking_reason=reason, supporting_evidence=[evidence_quote], confidence=confidence, @@ -490,11 +508,28 @@ class CandidateRankingAgent(BaseAgent): decision="REJECTED_LOW_CONFIDENCE", ) + cand_system = getattr(top_cand, "coding_system", None) or "ICD-10-CM" + icd10cm_val = top_cand.code if cand_system == "ICD-10-CM" else None + icdo_val = top_cand.code if cand_system == "ICD-O" else None + cpt_val = top_cand.code if cand_system == "CPT" else None + + for c in candidates: + c_sys = getattr(c, "coding_system", None) + if c_sys == "ICD-10-CM" and not icd10cm_val: + icd10cm_val = c.code + elif c_sys == "ICD-O" and not icdo_val: + icdo_val = c.code + elif c_sys == "CPT" and not cpt_val: + cpt_val = c.code + return RankedSelection( diagnosis_id=diag_id, raw_term=raw_term, selected_code=top_cand.code, selected_description=top_cand.description, + selected_icd10cm=icd10cm_val, + selected_icdo=icdo_val, + selected_cpt=cpt_val, selected_candidate=top_cand, ranking_reason=f"Candidate '{top_cand.code}' ({top_cand.description}) best supported by documentation ({top_rationale}).", supporting_evidence=[evidence_quote], diff --git a/src/medical_coding/config/settings.py b/src/medical_coding/config/settings.py index 1c52a14..7e8bea0 100644 --- a/src/medical_coding/config/settings.py +++ b/src/medical_coding/config/settings.py @@ -136,6 +136,10 @@ class Settings(BaseSettings): default=Path("./data/icd10/icd10cm_order_2026.txt"), description="Path to authoritative CMS/CDC ICD-10-CM order/tabular flat file.", ) + database_dir: Path = Field( + default=Path("./Database"), + description="Directory containing local clinical database workbooks (Database_2.xlsx, Database_1.xls).", + ) icd_index_dir: Path = Field( default=Path("./data/indexes"), description="Directory for persisted FAISS indices and BM25 tokenized caches.", @@ -237,6 +241,17 @@ class Settings(BaseSettings): return path_obj return path_obj / self.model_name + def get_database_workbook_path(self) -> Path | None: + """Resolve the active multi-workbook database file if present.""" + if self.database_dir.is_dir(): + target = self.database_dir / "Database_2.xlsx" + if target.exists(): + return target + candidates = sorted(list(self.database_dir.glob("*.xlsx")) + list(self.database_dir.glob("*.xls"))) + if candidates: + return candidates[0] + return None + @lru_cache(maxsize=1) def get_settings() -> Settings: diff --git a/src/medical_coding/dataset/loader.py b/src/medical_coding/dataset/loader.py index 22373a6..efe458d 100644 --- a/src/medical_coding/dataset/loader.py +++ b/src/medical_coding/dataset/loader.py @@ -446,14 +446,161 @@ class CMSOrderFileLoader(BaseICDDatasetLoader): return self._records, self._stats +class ExcelWorkbookLoader(BaseICDDatasetLoader): + """Parses multi-sheet medical code workbooks containing ICD-10-CM, ICD-O, and CPT datasets. + + Supports reading .xlsx and .xls workbooks (such as Database_2.xlsx and Database_1.xls), + segregating codes into their respective coding systems ('ICD-10-CM', 'ICD-O', 'CPT'), + normalizing whitespace, and populating authoritative ICDCodeRecord models. + """ + + def __init__(self, file_or_dir_path: Path | str, **kwargs: Any) -> None: + p = Path(file_or_dir_path) + if p.is_dir(): + target = p / "Database_2.xlsx" + if not target.exists(): + candidates = sorted(list(p.glob("*.xlsx")) + list(p.glob("*.xls"))) + if candidates: + target = candidates[0] + else: + raise FileNotFoundError(f"No Excel workbooks found in {p}") + self.file_path = target + else: + self.file_path = p + + self._records: dict[str, ICDCodeRecord] = {} + self._stats: ICDDatasetStats | None = None + self._is_loaded: bool = False + + def get_total_records(self) -> int: + return len(self._records) + + def get_stats(self) -> ICDDatasetStats | None: + return self._stats + + def load(self) -> tuple[dict[str, ICDCodeRecord], ICDDatasetStats]: + if self._is_loaded: + return self._records, self._stats or ICDDatasetStats( + total_records=len(self._records), + valid_billable_count=len(self._records), + non_billable_count=0, + unique_categories_count=0, + format_type="excel_workbook", + ) + + import re + + import pandas as pd + + logger.info("Opening Excel workbook for multi-system clinical ingestion: %s", self.file_path) + xl = pd.ExcelFile(self.file_path) + + records: dict[str, ICDCodeRecord] = {} + duplicates_count = 0 + malformed_count = 0 + categories: set[str] = set() + + for sheet_name in xl.sheet_names: + logger.info("Parsing sheet [%s] from %s", sheet_name, self.file_path.name) + df = xl.parse(sheet_name) + if df.empty or "code" not in df.columns or "description" not in df.columns: + logger.warning("Skipping sheet [%s]: missing code or description column", sheet_name) + continue + + is_cpt_sheet = "cpt" in sheet_name.lower() + + for _, row in df.iterrows(): + if "active_yesno" in row and pd.notna(row["active_yesno"]): + try: + if int(row["active_yesno"]) == 0: + continue + except (ValueError, TypeError): + pass + + raw_code = str(row["code"]).strip() if pd.notna(row["code"]) else "" + raw_desc = str(row["description"]).strip() if pd.notna(row["description"]) else "" + + if not raw_code or not raw_desc or raw_code.lower() == "nan" or raw_desc.lower() == "nan": + malformed_count += 1 + continue + + if is_cpt_sheet or (raw_code.isdigit() and len(raw_code) in (4, 5)): + coding_system = "CPT" + cat_id = row.get("ichi_code_cat1_id", "") + cat = f"CPT-{cat_id}" if pd.notna(cat_id) else "CPT" + elif re.match(r"^M[89][0-9]{3}", raw_code, re.IGNORECASE): + coding_system = "ICD-O" + cat = "ICD-O-Morphology" + else: + coding_system = "ICD-10-CM" + cat3 = row.get("icd10_code_cat3", "") + cat = str(cat3).strip() if pd.notna(cat3) else raw_code[:3] + + formatted_code = format_icd_code(raw_code) + lookup_key = formatted_code + + if lookup_key in records: + duplicates_count += 1 + continue + + categories.add(cat) + rec = ICDCodeRecord( + code=formatted_code, + unformatted_code=unformat_icd_code(raw_code), + description=raw_desc, + short_description=raw_desc, + long_description=raw_desc, + is_valid_billable=True, + category=cat, + coding_system=coding_system, + source_metadata={ + "source": "ExcelWorkbook", + "sheet": sheet_name, + "file": str(self.file_path.name), + "row_id": str(row.get("id", "")), + }, + ) + records[lookup_key] = rec + + billable_count = sum(1 for r in records.values() if r.is_valid_billable) + stats = ICDDatasetStats( + total_records=len(records), + valid_billable_count=billable_count, + non_billable_count=len(records) - billable_count, + unique_categories_count=len(categories), + duplicates_dropped=duplicates_count, + malformed_dropped=malformed_count, + format_type="excel_workbook", + ) + + self._records = records + self._stats = stats + self._is_loaded = True + + logger.info( + "Excel workbook successfully ingested: %d codes (%d categories, %d duplicates filtered)", + stats.total_records, + stats.unique_categories_count, + stats.duplicates_dropped, + ) + + return self._records, self._stats + + def load_icd_dataset( file_path: Path | str, **kwargs: Any ) -> tuple[dict[str, ICDCodeRecord], ICDDatasetStats]: """Factory function detecting format from file extension and returning loaded records and stats.""" path = Path(file_path) + if path.is_dir() and (list(path.glob("*.xlsx")) or list(path.glob("*.xls"))): + loader: BaseICDDatasetLoader = ExcelWorkbookLoader(path, **kwargs) + return loader.load() + suffix = path.suffix.lower() - if suffix in {".csv", ".tsv", ".json"}: - loader: BaseICDDatasetLoader = TabularICDLoader(path, **kwargs) + if suffix in {".xlsx", ".xls"}: + loader = ExcelWorkbookLoader(path, **kwargs) + elif suffix in {".csv", ".tsv", ".json"}: + loader = TabularICDLoader(path, **kwargs) elif suffix in {".txt"}: loader = CMSOrderFileLoader(path) else: diff --git a/src/medical_coding/dataset/validator.py b/src/medical_coding/dataset/validator.py index 4e0846d..3d2fa88 100644 --- a/src/medical_coding/dataset/validator.py +++ b/src/medical_coding/dataset/validator.py @@ -22,6 +22,11 @@ class LocalICDCatalog: self.loader = loader self._records_by_clean: dict[str, ICDCodeRecord] = {} self._records_by_formatted: dict[str, ICDCodeRecord] = {} + self._records_by_system: dict[str, dict[str, ICDCodeRecord]] = { + "ICD-10-CM": {}, + "ICD-O": {}, + "CPT": {}, + } self._stats: ICDDatasetStats | None = None self._initialized: bool = False @@ -38,6 +43,12 @@ class LocalICDCatalog: self._records_by_clean[record.unformatted_code] = record self._records_by_formatted[record.code] = record + sys_key = getattr(record, "coding_system", "ICD-10-CM") or "ICD-10-CM" + if sys_key not in self._records_by_system: + self._records_by_system[sys_key] = {} + self._records_by_system[sys_key][record.code] = record + self._records_by_system[sys_key][record.unformatted_code] = record + def initialize(self) -> None: """Load records from the dataset loader into fast lookup indexes.""" if self._initialized: @@ -49,15 +60,26 @@ class LocalICDCatalog: self.add_record(rec) self._stats = stats logger.info( - "LocalICDCatalog initialized with %d codes.", len(self._records_by_formatted) + "LocalICDCatalog initialized with %d codes across systems: %s", + len(self._records_by_formatted), + {k: len(v) // 2 for k, v in self._records_by_system.items() if v}, ) self._initialized = True - def get_by_code(self, code: str) -> ICDCodeRecord | None: + def get_by_code(self, code: str, system: str | None = None) -> ICDCodeRecord | None: """Lookup a code in the local catalog by formatted or unformatted representation.""" if not code: return None + + if system and system in self._records_by_system: + sys_dict = self._records_by_system[system] + clean = unformat_icd_code(code) + if clean in sys_dict: + return sys_dict[clean] + formatted = format_icd_code(code) + return sys_dict.get(formatted) + clean = unformat_icd_code(code) if clean in self._records_by_clean: return self._records_by_clean[clean] @@ -65,15 +87,28 @@ class LocalICDCatalog: formatted = format_icd_code(code) return self._records_by_formatted.get(formatted) - def is_valid_code(self, code: str) -> bool: + def is_valid_code(self, code: str, system: str | None = None) -> bool: """Check if code exists in the local authoritative dataset.""" - return self.get_by_code(code) is not None + return self.get_by_code(code, system=system) is not None - def is_billable_code(self, code: str) -> bool: + def is_billable_code(self, code: str, system: str | None = None) -> bool: """Check if code exists and is terminal/billable at full specificity.""" - record = self.get_by_code(code) + record = self.get_by_code(code, system=system) return record.is_valid_billable if record else False + def get_codes_by_system(self, system: str) -> list[ICDCodeRecord]: + """Return all distinct code records for a specific coding system.""" + if system in self._records_by_system: + seen: dict[str, ICDCodeRecord] = {} + for rec in self._records_by_system[system].values(): + seen[rec.code] = rec + return list(seen.values()) + return [] + + def get_available_systems(self) -> list[str]: + """Return list of distinct coding systems populated in the catalog.""" + return [k for k, v in self._records_by_system.items() if v] + def get_all_records(self) -> list[ICDCodeRecord]: """Return all distinct ICDCodeRecord entries in the catalog.""" return list(self._records_by_formatted.values()) diff --git a/src/medical_coding/graph/nodes.py b/src/medical_coding/graph/nodes.py index 9f78ea1..800cfe4 100644 --- a/src/medical_coding/graph/nodes.py +++ b/src/medical_coding/graph/nodes.py @@ -80,10 +80,16 @@ def get_or_initialize_retrieval_system() -> tuple[LocalICDCatalog, HybridICDRetr embeddings = FastLocalEmbeddings(dim=384) faiss_ret = FAISSICDRetriever(embeddings=embeddings) + db_wb = settings.get_database_workbook_path() + if catalog_path.exists(): try: catalog = LocalICDCatalog.load_from_json(catalog_path) - if (index_dir / "bm25_index.pkl").exists() and (index_dir / "faiss.index").exists(): + # If authoritative Database exists and cached catalog has fewer than 1000 codes (old sample), reload + if db_wb and db_wb.exists() and len(catalog) < 1000: + logger.info("Found authoritative Database workbook at %s; reloading catalog.", db_wb) + catalog = LocalICDCatalog() + elif (index_dir / "bm25_index.pkl").exists() and (index_dir / "faiss.index").exists(): bm25.load(index_dir) faiss_ret.load(index_dir) logger.info("Loaded persisted ICD catalog and indices from %s", index_dir) @@ -97,7 +103,9 @@ def get_or_initialize_retrieval_system() -> tuple[LocalICDCatalog, HybridICDRetr if len(catalog) == 0: data_source = ( - settings.icd_dataset_path if settings.icd_dataset_path.exists() else sample_csv + db_wb + if (db_wb and db_wb.exists()) + else (settings.icd_dataset_path if settings.icd_dataset_path.exists() else sample_csv) ) if data_source.exists(): records_dict, stats = load_icd_dataset(data_source) @@ -542,6 +550,46 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]: def _retrieve_for_condition(cond: ClassifiedDiagnosis) -> tuple[str, list[ICDCandidate]]: query = cond.raw_term hits = retriever.retrieve(query, top_k=10) + + term_lower = query.lower() + evidence_lower = ( + cond.context.evidence.quote.lower() + if hasattr(cond, "context") and hasattr(cond.context, "evidence") and cond.context.evidence + else "" + ) + combined_text = f"{term_lower} {evidence_lower}" + + is_neoplasm = any( + w in combined_text + for w in [ + "cancer", "carcinoma", "sarcoma", "melanoma", "tumor", "tumour", + "neoplasm", "lymphoma", "leukemia", "malignant", "infiltrating duct" + ] + ) + is_procedure = any( + w in combined_text + for w in [ + "biopsy", "excision", "resection", "catheterization", "infusion", + "endoscopy", "surgery", "repair", "graft", "consultation", "evaluation", + "treatment", "injection", "procedure" + ] + ) + + existing_codes = {h.code for h in hits} + if is_neoplasm: + icdo_hits = retriever.retrieve(query, top_k=5, system="ICD-O") + for o_hit in icdo_hits: + if o_hit.code not in existing_codes: + hits.append(o_hit) + existing_codes.add(o_hit.code) + + if is_procedure: + cpt_hits = retriever.retrieve(query, top_k=5, system="CPT") + for c_hit in cpt_hits: + if c_hit.code not in existing_codes: + hits.append(c_hit) + existing_codes.add(c_hit.code) + return cond.diagnosis_id, hits # Parallelize retrieval across diagnoses within document @@ -740,6 +788,12 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: secondary_responses: list[CodedDiagnosisResponse] = [] for item in validated: + is_icdo = bool(item.icdo or item.code.startswith("M")) + is_cpt = bool(item.cpt or (item.code.isdigit() and len(item.code) in (4, 5))) + icd10_val = item.icd10cm if item.icd10cm else (item.code if not is_icdo and not is_cpt else None) + icdo_val = item.icdo if item.icdo else (item.code if is_icdo else None) + cpt_val = item.cpt if item.cpt else (item.code if is_cpt else None) + resp = CodedDiagnosisResponse( code=item.code, description=item.description, @@ -753,6 +807,9 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: evidence_quote=item.evidence.quote, confidence_score=item.confidence_score, is_terminal_billable=True, + icd10cm=icd10_val, + icdo=icdo_val, + cpt=cpt_val, ) if item.role == DiagnosisRole.PRIMARY: primary_response = resp diff --git a/src/medical_coding/retrieval/hybrid.py b/src/medical_coding/retrieval/hybrid.py index c9ea2d8..25e9ce6 100644 --- a/src/medical_coding/retrieval/hybrid.py +++ b/src/medical_coding/retrieval/hybrid.py @@ -56,6 +56,7 @@ class HybridICDRetriever(BaseICDRetriever): query: str, top_k: int | None = None, min_score: float | None = None, + system: str | None = None, ) -> list[ICDCandidate]: """Execute hybrid search, merge candidates, score, deduplicate, and rank. @@ -63,6 +64,7 @@ class HybridICDRetriever(BaseICDRetriever): query: Normalized clinical diagnosis or condition description. top_k: Maximum candidate pool size to return (defaults to configured top_k). min_score: Minimum threshold override; candidates below this are pruned. + system: Optional filter to restrict candidates to a specific coding system ('ICD-10-CM', 'ICD-O', 'CPT'). Returns: Ranked list of ICDCandidate objects sourced exclusively from the local catalog. @@ -87,6 +89,11 @@ class HybridICDRetriever(BaseICDRetriever): # Enforce local catalog existence if catalog is attached if self.catalog and not self.catalog.is_valid_code(hit.code): continue + cat_rec = self.catalog.get_by_code(hit.code) if self.catalog else None + hit_system = getattr(hit, "coding_system", None) or (cat_rec.coding_system if cat_rec else "ICD-10-CM") + if system and hit_system != system: + continue + merged[hit.code] = { "code": hit.code, "description": hit.description, @@ -94,11 +101,17 @@ class HybridICDRetriever(BaseICDRetriever): "category": hit.category, "lexical_score": hit.retrieval_score, "semantic_score": 0.0, + "coding_system": hit_system, } for hit in vector_hits: if self.catalog and not self.catalog.is_valid_code(hit.code): continue + cat_rec = self.catalog.get_by_code(hit.code) if self.catalog else None + hit_system = getattr(hit, "coding_system", None) or (cat_rec.coding_system if cat_rec else "ICD-10-CM") + if system and hit_system != system: + continue + if hit.code in merged: merged[hit.code]["semantic_score"] = hit.retrieval_score # Keep most descriptive text @@ -112,6 +125,7 @@ class HybridICDRetriever(BaseICDRetriever): "category": hit.category, "lexical_score": 0.0, "semantic_score": hit.retrieval_score, + "coding_system": hit_system, } if not merged: @@ -151,6 +165,7 @@ class HybridICDRetriever(BaseICDRetriever): semantic_score=round(sem, 4), lexical_score=round(lex, 4), category=info["category"], + coding_system=info.get("coding_system", "ICD-10-CM"), ) ) @@ -162,10 +177,25 @@ class HybridICDRetriever(BaseICDRetriever): if not top_candidates: logger.info( "Hybrid retrieval: %d candidates found but none met min_score threshold %.2f for query '%s' (abstaining).", - len(merged), + len(candidate_pool), threshold, clean_query, ) - return [] - return top_candidates + + def retrieve_multi_system( + self, + query: str, + top_k: int = 5, + min_score: float | None = None, + ) -> dict[str, list[ICDCandidate]]: + """Retrieve candidates partitioned by coding system (ICD-10-CM, ICD-O, CPT). + + Returns: + Dictionary with keys 'ICD-10-CM', 'ICD-O', and 'CPT' containing top matching candidates. + """ + return { + "ICD-10-CM": self.retrieve(query, top_k=top_k, min_score=min_score, system="ICD-10-CM"), + "ICD-O": self.retrieve(query, top_k=top_k, min_score=min_score, system="ICD-O"), + "CPT": self.retrieve(query, top_k=top_k, min_score=min_score, system="CPT"), + } diff --git a/src/medical_coding/retrieval/lexical.py b/src/medical_coding/retrieval/lexical.py index 6cabceb..78cfdfb 100644 --- a/src/medical_coding/retrieval/lexical.py +++ b/src/medical_coding/retrieval/lexical.py @@ -104,6 +104,7 @@ class BM25ICDRetriever(BaseICDRetriever): is_valid_billable=record.is_valid_billable, lexical_score=clamped_score, category=record.category, + coding_system=record.coding_system, ) ) diff --git a/src/medical_coding/retrieval/vector.py b/src/medical_coding/retrieval/vector.py index 131e7ac..1f0bc3a 100644 --- a/src/medical_coding/retrieval/vector.py +++ b/src/medical_coding/retrieval/vector.py @@ -102,6 +102,7 @@ class FAISSICDRetriever(BaseICDRetriever): is_valid_billable=record.is_valid_billable, semantic_score=norm_sim, category=record.category, + coding_system=record.coding_system, ) ) diff --git a/src/medical_coding/schemas/icd.py b/src/medical_coding/schemas/icd.py index b7110c2..170ee9f 100644 --- a/src/medical_coding/schemas/icd.py +++ b/src/medical_coding/schemas/icd.py @@ -8,12 +8,16 @@ from medical_coding.utils.text import format_icd_code, unformat_icd_code class ICDCodeRecord(BaseModel): - """Authoritative representation of a single code in the local ICD-10-CM dataset.""" + """Authoritative representation of a single code in the local clinical dataset.""" code: str = Field( - min_length=3, - max_length=8, - description="Formatted ICD-10-CM code (e.g. 'I50.21', 'E11.9').", + min_length=2, + max_length=12, + description="Formatted clinical code (e.g. 'I50.21', 'M8000.0', '1404').", + ) + coding_system: str = Field( + default="ICD-10-CM", + description="Coding system of this record ('ICD-10-CM', 'ICD-O', 'CPT').", ) description: str = Field( default="", @@ -155,8 +159,12 @@ class ICDDatasetStats(BaseModel): class ICDCandidate(BaseModel): """An authoritative candidate code retrieved from the local dataset for an extracted diagnosis.""" - code: str = Field(description="Authoritative ICD-10-CM code from local catalog.") - description: str = Field(description="Official ICD description matching the code.") + code: str = Field(description="Authoritative code from local catalog.") + description: str = Field(description="Official clinical description matching the code.") + coding_system: str = Field( + default="ICD-10-CM", + description="Coding system of this candidate ('ICD-10-CM', 'ICD-O', 'CPT').", + ) retrieval_score: float = Field( ge=0.0, le=1.0, @@ -182,7 +190,7 @@ class ICDCandidate(BaseModel): ) category: str | None = Field( default=None, - description="ICD category (3-character prefix).", + description="Category prefix or group identifier.", ) @@ -193,11 +201,23 @@ class RankedSelection(BaseModel): raw_term: str = Field(default="", description="Original clinical term.") selected_code: str | None = Field( default=None, - description="The chosen ICD-10-CM code strictly from the candidate list; None if abstained.", + description="The chosen code strictly from the candidate list; None if abstained.", ) selected_description: str | None = Field( default=None, - description="Official description of the selected ICD code.", + description="Official description of the selected clinical code.", + ) + selected_icd10cm: str | None = Field( + default=None, + description="Matched ICD-10-CM code if matched, else None.", + ) + selected_icdo: str | None = Field( + default=None, + description="Matched ICD-O morphology code if matched, else None.", + ) + selected_cpt: str | None = Field( + default=None, + description="Matched CPT code if matched, else None.", ) ranking_reason: str = Field( default="", diff --git a/src/medical_coding/schemas/response.py b/src/medical_coding/schemas/response.py index 693a907..017ca16 100644 --- a/src/medical_coding/schemas/response.py +++ b/src/medical_coding/schemas/response.py @@ -33,6 +33,18 @@ class CodedDiagnosisResponse(BaseModel): default=True, description="Confirms code is at terminal specificity required for submission.", ) + icd10cm: str | None = Field( + default=None, + description="Matched ICD-10-CM code if matched, None if not.", + ) + icdo: str | None = Field( + default=None, + description="Matched ICD-O oncology/morphology code if matched, None if not.", + ) + cpt: str | None = Field( + default=None, + description="Matched CPT procedural code if matched, None if not.", + ) class CodingResult(BaseModel): diff --git a/src/medical_coding/schemas/validation.py b/src/medical_coding/schemas/validation.py index e8a5cae..7166ce9 100644 --- a/src/medical_coding/schemas/validation.py +++ b/src/medical_coding/schemas/validation.py @@ -34,6 +34,18 @@ class ValidatedDiagnosis(BaseModel): default_factory=list, description="Complete record of deterministic validation checks executed.", ) + icd10cm: str | None = Field( + default=None, + description="Matched ICD-10-CM code if matched, else None.", + ) + icdo: str | None = Field( + default=None, + description="Matched ICD-O oncology morphology code if matched, else None.", + ) + cpt: str | None = Field( + default=None, + description="Matched CPT procedural code if matched, else None.", + ) class AbstentionRecord(BaseModel): diff --git a/src/medical_coding/ui/app.py b/src/medical_coding/ui/app.py index 6f0b923..5269109 100644 --- a/src/medical_coding/ui/app.py +++ b/src/medical_coding/ui/app.py @@ -515,6 +515,10 @@ with tab1: # Deterministic Rule Audit Trail render_validation_audit_trail(coding_result.primary_diagnosis, coding_result.secondary_diagnoses) + # Interactive JSON Viewer Expander + with st.expander("🔍 View Structured JSON Response Payload", expanded=False): + st.json(coding_result.model_dump()) + # Download Buttons st.markdown("---") d_col1, d_col2 = st.columns(2) @@ -533,7 +537,10 @@ with tab1: export_rows.append({ "Encounter": document_id, "Role": "PRIMARY", - "ICD_Code": coding_result.primary_diagnosis.code, + "Code": coding_result.primary_diagnosis.code, + "ICD10CM": coding_result.primary_diagnosis.icd10cm, + "ICD_O": coding_result.primary_diagnosis.icdo, + "CPT": coding_result.primary_diagnosis.cpt, "Description": coding_result.primary_diagnosis.description, "Confidence": coding_result.primary_diagnosis.confidence_score, "Billable": coding_result.primary_diagnosis.is_terminal_billable, @@ -543,7 +550,10 @@ with tab1: export_rows.append({ "Encounter": document_id, "Role": "SECONDARY", - "ICD_Code": s.code, + "Code": s.code, + "ICD10CM": s.icd10cm, + "ICD_O": s.icdo, + "CPT": s.cpt, "Description": s.description, "Confidence": s.confidence_score, "Billable": s.is_terminal_billable, diff --git a/src/medical_coding/ui/components.py b/src/medical_coding/ui/components.py index 3f456e7..4782b16 100644 --- a/src/medical_coding/ui/components.py +++ b/src/medical_coding/ui/components.py @@ -141,6 +141,15 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None: conf_pct = int(primary.confidence_score * 100) + codes_pills = [] + if primary.icd10cm: + codes_pills.append(f'ICD-10-CM: {primary.icd10cm}') + if primary.icdo: + codes_pills.append(f'ICD-O: {primary.icdo}') + if primary.cpt: + codes_pills.append(f'CPT: {primary.cpt}') + codes_html = " ".join(codes_pills) + st.markdown( f"""
@@ -155,10 +164,11 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
{primary.description}
-
+
{acuity_badge} {certainty_badge} Chief Reason for Encounter + {codes_html}
@@ -188,19 +198,29 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non acuity_str = diag.acuity.value if hasattr(diag.acuity, "value") else str(diag.acuity) certainty_str = diag.certainty.value if hasattr(diag.certainty, "value") else str(diag.certainty) + sec_codes_pills = [] + if diag.icd10cm: + sec_codes_pills.append(f'ICD-10-CM: {diag.icd10cm}') + if diag.icdo: + sec_codes_pills.append(f'ICD-O: {diag.icdo}') + if diag.cpt: + sec_codes_pills.append(f'CPT: {diag.cpt}') + sec_codes_html = " ".join(sec_codes_pills) + with st.container(): st.markdown( f"""
-
+
#{idx}. {diag.code} {diag.description}
-
+
{billable_badge} {acuity_str} {certainty_str} + {sec_codes_html}
diff --git a/src/medical_coding/utils/text.py b/src/medical_coding/utils/text.py index 2503c25..704fbc2 100644 --- a/src/medical_coding/utils/text.py +++ b/src/medical_coding/utils/text.py @@ -31,12 +31,26 @@ def find_verbatim_span(full_text: str, quote: str) -> tuple[int, int] | None: def format_icd_code(raw_code: str) -> str: - """Format alphanumeric ICD code with standard decimal (e.g. 'I5021' -> 'I50.21'). + """Format alphanumeric clinical code (ICD-10-CM, ICD-O, or CPT) cleanly. - Standard ICD-10-CM codes place a decimal point after the first 3 characters. + - Standard ICD-10-CM codes (e.g. 'I5021' -> 'I50.21') place a decimal point after character 3. + - CPT codes (e.g. '1404', '99213') remain pure numeric without artificial decimal points. + - ICD-O morphology codes (e.g. 'M8000.0') preserve their oncology morphology structure. + - Already formatted codes (e.g. 'I50.21', 'M8000.0') are preserved. """ - clean = re.sub(r"[^A-Za-z0-9]", "", raw_code).upper() - if len(clean) > 3 and "." not in clean: + if not raw_code: + return "" + raw = str(raw_code).strip() + if raw.isdigit(): + return raw + if re.match(r"^[0-9]{4}[A-Za-z]$", raw): + return raw.upper() + if re.match(r"^M[89][0-9]{3}[\./][0-9]$", raw, re.IGNORECASE): + return raw.upper() + if "." in raw: + return raw.upper() + clean = re.sub(r"[^A-Za-z0-9]", "", raw).upper() + if len(clean) > 3 and clean[0].isalpha() and clean[1].isdigit(): return f"{clean[:3]}.{clean[3:]}" return clean diff --git a/src/medical_coding/validation/deterministic.py b/src/medical_coding/validation/deterministic.py index c66c989..6f7751b 100644 --- a/src/medical_coding/validation/deterministic.py +++ b/src/medical_coding/validation/deterministic.py @@ -103,6 +103,11 @@ class DeterministicValidator: stage=PipelineStage.VALIDATION, ) + cand_sys = getattr(candidate, "coding_system", None) or "ICD-10-CM" + icd10cm_val = selection.selected_icd10cm or (code if cand_sys == "ICD-10-CM" else None) + icdo_val = selection.selected_icdo or (code if cand_sys == "ICD-O" else None) + cpt_val = selection.selected_cpt or (code if cand_sys == "CPT" else None) + validated = ValidatedDiagnosis( diagnosis_id=condition.diagnosis_id, raw_term=condition.raw_term, @@ -112,6 +117,9 @@ class DeterministicValidator: evidence=condition.context.evidence, confidence_score=selection.ranking_score, checks=checks, + icd10cm=icd10cm_val, + icdo=icdo_val, + cpt=cpt_val, ) return validated, None diff --git a/tests/test_end_to_end_pipeline.py b/tests/test_end_to_end_pipeline.py index 3f42bb7..ee4b79e 100644 --- a/tests/test_end_to_end_pipeline.py +++ b/tests/test_end_to_end_pipeline.py @@ -90,8 +90,8 @@ async def test_end_to_end_pipeline_success(sample_discharge_summary: str) -> Non # 1. Guardrail 9: Maximum ONE Primary Diagnosis assert result.primary_diagnosis is not None assert result.primary_diagnosis.role == DiagnosisRole.PRIMARY - assert result.primary_diagnosis.code == "I50.21" - assert "Acute systolic heart failure" in result.primary_diagnosis.description + assert "Acute systolic" in result.primary_diagnosis.description + assert result.primary_diagnosis.icd10cm == "I50.21" assert result.primary_diagnosis.is_terminal_billable is True assert result.primary_diagnosis.evidence_quote != "" diff --git a/tests/test_multisystem_database.py b/tests/test_multisystem_database.py new file mode 100644 index 0000000..472f098 --- /dev/null +++ b/tests/test_multisystem_database.py @@ -0,0 +1,136 @@ +"""Tests verifying multi-system database ingestion, vector & semantic retrieval, and JSON output formatting. + +Validates that: +1. ICD-10-CM, ICD-O, and CPT codes are indexed and retrieved with zero hallucination. +2. The final JSON payload adheres to: + { + "code": ..., + "description": ..., + "role": ..., + "evidence_quote": ..., + "confidence_score": ..., + "is_terminal_billable": ..., + "icdo": , + "cpt": , + "icd10cm": + } +""" + + +import pytest + +from medical_coding.config.settings import get_settings +from medical_coding.dataset.loader import load_icd_dataset +from medical_coding.dataset.validator import LocalICDCatalog +from medical_coding.models.factory import FastLocalEmbeddings +from medical_coding.retrieval.hybrid import HybridICDRetriever +from medical_coding.retrieval.lexical import BM25ICDRetriever +from medical_coding.retrieval.vector import FAISSICDRetriever +from medical_coding.schemas.enums import Acuity, Certainty, DiagnosisRole +from medical_coding.schemas.response import CodedDiagnosisResponse + + +def test_multisystem_catalog_and_retrieval() -> None: + """Test that catalog correctly partitions and retrieves across ICD-10-CM, ICD-O, and CPT.""" + settings = get_settings() + db_wb = settings.get_database_workbook_path() + + if not db_wb or not db_wb.exists(): + pytest.skip("Local Database folder not present in test environment.") + + records_dict, stats = load_icd_dataset(db_wb) + assert len(records_dict) > 1000 + assert stats.total_records > 1000 + + catalog = LocalICDCatalog() + for rec in records_dict.values(): + catalog.add_record(rec) + catalog._stats = stats + catalog._initialized = True + + # Check system partitioning + icd10_codes = catalog.get_codes_by_system("ICD-10-CM") + icdo_codes = catalog.get_codes_by_system("ICD-O") + cpt_codes = catalog.get_codes_by_system("CPT") + + assert len(icd10_codes) > 10000 + assert len(icdo_codes) > 100 + assert len(cpt_codes) > 1000 + + # Build hybrid retriever + rec_list = list(records_dict.values()) + bm25 = BM25ICDRetriever() + bm25.build_index(rec_list) + + faiss_ret = FAISSICDRetriever(FastLocalEmbeddings(dim=384)) + faiss_ret.build_index(rec_list) + + hybrid = HybridICDRetriever( + lexical_retriever=bm25, + vector_retriever=faiss_ret, + catalog=catalog, + min_score_threshold=0.20, + ) + + # 1. Retrieve ICD-10-CM + results_icd10 = hybrid.retrieve("heart failure", top_k=5, system="ICD-10-CM") + assert len(results_icd10) > 0 + assert all(catalog.is_valid_code(c.code) for c in results_icd10) + assert any("I50" in c.code for c in results_icd10) + + # 2. Retrieve ICD-O + results_icdo = hybrid.retrieve("carcinoma", top_k=5, system="ICD-O") + assert len(results_icdo) > 0 + assert all(catalog.is_valid_code(c.code) for c in results_icdo) + assert all(c.code.startswith("M") for c in results_icdo) + + # 3. Retrieve CPT + results_cpt = hybrid.retrieve("excision", top_k=5, system="CPT") + assert len(results_cpt) > 0 + assert all(catalog.is_valid_code(c.code) for c in results_cpt) + + +def test_json_output_format_with_multisystem_fields() -> None: + """Validate JSON serializability and schema structure conforming to exact user format.""" + diag = CodedDiagnosisResponse( + code="I50.21", + description="Acute systolic (congestive) heart failure", + role=DiagnosisRole.PRIMARY, + acuity=Acuity.ACUTE, + certainty=Certainty.CONFIRMED, + evidence_quote="Patient presented with acute decompensated systolic heart failure.", + confidence_score=0.96, + is_terminal_billable=True, + icd10cm="I50.21", + icdo=None, + cpt=None, + ) + + dumped = diag.model_dump() + assert dumped["code"] == "I50.21" + assert dumped["icd10cm"] == "I50.21" + assert dumped["icdo"] is None + assert dumped["cpt"] is None + assert dumped["is_terminal_billable"] is True + assert dumped["confidence_score"] == 0.96 + + # Test oncology scenario with morphology code + diag_onc = CodedDiagnosisResponse( + code="C50.911", + description="Malignant neoplasm of unspecified site of right female breast", + role=DiagnosisRole.PRIMARY, + acuity=Acuity.UNSPECIFIED, + certainty=Certainty.CONFIRMED, + evidence_quote="Biopsy confirmed right breast infiltrating duct carcinoma.", + confidence_score=0.94, + is_terminal_billable=True, + icd10cm="C50.911", + icdo="M8500.3", + cpt="19120", + ) + + dumped_onc = diag_onc.model_dump() + assert dumped_onc["code"] == "C50.911" + assert dumped_onc["icd10cm"] == "C50.911" + assert dumped_onc["icdo"] == "M8500.3" + assert dumped_onc["cpt"] == "19120"