fix(persistence): persist surgical procedures and structured oncology in database layer
This commit is contained in:
@@ -104,7 +104,7 @@ def init_db(settings: Settings | None = None) -> None:
|
|||||||
engine = get_engine(settings=settings)
|
engine = get_engine(settings=settings)
|
||||||
Base.metadata.create_all(bind=engine)
|
Base.metadata.create_all(bind=engine)
|
||||||
|
|
||||||
# Safely migrate new columns to diagnosis_records if it was created under previous schema
|
# Safely migrate new columns to diagnosis_records and processed_documents if created under previous schema
|
||||||
try:
|
try:
|
||||||
inspector = inspect(engine)
|
inspector = inspect(engine)
|
||||||
if "diagnosis_records" in inspector.get_table_names():
|
if "diagnosis_records" in inspector.get_table_names():
|
||||||
@@ -117,6 +117,17 @@ def init_db(settings: Settings | None = None) -> None:
|
|||||||
if "cpt" not in columns:
|
if "cpt" not in columns:
|
||||||
conn.execute(text("ALTER TABLE diagnosis_records ADD COLUMN cpt VARCHAR(32);"))
|
conn.execute(text("ALTER TABLE diagnosis_records ADD COLUMN cpt VARCHAR(32);"))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
|
if "processed_documents" in inspector.get_table_names():
|
||||||
|
doc_columns = {col["name"] for col in inspector.get_columns("processed_documents")}
|
||||||
|
with engine.connect() as conn:
|
||||||
|
if "procedures_json" not in doc_columns:
|
||||||
|
conn.execute(text("ALTER TABLE processed_documents ADD COLUMN procedures_json TEXT DEFAULT '[]';"))
|
||||||
|
if "operative_findings_json" not in doc_columns:
|
||||||
|
conn.execute(text("ALTER TABLE processed_documents ADD COLUMN operative_findings_json TEXT DEFAULT '[]';"))
|
||||||
|
if "oncology_context_json" not in doc_columns:
|
||||||
|
conn.execute(text("ALTER TABLE processed_documents ADD COLUMN oncology_context_json TEXT DEFAULT '{}';"))
|
||||||
|
conn.commit()
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.warning("Database column migration check notice: %s", exc)
|
logger.warning("Database column migration check notice: %s", exc)
|
||||||
|
|
||||||
|
|||||||
@@ -47,6 +47,11 @@ class ProcessedDocument(Base):
|
|||||||
abstention_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
abstention_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||||
processing_time_ms: Mapped[float] = mapped_column(Float, default=0.0, nullable=False)
|
processing_time_ms: Mapped[float] = mapped_column(Float, default=0.0, nullable=False)
|
||||||
|
|
||||||
|
# Surgical Oncology & Procedures
|
||||||
|
procedures_json: Mapped[str] = mapped_column(Text, default="[]", nullable=False)
|
||||||
|
operative_findings_json: Mapped[str] = mapped_column(Text, default="[]", nullable=False)
|
||||||
|
oncology_context_json: Mapped[str] = mapped_column(Text, default="{}", nullable=False)
|
||||||
|
|
||||||
# Metadata & Auditing
|
# Metadata & Auditing
|
||||||
metadata_json: Mapped[str] = mapped_column(Text, default="{}", nullable=False)
|
metadata_json: Mapped[str] = mapped_column(Text, default="{}", nullable=False)
|
||||||
created_at: Mapped[datetime] = mapped_column(
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
@@ -85,6 +90,27 @@ class ProcessedDocument(Base):
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
procedures = []
|
||||||
|
if getattr(self, "procedures_json", None):
|
||||||
|
try:
|
||||||
|
procedures = json.loads(self.procedures_json)
|
||||||
|
except Exception:
|
||||||
|
procedures = []
|
||||||
|
|
||||||
|
operative_findings = []
|
||||||
|
if getattr(self, "operative_findings_json", None):
|
||||||
|
try:
|
||||||
|
operative_findings = json.loads(self.operative_findings_json)
|
||||||
|
except Exception:
|
||||||
|
operative_findings = []
|
||||||
|
|
||||||
|
oncology_context = {}
|
||||||
|
if getattr(self, "oncology_context_json", None):
|
||||||
|
try:
|
||||||
|
oncology_context = json.loads(self.oncology_context_json)
|
||||||
|
except Exception:
|
||||||
|
oncology_context = {}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"id": self.id,
|
"id": self.id,
|
||||||
"document_id": self.document_id,
|
"document_id": self.document_id,
|
||||||
@@ -101,6 +127,9 @@ class ProcessedDocument(Base):
|
|||||||
"primary_confidence": self.primary_confidence,
|
"primary_confidence": self.primary_confidence,
|
||||||
"secondary_count": self.secondary_count,
|
"secondary_count": self.secondary_count,
|
||||||
"abstention_count": self.abstention_count,
|
"abstention_count": self.abstention_count,
|
||||||
|
"procedures": procedures,
|
||||||
|
"operative_findings": operative_findings,
|
||||||
|
"oncology_context": oncology_context,
|
||||||
"processing_time_ms": self.processing_time_ms,
|
"processing_time_ms": self.processing_time_ms,
|
||||||
"metadata": meta,
|
"metadata": meta,
|
||||||
"created_at": self.created_at.isoformat() if self.created_at else None,
|
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||||||
|
|||||||
@@ -81,6 +81,13 @@ class MedicalCodingRepository:
|
|||||||
doc.abstention_count = len(result.abstentions)
|
doc.abstention_count = len(result.abstentions)
|
||||||
doc.processing_time_ms = result.processing_time_ms
|
doc.processing_time_ms = result.processing_time_ms
|
||||||
doc.metadata_json = json.dumps(meta_dict)
|
doc.metadata_json = json.dumps(meta_dict)
|
||||||
|
doc.procedures_json = json.dumps(result.procedures) if getattr(result, "procedures", None) else "[]"
|
||||||
|
doc.operative_findings_json = (
|
||||||
|
json.dumps(result.operative_findings) if getattr(result, "operative_findings", None) else "[]"
|
||||||
|
)
|
||||||
|
doc.oncology_context_json = (
|
||||||
|
json.dumps(result.oncology_context) if getattr(result, "oncology_context", None) else "{}"
|
||||||
|
)
|
||||||
|
|
||||||
# Clear previous diagnoses, abstentions, checks for clean re-save
|
# Clear previous diagnoses, abstentions, checks for clean re-save
|
||||||
doc.diagnoses.clear()
|
doc.diagnoses.clear()
|
||||||
@@ -106,6 +113,13 @@ class MedicalCodingRepository:
|
|||||||
),
|
),
|
||||||
secondary_count=len(result.secondary_diagnoses),
|
secondary_count=len(result.secondary_diagnoses),
|
||||||
abstention_count=len(result.abstentions),
|
abstention_count=len(result.abstentions),
|
||||||
|
procedures_json=json.dumps(result.procedures) if getattr(result, "procedures", None) else "[]",
|
||||||
|
operative_findings_json=(
|
||||||
|
json.dumps(result.operative_findings) if getattr(result, "operative_findings", None) else "[]"
|
||||||
|
),
|
||||||
|
oncology_context_json=(
|
||||||
|
json.dumps(result.oncology_context) if getattr(result, "oncology_context", None) else "{}"
|
||||||
|
),
|
||||||
processing_time_ms=result.processing_time_ms,
|
processing_time_ms=result.processing_time_ms,
|
||||||
metadata_json=json.dumps(meta_dict),
|
metadata_json=json.dumps(meta_dict),
|
||||||
created_at=datetime.now(UTC),
|
created_at=datetime.now(UTC),
|
||||||
|
|||||||
@@ -264,3 +264,59 @@ def test_export_documents_df(repo: MedicalCodingRepository) -> None:
|
|||||||
assert len(df) == 1
|
assert len(df) == 1
|
||||||
assert df.iloc[0]["document_id"] == "ENC-DF"
|
assert df.iloc[0]["document_id"] == "ENC-DF"
|
||||||
assert df.iloc[0]["primary_code"] == "I50.21"
|
assert df.iloc[0]["primary_code"] == "I50.21"
|
||||||
|
|
||||||
|
|
||||||
|
def test_save_and_retrieve_surgical_oncology_and_procedures(repo: MedicalCodingRepository) -> None:
|
||||||
|
"""Test saving and retrieving procedures, operative findings, and structured oncology context."""
|
||||||
|
res = CodingResult(
|
||||||
|
document_id="ENC-ONC-001",
|
||||||
|
status=ExecutionStatus.SUCCESS,
|
||||||
|
primary_diagnosis=CodedDiagnosisResponse(
|
||||||
|
code="C50.911",
|
||||||
|
description="Malignant neoplasm of unspecified site of right female breast",
|
||||||
|
role=DiagnosisRole.PRIMARY,
|
||||||
|
acuity=Acuity.CHRONIC,
|
||||||
|
certainty=Certainty.CONFIRMED,
|
||||||
|
evidence_quote="invasive ductal carcinoma of right breast",
|
||||||
|
confidence_score=0.96,
|
||||||
|
is_terminal_billable=True,
|
||||||
|
),
|
||||||
|
procedures=["Right modified radical mastectomy", "Sentinel lymph node biopsy"],
|
||||||
|
operative_findings=[
|
||||||
|
{
|
||||||
|
"finding": "Ovarian follicular cyst",
|
||||||
|
"adhesions": True,
|
||||||
|
"eligibility": "EXCLUDED_BY_UHDDS",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
oncology_context={
|
||||||
|
"histology": "invasive ductal carcinoma",
|
||||||
|
"grade": "Grade 2",
|
||||||
|
"er_status": "positive",
|
||||||
|
"pr_status": "positive",
|
||||||
|
"her2_status": "negative",
|
||||||
|
"ki67": "18%",
|
||||||
|
},
|
||||||
|
processing_time_ms=88.5,
|
||||||
|
)
|
||||||
|
|
||||||
|
saved = repo.save_coding_result(
|
||||||
|
result=res,
|
||||||
|
raw_text="Patient underwent right modified radical mastectomy for invasive ductal carcinoma.",
|
||||||
|
filename="operative_report.txt",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert saved["document_id"] == "ENC-ONC-001"
|
||||||
|
assert "Right modified radical mastectomy" in saved["procedures"]
|
||||||
|
assert len(saved["operative_findings"]) == 1
|
||||||
|
assert saved["oncology_context"]["er_status"] == "positive"
|
||||||
|
|
||||||
|
# Query back from DB
|
||||||
|
retrieved = repo.get_document_by_id("ENC-ONC-001")
|
||||||
|
assert retrieved is not None
|
||||||
|
assert retrieved["procedures"] == ["Right modified radical mastectomy", "Sentinel lymph node biopsy"]
|
||||||
|
assert len(retrieved["operative_findings"]) == 1
|
||||||
|
assert retrieved["operative_findings"][0]["finding"] == "Ovarian follicular cyst"
|
||||||
|
assert retrieved["oncology_context"]["histology"] == "invasive ductal carcinoma"
|
||||||
|
assert retrieved["oncology_context"]["her2_status"] == "negative"
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ def test_validation_passes_valid_billable_code(
|
|||||||
assert validated is not None
|
assert validated is not None
|
||||||
assert validated.code == "I50.21"
|
assert validated.code == "I50.21"
|
||||||
assert validated.role == DiagnosisRole.PRIMARY
|
assert validated.role == DiagnosisRole.PRIMARY
|
||||||
assert len(validated.checks) == 2
|
assert len(validated.checks) == 5
|
||||||
assert all(c.passed for c in validated.checks)
|
assert all(c.passed for c in validated.checks)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user