feat: integrate local multi-system Database (ICD-10-CM, ICD-O, CPT), add cross-platform installers & dedicated runners

This commit is contained in:
Abhinav Gupta
2026-10-03 10:15:18 +05:30
parent 9ed0318b19
commit d3b000cb7c
32 changed files with 1098 additions and 1618 deletions
+35
View File
@@ -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],
+15
View File
@@ -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:
+149 -2
View File
@@ -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:
+41 -6
View File
@@ -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())
+59 -2
View File
@@ -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
+33 -3
View File
@@ -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"),
}
+1
View File
@@ -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,
)
)
+1
View File
@@ -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,
)
)
+29 -9
View File
@@ -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="",
+12
View File
@@ -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):
+12
View File
@@ -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):
+12 -2
View File
@@ -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,
+23 -3
View File
@@ -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'<span class="pill-badge badge-info">ICD-10-CM: {primary.icd10cm}</span>')
if primary.icdo:
codes_pills.append(f'<span class="pill-badge badge-warning">ICD-O: {primary.icdo}</span>')
if primary.cpt:
codes_pills.append(f'<span class="pill-badge badge-success">CPT: {primary.cpt}</span>')
codes_html = " ".join(codes_pills)
st.markdown(
f"""
<div class="primary-card">
@@ -155,10 +164,11 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
</div>
</div>
<div class="primary-desc">{primary.description}</div>
<div style="display: flex; gap: 8px; margin: 10px 0;">
<div style="display: flex; gap: 8px; margin: 10px 0; flex-wrap: wrap;">
{acuity_badge}
{certainty_badge}
<span class="pill-badge badge-info">Chief Reason for Encounter</span>
{codes_html}
</div>
<div class="evidence-box">
<span style="font-weight: 600; color: #6ee7b7; font-size: 11px; text-transform: uppercase;">
@@ -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'<span class="pill-badge badge-info">ICD-10-CM: {diag.icd10cm}</span>')
if diag.icdo:
sec_codes_pills.append(f'<span class="pill-badge badge-warning">ICD-O: {diag.icdo}</span>')
if diag.cpt:
sec_codes_pills.append(f'<span class="pill-badge badge-success">CPT: {diag.cpt}</span>')
sec_codes_html = " ".join(sec_codes_pills)
with st.container():
st.markdown(
f"""
<div class="secondary-card">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; flex-wrap: wrap;">
<div>
<strong style="font-size: 18px; color: #38bdf8;">#{idx}. {diag.code}</strong>
<span style="font-size: 15px; font-weight: 600; color: #f8fafc; margin-left: 10px;">{diag.description}</span>
</div>
<div style="display: flex; gap: 6px; align-items: center;">
<div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
{billable_badge}
<span class="pill-badge badge-secondary">{acuity_str}</span>
<span class="pill-badge badge-secondary">{certainty_str}</span>
{sec_codes_html}
</div>
</div>
<div class="evidence-box">
+18 -4
View File
@@ -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
@@ -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