A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
updated readme
cyberholics6c9091e8918d
diff --git a/README.md b/README.mdindex 14d33e7..5fdefa4 100644--- a/README.md+++ b/README.md@@ -69,6 +69,7 @@ Intelligent ai agents for various automation tasks.- [**Job Posting Agent**](./ai_agents/job_posting_agent) - Generates tailored job postings from a company name and role using DeepSeek V4 Flash on NVIDIA NIM.- [**LangChain Data Agent**](./ai_agents/langchain_data_agent) - Query the Chinook SQLite database in plain English through a conversational Streamlit chat interface.- [**Travel Planner Agent**](./ai_agents/travel_planner_agent) - AI trip planning assistant covering weather, budget, packing lists, and day-by-day itineraries from a single request.+- [**Personal Finance Agent**](./ai_agents/personal_finance_agent) - Upload a bank statement CSV, auto-categorize transactions, and ask natural language questions about your spending. Powered by a LangChain tool-calling agent backed by Orq.ai with SQLite persistence.### πΈ OCR@@ -84,6 +85,7 @@ Extracting structure and meaning from visual data and documents.Projects for audio understanding and analysis.- [**Music Explorer**](./audio/music_explorer) β Chat with any audio file or YouTube video using Gemini 3 Flash. Ask for transcriptions, emotion analysis, instrument identification, and timestamp-aware breakdowns.+- [**Multilingual Audio Translator**](./audio/multilingual_audio_translator) β Upload or record audio in any language, get it transcribed with faster-whisper, translated via Gemini, and played back as synthesized speech using Kokoro TTS.### π¬ Multimodal@@ -94,7 +96,7 @@ Projects combining vision, video, and language models.- [**Multimodal Weather App**](./multimodal/multimodal_weather_app) β Upload a map image and get live weather. Mistral Small 4 identifies the city via vision, then fetches real-time conditions through native tool calling.- [**Multimodal RAG**](./multimodal/multimodal_rag) β RAG system that ingests text, URLs, PDFs, images, audio, and video into a shared ChromaDB index. Gemini Embedding 2 handles retrieval and Gemini 3 Flash generates grounded answers, passing actual file URIs for media sources.- [**Image Question Answering**](./multimodal/image_question_answering) β Upload a PDF, select a page, and ask visual questions answered by Gemma 4 with thinking mode. PyMuPDF renders each page to a full-resolution image for grounded reasoning over charts, tables, and figures.-- [**Medical Document Parser**](./multimodal/medical-document-parser) - Extracts a structured clinical profile from medical PDFs and images using Gemma 4 vision.+- [**Medical Document Parser**](./multimodal/medical_document_parser) - Extracts a structured clinical profile from medical PDFs and images using Gemma 4 vision.### π RAG Applicationsdiff --git a/multimodal/medical-document-parser/.env.example b/multimodal/medical-document-parser/.env.exampledeleted file mode 100644index 8c7ca3d..0000000--- a/multimodal/medical-document-parser/.env.example+++ /dev/null@@ -1 +0,0 @@-ORQ_API_KEY=your_orq_api_key_herediff --git a/multimodal/medical-document-parser/README.md b/multimodal/medical-document-parser/README.mddeleted file mode 100644index 5a46587..0000000--- a/multimodal/medical-document-parser/README.md+++ /dev/null@@ -1,100 +0,0 @@-# Medical Document Parser--> Extract a structured clinical profile from medical PDFs and images using Gemma 4 vision via Orq.ai.--## Overview--Medical Document Parser is a Gradio app that ingests lab reports, prescriptions, imaging results, and clinical notes. PyMuPDF classifies each PDF page as text or vision, routes content to the appropriate extraction path, and uses Gemma 4 (`gemma-4-31b-it`) via [Orq.ai](https://orq.ai) to return a unified JSON clinical profile. Abnormal and critical values are surfaced in a dedicated flagged panel.--## Demo-----## Features--- Upload medical PDFs or images (PNG, JPG, WEBP, BMP, TIFF)-- Per-page routing: text pages (>50 characters) vs vision pages (charts, scans, complex layouts)-- Vision pages rendered at 150 DPI with Pillow before analysis-- Structured JSON extraction with patient info, labs, imaging, and clinical signals-- Multi-page PDF support with merged results across pages-- Progress bar during processing-- Abnormal and critical values highlighted in red--## Tech Stack--| Layer | Technology |-|-------|------------|-| LLM | Gemma 4 (`gemma-4-31b-it`) via [Orq.ai](https://orq.ai) (`openai` SDK) |-| PDF parsing | PyMuPDF (`fitz`) |-| Image processing | Pillow |-| UI | Gradio |-| Config | `python-dotenv`, Pydantic |--## Prerequisites--- Python 3.10+-- [Orq.ai API key](https://orq.ai)--## Installation--```bash-git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git-cd Hands-On-AI-Engineering/multimodal/medical_document_parser-```--**Windows**--```bash-py -m venv .venv-.venv\Scripts\activate-pip install -r requirements.txt-copy .env.example .env-```--**macOS / Linux**--```bash-python3 -m venv .venv-source .venv/bin/activate-pip install -r requirements.txt-cp .env.example .env-```--Edit `.env` and set your API key before running the app.--## Usage--```bash-python app.py-```--Open the local Gradio URL shown in the terminal (typically `http://127.0.0.1:7860`). Upload a medical document, click **Extract Clinical Profile**, and review the JSON output and flagged values.--## Environment Variables--| Variable | Required | Description |-|----------|----------|-------------|-| `ORQ_API_KEY` | Yes | API key from [Orq.ai](https://orq.ai) |--Copy `.env.example` to `.env` and add your key:--```env-ORQ_API_KEY=your_orq_api_key_here-```--## Project Structure--```text-medical-document-parser/-βββ app.py # Gradio UI and orchestration-βββ document_processor.py # PDF/image page classification and rendering-βββ llm_extractor.py # Gemma 4 API calls via Orq.ai (OpenAI SDK)-βββ merger.py # Multi-page result merging-βββ schemas.py # Pydantic clinical profile schema-βββ requirements.txt-βββ .env.example-βββ assets/-β βββ demo.png # Demo screenshot-βββ README.md-```diff --git a/multimodal/medical-document-parser/app.py b/multimodal/medical-document-parser/app.pydeleted file mode 100644index 7536e78..0000000--- a/multimodal/medical-document-parser/app.py+++ /dev/null@@ -1,110 +0,0 @@-from __future__ import annotations--from pathlib import Path--import gradio as gr-from dotenv import load_dotenv--from document_processor import process_upload-from llm_extractor import _build_client, extract_from_page-from merger import merge_profiles--PROJECT_DIR = Path(__file__).resolve().parent-load_dotenv(PROJECT_DIR / ".env")--CUSTOM_CSS = """-.flagged-box textarea {- color: #dc3545 !important;- font-weight: 600 !important;- background: #fff5f5 !important;- border-color: #f5c2c7 !important;-}-"""---def _format_flagged_text(flagged_items: list[str]) -> str:- if not flagged_items:- return "No abnormal or critical values flagged."- return "\n".join(f"β’ {item}" for item in flagged_items)---def parse_document(- upload: str | None,- progress: gr.Progress = gr.Progress(),-) -> tuple[dict, str]:- if upload is None:- raise gr.Error("Please upload a medical PDF or image.")-- file_path = Path(upload)- if not file_path.exists():- raise gr.Error("Uploaded file could not be found.")-- progress(0, desc="Preparing document...")- pages = process_upload(file_path)- if not pages:- raise gr.Error("No pages were found in the uploaded document.")-- client = _build_client()- profiles = []- total = len(pages)-- for index, page in enumerate(pages, start=1):- progress(- index / total,- desc=f"Analyzing page {index}/{total} ({page.kind}) with Gemma 4...",- )- profiles.append(extract_from_page(client, page))-- progress(1.0, desc="Merging results...")- merged = merge_profiles(profiles)- payload = merged.model_dump()- return payload, _format_flagged_text(payload["flagged_items"])---def build_app() -> gr.Blocks:- with gr.Blocks(title="Medical Document Parser") as demo:- gr.Markdown(- """- # Medical Document Parser- Upload a medical **PDF** or **image** (lab report, prescription, imaging result, or clinical notes).- The app routes each page through text or vision extraction, then uses **Gemma 4** to build a unified clinical profile.- """- )-- with gr.Row():- upload = gr.File(- label="Medical document",- file_types=[".pdf", ".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff"],- type="filepath",- )-- parse_button = gr.Button("Extract Clinical Profile", variant="primary")-- with gr.Row():- json_output = gr.JSON(label="Structured Clinical Profile")- flagged_output = gr.Textbox(- label="Flagged Abnormal Values",- lines=10,- elem_classes=["flagged-box"],- )-- parse_button.click(- fn=parse_document,- inputs=[upload],- outputs=[json_output, flagged_output],- )-- gr.Markdown(- """- **How it works**- 1. PyMuPDF classifies each PDF page as text (>50 characters) or vision.- 2. Text pages are sent directly to Gemma 4; vision pages are rendered at 150 DPI.- 3. Per-page extractions are merged into one JSON profile with abnormal values highlighted.- """- )-- return demo---if __name__ == "__main__":- build_app().launch(css=CUSTOM_CSS, theme=gr.themes.Soft())diff --git a/multimodal/medical-document-parser/document_processor.py b/multimodal/medical-document-parser/document_processor.pydeleted file mode 100644index c6a1274..0000000--- a/multimodal/medical-document-parser/document_processor.py+++ /dev/null@@ -1,83 +0,0 @@-from __future__ import annotations--import io-from dataclasses import dataclass-from pathlib import Path-from typing import Literal--import fitz-from PIL import Image--TEXT_THRESHOLD = 50-RENDER_DPI = 150--PageKind = Literal["text", "vision"]---@dataclass-class ProcessedPage:- page_number: int- kind: PageKind- text: str | None = None- image_bytes: bytes | None = None---def _text_page(page: fitz.Page) -> ProcessedPage:- return ProcessedPage(- page_number=page.number + 1,- kind="text",- text=page.get_text("text").strip(),- )---def _vision_page(page: fitz.Page) -> ProcessedPage:- pixmap = page.get_pixmap(dpi=RENDER_DPI)- image = Image.frombytes("RGB", (pixmap.width, pixmap.height), pixmap.samples)- buffer = io.BytesIO()- image.save(buffer, format="PNG")- return ProcessedPage(- page_number=page.number + 1,- kind="vision",- image_bytes=buffer.getvalue(),- )---def _classify_pdf_page(page: fitz.Page) -> ProcessedPage:- text = page.get_text("text").strip()- if len(text) > TEXT_THRESHOLD:- return ProcessedPage(- page_number=page.number + 1,- kind="text",- text=text,- )- return _vision_page(page)---def _image_to_page(image_bytes: bytes, page_number: int = 1) -> ProcessedPage:- image = Image.open(io.BytesIO(image_bytes))- if image.mode != "RGB":- image = image.convert("RGB")- buffer = io.BytesIO()- image.save(buffer, format="PNG")- return ProcessedPage(- page_number=page_number,- kind="vision",- image_bytes=buffer.getvalue(),- )---def process_upload(file_path: str | Path) -> list[ProcessedPage]:- path = Path(file_path)- suffix = path.suffix.lower()-- if suffix == ".pdf":- pages: list[ProcessedPage] = []- with fitz.open(path) as document:- for page in document:- pages.append(_classify_pdf_page(page))- return pages-- if suffix in {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff"}:- return [_image_to_page(path.read_bytes())]-- raise ValueError(f"Unsupported file type: {suffix or 'unknown'}")diff --git a/multimodal/medical-document-parser/llm_extractor.py b/multimodal/medical-document-parser/llm_extractor.pydeleted file mode 100644index 0ff5db0..0000000--- a/multimodal/medical-document-parser/llm_extractor.py+++ /dev/null@@ -1,97 +0,0 @@-from __future__ import annotations--import base64-import json-import os-import re--from openai import OpenAI--from document_processor import ProcessedPage-from schemas import ClinicalProfile--MODEL_ID = "gemma-4-31b-it"-ORQ_BASE_URL = "https://api.orq.ai/v3/router"--SYSTEM_INSTRUCTION = """You are a clinical document extraction assistant.-Extract structured medical information from the provided page content.-Return only factual information present in the document.-Use empty strings or empty lists when information is missing.-For lab findings, set status to:-- normal: within reference range-- abnormal: outside reference range but not life-threatening-- critical: dangerously out of range or marked critical-Populate flagged_items with concise descriptions of abnormal or critical values."""--EXTRACTION_PROMPT = """Extract a structured clinical profile from this medical document page.-Include patient demographics, laboratory results, imaging findings, clinical signals,-and any abnormal or critical values in flagged_items."""---def _build_client() -> OpenAI:- 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.")- return OpenAI(- base_url=ORQ_BASE_URL,- api_key=api_key,- )---def _system_message() -> str:- schema = json.dumps(ClinicalProfile.model_json_schema(), indent=2)- return (- f"{SYSTEM_INSTRUCTION}\n\n"- "Respond with valid JSON only, matching this schema:\n"- f"{schema}"- )---def _parse_response_text(text: str) -> ClinicalProfile:- cleaned = text.strip()- if cleaned.startswith("```"):- cleaned = re.sub(r"^```(?:json)?\s*", "", cleaned)- cleaned = re.sub(r"\s*```$", "", cleaned)- data = json.loads(cleaned)- return ClinicalProfile.model_validate(data)---def extract_from_page(client: OpenAI, page: ProcessedPage) -> ClinicalProfile:- page_context = f"{EXTRACTION_PROMPT}\n\nPage {page.page_number}."- messages: list[dict] = [{"role": "system", "content": _system_message()}]-- if page.kind == "text" and page.text:- messages.append(- {- "role": "user",- "content": f"{page_context}\n\nDocument text:\n{page.text}",- }- )- elif page.kind == "vision" and page.image_bytes:- image_b64 = base64.b64encode(page.image_bytes).decode("utf-8")- messages.append(- {- "role": "user",- "content": [- {- "type": "image_url",- "image_url": {"url": f"data:image/png;base64,{image_b64}"},- },- {"type": "text", "text": page_context},- ],- }- )- else:- return ClinicalProfile()-- response = client.chat.completions.create(- model=MODEL_ID,- messages=messages,- response_format={"type": "json_object"},- )-- content = response.choices[0].message.content- if not content:- return ClinicalProfile()-- return _parse_response_text(content)diff --git a/multimodal/medical-document-parser/merger.py b/multimodal/medical-document-parser/merger.pydeleted file mode 100644index 00aae86..0000000--- a/multimodal/medical-document-parser/merger.py+++ /dev/null@@ -1,64 +0,0 @@-from __future__ import annotations--from schemas import ClinicalProfile, ImagingResult, LabFinding, PatientInfo---def _merge_patient(current: PatientInfo, incoming: PatientInfo) -> PatientInfo:- return PatientInfo(- name=current.name or incoming.name,- age=current.age or incoming.age,- date=current.date or incoming.date,- )---def _dedupe_lab_findings(findings: list[LabFinding]) -> list[LabFinding]:- seen: dict[str, LabFinding] = {}- for finding in findings:- key = finding.test.strip().lower()- if not key:- continue- existing = seen.get(key)- if existing is None or (existing.status == "normal" and finding.status != "normal"):- seen[key] = finding- return list(seen.values())---def _dedupe_strings(items: list[str]) -> list[str]:- seen: set[str] = set()- result: list[str] = []- for item in items:- normalized = item.strip()- if not normalized:- continue- key = normalized.lower()- if key in seen:- continue- seen.add(key)- result.append(normalized)- return result---def merge_profiles(profiles: list[ClinicalProfile]) -> ClinicalProfile:- merged = ClinicalProfile()-- for profile in profiles:- merged.patient = _merge_patient(merged.patient, profile.patient)- merged.lab_findings.extend(profile.lab_findings)- merged.imaging_results.extend(profile.imaging_results)- merged.clinical_signals.extend(profile.clinical_signals)- merged.flagged_items.extend(profile.flagged_items)-- merged.lab_findings = _dedupe_lab_findings(merged.lab_findings)- merged.clinical_signals = _dedupe_strings(merged.clinical_signals)- merged.flagged_items = _dedupe_strings(merged.flagged_items)-- for finding in merged.lab_findings:- if finding.status in {"abnormal", "critical"}:- label = f"{finding.test}: {finding.value}"- if finding.normal_range:- label += f" (ref: {finding.normal_range})"- label += f" [{finding.status}]"- if label not in merged.flagged_items:- merged.flagged_items.append(label)-- return mergeddiff --git a/multimodal/medical-document-parser/requirements.txt b/multimodal/medical-document-parser/requirements.txtdeleted file mode 100644index ba835db..0000000--- a/multimodal/medical-document-parser/requirements.txt+++ /dev/null@@ -1,6 +0,0 @@-gradio>=5.0.0-openai>=1.0.0-PyMuPDF>=1.24.0-Pillow>=10.0.0-python-dotenv>=1.0.0-pydantic>=2.0.0diff --git a/multimodal/medical-document-parser/schemas.py b/multimodal/medical-document-parser/schemas.pydeleted file mode 100644index 8b2016e..0000000--- a/multimodal/medical-document-parser/schemas.py+++ /dev/null@@ -1,32 +0,0 @@-from __future__ import annotations--from typing import Literal--from pydantic import BaseModel, Field---class PatientInfo(BaseModel):- name: str = ""- age: str = ""- date: str = ""---class LabFinding(BaseModel):- test: str = ""- value: str = ""- normal_range: str = ""- status: Literal["normal", "abnormal", "critical"] = "normal"---class ImagingResult(BaseModel):- study: str = ""- findings: str = ""- impression: str = ""---class ClinicalProfile(BaseModel):- patient: PatientInfo = Field(default_factory=PatientInfo)- lab_findings: list[LabFinding] = Field(default_factory=list)- imaging_results: list[ImagingResult] = Field(default_factory=list)- clinical_signals: list[str] = Field(default_factory=list)- flagged_items: list[str] = Field(default_factory=list)diff --git a/multimodal/medical_document_parser/.env.example b/multimodal/medical_document_parser/.env.exampleindex aaf663d..8c7ca3d 100644--- a/multimodal/medical_document_parser/.env.example+++ b/multimodal/medical_document_parser/.env.example@@ -1 +1 @@-GOOGLE_API_KEY=your_google_ai_studio_api_key_here+ORQ_API_KEY=your_orq_api_key_herediff --git a/multimodal/medical-document-parser/.gitignore b/multimodal/medical_document_parser/.gitignoresimilarity index 100%rename from multimodal/medical-document-parser/.gitignorerename to multimodal/medical_document_parser/.gitignorediff --git a/multimodal/medical_document_parser/README.md b/multimodal/medical_document_parser/README.mdindex d3e8358..5a46587 100644--- a/multimodal/medical_document_parser/README.md+++ b/multimodal/medical_document_parser/README.md@@ -1,14 +1,14 @@# Medical Document Parser-> Extract a structured clinical profile from medical PDFs and images using Gemma 4 vision.+> Extract a structured clinical profile from medical PDFs and images using Gemma 4 vision via Orq.ai.## Overview-Medical Document Parser is a Gradio app that ingests lab reports, prescriptions, imaging results, and clinical notes. PyMuPDF classifies each PDF page as text or vision, routes content to the appropriate extraction path, and uses Gemma 4 (`gemma-4-31b-it`) via the Google AI Studio API to return a unified JSON clinical profile. Abnormal and critical values are surfaced in a dedicated flagged panel.+Medical Document Parser is a Gradio app that ingests lab reports, prescriptions, imaging results, and clinical notes. PyMuPDF classifies each PDF page as text or vision, routes content to the appropriate extraction path, and uses Gemma 4 (`gemma-4-31b-it`) via [Orq.ai](https://orq.ai) to return a unified JSON clinical profile. Abnormal and critical values are surfaced in a dedicated flagged panel.## Demo-+## Features@@ -25,7 +25,7 @@ Medical Document Parser is a Gradio app that ingests lab reports, prescriptions,| Layer | Technology ||-------|------------|-| LLM | Gemma 4 (`gemma-4-31b-it`) via [Google AI Studio API](https://aistudio.google.com) (`google-genai`, thinking mode) |+| LLM | Gemma 4 (`gemma-4-31b-it`) via [Orq.ai](https://orq.ai) (`openai` SDK) || PDF parsing | PyMuPDF (`fitz`) || Image processing | Pillow || UI | Gradio |@@ -34,7 +34,7 @@ Medical Document Parser is a Gradio app that ingests lab reports, prescriptions,## Prerequisites- Python 3.10+-- [Google AI Studio API key](https://aistudio.google.com/app/apikey)+- [Orq.ai API key](https://orq.ai)## Installation@@ -75,12 +75,12 @@ Open the local Gradio URL shown in the terminal (typically `http://127.0.0.1:786| Variable | Required | Description ||----------|----------|-------------|-| `GOOGLE_API_KEY` | Yes | API key from [Google AI Studio](https://aistudio.google.com/app/apikey) |+| `ORQ_API_KEY` | Yes | API key from [Orq.ai](https://orq.ai) |Copy `.env.example` to `.env` and add your key:```env-GOOGLE_API_KEY=your_google_ai_studio_api_key_here+ORQ_API_KEY=your_orq_api_key_here```## Project Structure@@ -89,7 +89,7 @@ GOOGLE_API_KEY=your_google_ai_studio_api_key_heremedical-document-parser/βββ app.py # Gradio UI and orchestrationβββ document_processor.py # PDF/image page classification and rendering-βββ llm_extractor.py # Gemma 4 API calls and JSON parsing+βββ llm_extractor.py # Gemma 4 API calls via Orq.ai (OpenAI SDK)βββ merger.py # Multi-page result mergingβββ schemas.py # Pydantic clinical profile schemaβββ requirements.txtdiff --git a/multimodal/medical-document-parser/assets/demo.gif b/multimodal/medical_document_parser/assets/demo.gifsimilarity index 100%rename from multimodal/medical-document-parser/assets/demo.gifrename to multimodal/medical_document_parser/assets/demo.gifdiff --git a/multimodal/medical_document_parser/assets/demo.png b/multimodal/medical_document_parser/assets/demo.pngdeleted file mode 100644index bd0e57d..0000000Binary files a/multimodal/medical_document_parser/assets/demo.png and /dev/null differdiff --git a/multimodal/medical_document_parser/llm_extractor.py b/multimodal/medical_document_parser/llm_extractor.pyindex 1397130..0ff5db0 100644--- a/multimodal/medical_document_parser/llm_extractor.py+++ b/multimodal/medical_document_parser/llm_extractor.py@@ -1,16 +1,17 @@from __future__ import annotations+import base64import jsonimport osimport re-from google import genai-from google.genai import types+from openai import OpenAIfrom document_processor import ProcessedPagefrom schemas import ClinicalProfileMODEL_ID = "gemma-4-31b-it"+ORQ_BASE_URL = "https://api.orq.ai/v3/router"SYSTEM_INSTRUCTION = """You are a clinical document extraction assistant.Extract structured medical information from the provided page content.@@ -27,21 +28,22 @@ Include patient demographics, laboratory results, imaging findings, clinical sigand any abnormal or critical values in flagged_items."""-def _build_client() -> genai.Client:- api_key = os.getenv("GOOGLE_API_KEY")+def _build_client() -> OpenAI:+ api_key = os.getenv("ORQ_API_KEY")if not api_key:- raise ValueError("GOOGLE_API_KEY is not set. Add it to your .env file.")- return genai.Client(api_key=api_key)---def _generation_config() -> types.GenerateContentConfig:- return types.GenerateContentConfig(- system_instruction=SYSTEM_INSTRUCTION,- response_mime_type="application/json",- response_json_schema=ClinicalProfile.model_json_schema(),- thinking_config=types.ThinkingConfig(- thinking_level=types.ThinkingLevel.HIGH,- ),+ raise ValueError("ORQ_API_KEY is not set. Add it to your .env file.")+ return OpenAI(+ base_url=ORQ_BASE_URL,+ api_key=api_key,+ )+++def _system_message() -> str:+ schema = json.dumps(ClinicalProfile.model_json_schema(), indent=2)+ return (+ f"{SYSTEM_INSTRUCTION}\n\n"+ "Respond with valid JSON only, matching this schema:\n"+ f"{schema}")@@ -54,29 +56,42 @@ def _parse_response_text(text: str) -> ClinicalProfile:return ClinicalProfile.model_validate(data)-def extract_from_page(client: genai.Client, page: ProcessedPage) -> ClinicalProfile:- config = _generation_config()+def extract_from_page(client: OpenAI, page: ProcessedPage) -> ClinicalProfile:page_context = f"{EXTRACTION_PROMPT}\n\nPage {page.page_number}."+ messages: list[dict] = [{"role": "system", "content": _system_message()}]if page.kind == "text" and page.text:- response = client.models.generate_content(- model=MODEL_ID,- contents=f"{page_context}\n\nDocument text:\n{page.text}",- config=config,+ messages.append(+ {+ "role": "user",+ "content": f"{page_context}\n\nDocument text:\n{page.text}",+ })elif page.kind == "vision" and page.image_bytes:- response = client.models.generate_content(- model=MODEL_ID,- contents=[- types.Part.from_bytes(data=page.image_bytes, mime_type="image/png"),- page_context,- ],- config=config,+ image_b64 = base64.b64encode(page.image_bytes).decode("utf-8")+ messages.append(+ {+ "role": "user",+ "content": [+ {+ "type": "image_url",+ "image_url": {"url": f"data:image/png;base64,{image_b64}"},+ },+ {"type": "text", "text": page_context},+ ],+ })else:return ClinicalProfile()- if not response.text:+ response = client.chat.completions.create(+ model=MODEL_ID,+ messages=messages,+ response_format={"type": "json_object"},+ )++ content = response.choices[0].message.content+ if not content:return ClinicalProfile()- return _parse_response_text(response.text)+ return _parse_response_text(content)diff --git a/multimodal/medical_document_parser/requirements.txt b/multimodal/medical_document_parser/requirements.txtindex fc5b7ae..ba835db 100644--- a/multimodal/medical_document_parser/requirements.txt+++ b/multimodal/medical_document_parser/requirements.txt@@ -1,5 +1,5 @@gradio>=5.0.0-google-genai>=1.0.0+openai>=1.0.0PyMuPDF>=1.24.0Pillow>=10.0.0python-dotenv>=1.0.0