|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +A complete CDI service that processes clinical notes and extracts billing codes. |
| 4 | +Demonstrates FHIR-native pipelines, legacy system integration, and multi-source data handling. |
| 5 | +
|
| 6 | +Requirements: |
| 7 | +- pip install healthchain |
| 8 | +- pip install scispacy |
| 9 | +- pip install https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.5.4/en_core_sci_sm-0.5.4.tar.gz |
| 10 | +- pip install python-dotenv |
| 11 | +
|
| 12 | +Run: |
| 13 | +- python notereader_clinical_coding_fhir.py # Demo and start server |
| 14 | +""" |
| 15 | + |
| 16 | +import os |
| 17 | +import uvicorn |
| 18 | +from datetime import datetime, timezone |
| 19 | + |
| 20 | +import healthchain as hc |
| 21 | +from fhir.resources.documentreference import DocumentReference |
| 22 | +from fhir.resources.meta import Meta |
| 23 | +from spacy.tokens import Span |
| 24 | +from dotenv import load_dotenv |
| 25 | + |
| 26 | +from healthchain.fhir import create_document_reference |
| 27 | +from healthchain.gateway.api import HealthChainAPI |
| 28 | +from healthchain.gateway.fhir import FHIRGateway |
| 29 | +from healthchain.gateway.soap import NoteReaderService |
| 30 | +from healthchain.io import CdaAdapter, Document |
| 31 | +from healthchain.models import CdaRequest |
| 32 | +from healthchain.pipeline.medicalcodingpipeline import MedicalCodingPipeline |
| 33 | +from healthchain.sandbox.use_cases import ClinicalDocumentation |
| 34 | + |
| 35 | + |
| 36 | +load_dotenv() |
| 37 | + |
| 38 | + |
| 39 | +BILLING_URL = ( |
| 40 | + f"fhir://api.medplum.com/fhir/R4/" |
| 41 | + f"?client_id={os.environ.get('MEDPLUM_CLIENT_ID')}" |
| 42 | + f"&client_secret={os.environ.get('MEDPLUM_CLIENT_SECRET')}" |
| 43 | + f"&token_url={os.environ.get('MEDPLUM_TOKEN_URL', 'https://api.medplum.com/oauth2/token')}" |
| 44 | + f"&scope={os.environ.get('MEDPLUM_SCOPE', 'openid')}" |
| 45 | +) |
| 46 | + |
| 47 | + |
| 48 | +def create_pipeline(): |
| 49 | + """Build FHIR-native ML pipeline with automatic problem extraction.""" |
| 50 | + pipeline = MedicalCodingPipeline.from_model_id("en_core_sci_sm", source="spacy") |
| 51 | + |
| 52 | + # Add custom entity linking |
| 53 | + @pipeline.add_node(position="after", reference="SpacyNLP") |
| 54 | + def link_entities(doc: Document) -> Document: |
| 55 | + """Add CUI codes to medical entities for problem extraction""" |
| 56 | + if not Span.has_extension("cui"): |
| 57 | + Span.set_extension("cui", default=None) |
| 58 | + |
| 59 | + spacy_doc = doc.nlp.get_spacy_doc() |
| 60 | + |
| 61 | + # Simple dummy linker for demo purposes |
| 62 | + dummy_linker = { |
| 63 | + "pneumonia": "233604007", |
| 64 | + "type 2 diabetes mellitus": "44054006", |
| 65 | + "congestive heart failure": "42343007", |
| 66 | + "chronic kidney disease": "431855005", |
| 67 | + "hypertension": "38341003", |
| 68 | + "community acquired pneumonia": "385093006", |
| 69 | + "ventilator associated pneumonia": "233717007", |
| 70 | + "anaphylaxis": "39579001", |
| 71 | + "delirium": "2776000", |
| 72 | + "depression": "35489007", |
| 73 | + "asthma": "195967001", |
| 74 | + "copd": "13645005", |
| 75 | + } |
| 76 | + |
| 77 | + for ent in spacy_doc.ents: |
| 78 | + if ent.text.lower() in dummy_linker: |
| 79 | + ent._.cui = dummy_linker[ent.text.lower()] |
| 80 | + |
| 81 | + return doc |
| 82 | + |
| 83 | + return pipeline |
| 84 | + |
| 85 | + |
| 86 | +def create_app(): |
| 87 | + """Create production healthcare API.""" |
| 88 | + pipeline = create_pipeline() |
| 89 | + cda_adapter = CdaAdapter() |
| 90 | + |
| 91 | + # Modern FHIR sources |
| 92 | + fhir_gateway = FHIRGateway() |
| 93 | + fhir_gateway.add_source("billing", BILLING_URL) |
| 94 | + |
| 95 | + # Legacy CDA processing |
| 96 | + note_service = NoteReaderService() |
| 97 | + |
| 98 | + @note_service.method("ProcessDocument") |
| 99 | + def ai_coding_workflow(request: CdaRequest): |
| 100 | + doc = cda_adapter.parse(request) |
| 101 | + doc = pipeline(doc) |
| 102 | + |
| 103 | + for condition in doc.fhir.problem_list: |
| 104 | + # Add basic provenance tracking |
| 105 | + condition.meta = Meta( |
| 106 | + source="urn:healthchain:pipeline:cdi", |
| 107 | + lastUpdated=datetime.now(timezone.utc).isoformat(), |
| 108 | + ) |
| 109 | + fhir_gateway.create(condition, source="billing") |
| 110 | + |
| 111 | + cda_response = cda_adapter.format(doc) |
| 112 | + |
| 113 | + return cda_response |
| 114 | + |
| 115 | + # Register services |
| 116 | + app = HealthChainAPI(title="Epic CDI Service with FHIR integration") |
| 117 | + app.register_gateway(fhir_gateway, path="/fhir") |
| 118 | + app.register_service(note_service, path="/notereader") |
| 119 | + |
| 120 | + return app |
| 121 | + |
| 122 | + |
| 123 | +def create_sandbox(): |
| 124 | + @hc.sandbox(api="http://localhost:8000/") |
| 125 | + class NotereaderSandbox(ClinicalDocumentation): |
| 126 | + """Sandbox for testing clinical documentation workflows""" |
| 127 | + |
| 128 | + def __init__(self): |
| 129 | + super().__init__() |
| 130 | + self.data_path = "./resources/uclh_cda.xml" |
| 131 | + |
| 132 | + @hc.ehr(workflow="sign-note-inpatient") |
| 133 | + def load_clinical_document(self) -> DocumentReference: |
| 134 | + """Load a sample CDA document for processing""" |
| 135 | + with open(self.data_path, "r") as file: |
| 136 | + xml_content = file.read() |
| 137 | + |
| 138 | + return create_document_reference( |
| 139 | + data=xml_content, |
| 140 | + content_type="text/xml", |
| 141 | + description="Sample CDA document from sandbox", |
| 142 | + ) |
| 143 | + |
| 144 | + return NotereaderSandbox() |
| 145 | + |
| 146 | + |
| 147 | +# Create the app |
| 148 | +app = create_app() |
| 149 | + |
| 150 | + |
| 151 | +if __name__ == "__main__": |
| 152 | + import threading |
| 153 | + from time import sleep |
| 154 | + |
| 155 | + # Start server |
| 156 | + def run_server(): |
| 157 | + uvicorn.run(app, port=8000, log_level="warning") |
| 158 | + |
| 159 | + server_thread = threading.Thread(target=run_server, daemon=True) |
| 160 | + server_thread.start() |
| 161 | + sleep(2) # Wait for startup |
| 162 | + |
| 163 | + # Test sandbox |
| 164 | + sandbox = create_sandbox() |
| 165 | + sandbox.start_sandbox() |
| 166 | + |
| 167 | + try: |
| 168 | + server_thread.join() |
| 169 | + except KeyboardInterrupt: |
| 170 | + pass |
0 commit comments