Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

audit: fix medical_document_parser - add env comment, module docstring, add missing docstrings across all files

Tiioluwani98097cc84a0f
diff --git a/multimodal/medical_document_parser/.env.example b/multimodal/medical_document_parser/.env.example
index 8c7ca3d..d8e948f 100644
--- a/multimodal/medical_document_parser/.env.example
+++ b/multimodal/medical_document_parser/.env.example
@@ -1 +1,2 @@
+# Orq.ai API key - sign up and copy your key from https://orq.ai
ORQ_API_KEY=your_orq_api_key_here
diff --git a/multimodal/medical_document_parser/app.py b/multimodal/medical_document_parser/app.py
index 7536e78..27ca9c3 100644
--- a/multimodal/medical_document_parser/app.py
+++ b/multimodal/medical_document_parser/app.py
@@ -1,3 +1,5 @@
+"""Gradio app for extracting structured clinical profiles from medical PDFs and images."""
+
from __future__ import annotations
from pathlib import Path
@@ -23,6 +25,7 @@ CUSTOM_CSS = """
def _format_flagged_text(flagged_items: list[str]) -> str:
+ """Format the list of flagged abnormal values into a human-readable string."""
if not flagged_items:
return "No abnormal or critical values flagged."
return "\n".join(f"• {item}" for item in flagged_items)
@@ -32,6 +35,7 @@ def parse_document(
upload: str | None,
progress: gr.Progress = gr.Progress(),
) -> tuple[dict, str]:
+ """Process the uploaded medical document and return the structured profile and flagged values."""
if upload is None:
raise gr.Error("Please upload a medical PDF or image.")
@@ -62,6 +66,7 @@ def parse_document(
def build_app() -> gr.Blocks:
+ """Construct and return the Gradio Blocks interface for the medical document parser."""
with gr.Blocks(title="Medical Document Parser") as demo:
gr.Markdown(
"""
diff --git a/multimodal/medical_document_parser/document_processor.py b/multimodal/medical_document_parser/document_processor.py
index c6a1274..b6a84e7 100644
--- a/multimodal/medical_document_parser/document_processor.py
+++ b/multimodal/medical_document_parser/document_processor.py
@@ -16,6 +16,8 @@ PageKind = Literal["text", "vision"]
@dataclass
class ProcessedPage:
+ """Holds the content of a single document page classified as text or vision."""
+
page_number: int
kind: PageKind
text: str | None = None
@@ -23,6 +25,7 @@ class ProcessedPage:
def _text_page(page: fitz.Page) -> ProcessedPage:
+ """Extract plain text from a PDF page and return it as a text ProcessedPage."""
return ProcessedPage(
page_number=page.number + 1,
kind="text",
@@ -31,6 +34,7 @@ def _text_page(page: fitz.Page) -> ProcessedPage:
def _vision_page(page: fitz.Page) -> ProcessedPage:
+ """Render a PDF page to a PNG image at RENDER_DPI and return it as a vision ProcessedPage."""
pixmap = page.get_pixmap(dpi=RENDER_DPI)
image = Image.frombytes("RGB", (pixmap.width, pixmap.height), pixmap.samples)
buffer = io.BytesIO()
@@ -43,6 +47,7 @@ def _vision_page(page: fitz.Page) -> ProcessedPage:
def _classify_pdf_page(page: fitz.Page) -> ProcessedPage:
+ """Route a PDF page to text or vision extraction based on the extracted character count."""
text = page.get_text("text").strip()
if len(text) > TEXT_THRESHOLD:
return ProcessedPage(
@@ -54,6 +59,7 @@ def _classify_pdf_page(page: fitz.Page) -> ProcessedPage:
def _image_to_page(image_bytes: bytes, page_number: int = 1) -> ProcessedPage:
+ """Convert raw image bytes to a vision ProcessedPage, normalizing to RGB PNG."""
image = Image.open(io.BytesIO(image_bytes))
if image.mode != "RGB":
image = image.convert("RGB")
@@ -67,6 +73,7 @@ def _image_to_page(image_bytes: bytes, page_number: int = 1) -> ProcessedPage:
def process_upload(file_path: str | Path) -> list[ProcessedPage]:
+ """Dispatch a PDF or image file to the appropriate page-processing path and return all pages."""
path = Path(file_path)
suffix = path.suffix.lower()
diff --git a/multimodal/medical_document_parser/llm_extractor.py b/multimodal/medical_document_parser/llm_extractor.py
index 0ff5db0..d1460a7 100644
--- a/multimodal/medical_document_parser/llm_extractor.py
+++ b/multimodal/medical_document_parser/llm_extractor.py
@@ -29,6 +29,7 @@ and any abnormal or critical values in flagged_items."""
def _build_client() -> OpenAI:
+ """Build and return an OpenAI client pointed at the Orq.ai router."""
api_key = os.getenv("ORQ_API_KEY")
if not api_key:
raise ValueError("ORQ_API_KEY is not set. Add it to your .env file.")
@@ -39,6 +40,7 @@ def _build_client() -> OpenAI:
def _system_message() -> str:
+ """Build the system prompt string with the clinical extraction instructions and JSON schema."""
schema = json.dumps(ClinicalProfile.model_json_schema(), indent=2)
return (
f"{SYSTEM_INSTRUCTION}\n\n"
@@ -48,6 +50,7 @@ def _system_message() -> str:
def _parse_response_text(text: str) -> ClinicalProfile:
+ """Strip markdown fences from the LLM response and parse it into a ClinicalProfile."""
cleaned = text.strip()
if cleaned.startswith("```"):
cleaned = re.sub(r"^```(?:json)?\s*", "", cleaned)
@@ -57,6 +60,7 @@ def _parse_response_text(text: str) -> ClinicalProfile:
def extract_from_page(client: OpenAI, page: ProcessedPage) -> ClinicalProfile:
+ """Send a single page to the LLM and return the extracted ClinicalProfile."""
page_context = f"{EXTRACTION_PROMPT}\n\nPage {page.page_number}."
messages: list[dict] = [{"role": "system", "content": _system_message()}]
diff --git a/multimodal/medical_document_parser/merger.py b/multimodal/medical_document_parser/merger.py
index 00aae86..eec4e89 100644
--- a/multimodal/medical_document_parser/merger.py
+++ b/multimodal/medical_document_parser/merger.py
@@ -4,6 +4,7 @@ from schemas import ClinicalProfile, ImagingResult, LabFinding, PatientInfo
def _merge_patient(current: PatientInfo, incoming: PatientInfo) -> PatientInfo:
+ """Merge two PatientInfo objects, preferring the first non-empty value for each field."""
return PatientInfo(
name=current.name or incoming.name,
age=current.age or incoming.age,
@@ -12,6 +13,7 @@ def _merge_patient(current: PatientInfo, incoming: PatientInfo) -> PatientInfo:
def _dedupe_lab_findings(findings: list[LabFinding]) -> list[LabFinding]:
+ """Deduplicate lab findings by test name, keeping the most severe status."""
seen: dict[str, LabFinding] = {}
for finding in findings:
key = finding.test.strip().lower()
@@ -24,6 +26,7 @@ def _dedupe_lab_findings(findings: list[LabFinding]) -> list[LabFinding]:
def _dedupe_strings(items: list[str]) -> list[str]:
+ """Remove duplicate strings from a list using case-insensitive comparison while preserving order."""
seen: set[str] = set()
result: list[str] = []
for item in items:
@@ -39,6 +42,7 @@ def _dedupe_strings(items: list[str]) -> list[str]:
def merge_profiles(profiles: list[ClinicalProfile]) -> ClinicalProfile:
+ """Combine per-page ClinicalProfiles into a single deduplicated profile."""
merged = ClinicalProfile()
for profile in profiles:
diff --git a/multimodal/medical_document_parser/schemas.py b/multimodal/medical_document_parser/schemas.py
index 8b2016e..96bb6c2 100644
--- a/multimodal/medical_document_parser/schemas.py
+++ b/multimodal/medical_document_parser/schemas.py
@@ -6,12 +6,16 @@ from pydantic import BaseModel, Field
class PatientInfo(BaseModel):
+ """Basic patient demographics extracted from the document."""
+
name: str = ""
age: str = ""
date: str = ""
class LabFinding(BaseModel):
+ """A single laboratory test result with its value, reference range, and status."""
+
test: str = ""
value: str = ""
normal_range: str = ""
@@ -19,12 +23,16 @@ class LabFinding(BaseModel):
class ImagingResult(BaseModel):
+ """Findings and impression from a single imaging study."""
+
study: str = ""
findings: str = ""
impression: str = ""
class ClinicalProfile(BaseModel):
+ """Unified clinical profile combining patient info, labs, imaging, and flagged values."""
+
patient: PatientInfo = Field(default_factory=PatientInfo)
lab_findings: list[LabFinding] = Field(default_factory=list)
imaging_results: list[ImagingResult] = Field(default_factory=list)