# saurabhdvdi/medical-report-analyzer architecture

> Architecture diagram of the GitHub repository saurabhdvdi/medical-report-analyzer, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-09-17). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/saurabhdvdi/medical-report-analyzer
- Repository: https://github.com/saurabhdvdi/medical-report-analyzer

## Overview

#### Purpose and Entry Points
Medical Report Analyzer is a full-stack, role-based clinical-record platform. It ingests PDF/image lab reports, converts them into structured lab values, supports longitudinal analytics and doctor-patient consent, and exposes a grounded AI assistant. Backend startup and router assembly are in `backend/main.py`; the SPA starts at `frontend/src/main.jsx` and routes/authenticates through `frontend/src/App.jsx`.

#### Client Application Boundary
React/Vite provides separate patient and doctor workflows: report management, health dashboards, medicine tracking, doctor discovery, and authorized patient review. `frontend/src/contexts/AuthContext.jsx` owns session/JWT state; API-facing feature modules include `frontend/src/services/reportService.js`, `frontend/src/services/analyticsService.js`, and `frontend/src/services/aiService.js`. Role-gated navigation/view access is centered in `frontend/src/components/RoleRoute.jsx`.

#### API, Identity, and Persistence
FastAPI exposes modular REST domains through `backend/routes/auth.py`, `backend/routes/reports.py`, `backend/routes/analytics.py`, `backend/routes/patient.py`, and related routers. JWT authentication, password hashing, and request identity dependencies are in `backend/auth.py` and `backend/core/security.py`. SQLAlchemy database/session lifecycle is in `backend/database.py`; core clinical, user, access-grant, report, lab-value, medicine, and note entities are defined in `backend/models.py` with additional artery modeling in `backend/models/artery.py`. SQLite is the default datastore; PyMySQL/MySQL is an optional deployment target.

#### Report Ingestion Pipeline
Upload handling persists the original report and drives extraction: multi-engine OCR reads PDFs/images, parser stages identify candidate labs, normalization standardizes values/units/ranges, and validation/classification marks usable or abnormal results. Primary stages reside in `backend/services/ocr_service.py`, `backend/services/report_parser.py`, `backend/services/lab_candidate_extractor.py`, `backend/services/normalizer.py`, and `backend/services/lab_validator.py`. OCR depends on PyTesseract, EasyOCR, PyMuPDF, and optionally Poppler; ingestion may invoke LLM summarization through `backend/ai/llm_service.py`.

#### Analytics and Clinical Views
Structured `LabValue` history feeds deterministic comparison, trend analysis, risk scoring, and generated observations used by dashboards and the AI tool layer. Key services are `backend/services/analytics_service.py`, `backend/services/comparison_service.py`, `backend/services/risk_engine.py`, and `backend/services/insights.py`. The frontend renders this data in patient/doctor dashboards and trend-oriented pages, notably `frontend/src/pages/PatientDashboard.jsx`, `frontend/src/pages/DoctorInterface.jsx`, and `frontend/src/pages/HealthTrendsPage.jsx`.

#### Consent Boundary and Collaboration
Patients and doctors are distinct roles. Doctor access to a patient requires an approved patient-doctor access relationship; revoked, pending, or rejected relationships must not expose patient records. This boundary is applied in authorization logic and domain routes, especially `backend/auth.py`, `backend/routes/doctor.py`, and `backend/routes/patient.py`. Doctor profiles/taxonomy, patient discovery, access lifecycle, and clinical notes are supported by `backend/routes/doctor.py`, `backend/routes/doctor_notes.py`, and `backend/services/doctor_taxonomy_seed.py`.

#### AI Agent and MCP Execution
`backend/routes/ai_routes.py` accepts chat and comparison requests and invokes the LangGraph-based assistant in `backend/ai/agent.py`. The agent establishes a security-scoped target, classifies intent, selects MCP tools, gathers grounded context/RAG, generates via the configured LLM, then returns citations and suggested follow-ups. `backend/mcp/tools.py` defines the security-aware tool registry and `backend/mcp/client.py` executes it; `backend/ai/rag_service.py` and `backend/ai/suggestion_service.py` supply context and next questions. LLM abstraction in `backend/ai/llm_service.py` supports local Ollama or Groq cloud models.

#### Deployment Runtime
The system runs Python/FastAPI/Uvicorn and a Node-built React SPA. Docker definitions exist at `backend/Dockerfile`, `frontend/Dockerfile`, `docker-compose.yml`, and `docker-compose.prod.yml`; Nginx reverse-proxy/static serving configuration is `nginx/nginx.conf`. External runtime dependencies include an LLM endpoint (Ollama or Groq), OCR binaries/services, and SQLite or MySQL.

Main entry points: [`backend/models.py`](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/models.py) (SQLAlchemy models), [`backend/routes/reports.py`](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/routes/reports.py) (Clinical REST routes), [`backend/ai/agent.py`](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/ai/agent.py) (LangGraph assistant), [`frontend/src/main.jsx`](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/frontend/src/main.jsx) (React/Vite app)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_client["React SPA"]
  node_spa["React/Vite app<br/>SPA<br/>[main.jsx]"]
  node_client_auth["Session and role gates<br/>client auth<br/>[AuthContext.jsx]"]
  node_client_api["API service modules<br/>client API<br/>[reportService.js]"]
  node_clinical_views["Clinical dashboards<br/>views"]
end

subgraph group_api["FastAPI API"]
  node_api_app["FastAPI application<br/>API assembly<br/>[main.py]"]
  node_authz["JWT identity and consent<br/>authorization<br/>[auth.py]"]
  node_domain_routes["Clinical REST routes<br/>route modules<br/>[reports.py]"]
  node_ai_routes["AI chat routes<br/>route module<br/>[ai_routes.py]"]
  node_orm["SQLAlchemy models<br/>domain model<br/>[models.py]"]
end

subgraph group_ingestion["Report ingestion"]
  node_upload_extract["OCR extraction<br/>OCR stage<br/>[ocr_service.py]"]
  node_lab_parse["Lab candidate parsing<br/>parser stage"]
  node_normalize_validate["Normalize and validate<br/>quality stage<br/>[normalizer.py]"]
end

subgraph group_clinical["Clinical intelligence"]
  node_analytics["Analytics pipeline<br/>clinical analytics"]
  node_risk_engine["Risk scoring<br/>risk engine<br/>[risk_engine.py]"]
end

subgraph group_assistant["AI assistant"]
  node_agent["LangGraph assistant<br/>AI orchestrator<br/>[agent.py]"]
  node_mcp_tools["Security-aware MCP tools<br/>tool registry<br/>[tools.py]"]
  node_rag["Grounded context<br/>RAG service<br/>[rag_service.py]"]
  node_llm["LLM abstraction<br/>model gateway<br/>[llm_service.py]"]
end

subgraph group_runtime["Runtime dependencies"]
  node_database[("SQLite / MySQL<br/>datastore")]
  node_ocr_runtime{{"OCR engines<br/>external runtime"}}
  node_llm_endpoint{{"Ollama or Groq<br/>external AI"}}
  node_edge_proxy["Nginx deployment edge<br/>reverse proxy<br/>[nginx.conf]"]
end

node_spa -->|"initializes"| node_client_auth
node_spa -->|"uses"| node_client_api
node_spa -->|"renders"| node_clinical_views
node_client_auth -->|"JWT"| node_authz
node_client_api -->|"REST requests"| node_api_app
node_clinical_views -->|"loads data"| node_client_api
node_edge_proxy -->|"serves"| node_spa
node_edge_proxy -->|"proxies"| node_api_app
node_api_app -->|"mounts"| node_domain_routes
node_api_app -->|"mounts"| node_ai_routes
node_domain_routes -->|"authorizes"| node_authz
node_domain_routes -->|"uploads report"| node_upload_extract
node_domain_routes -->|"requests insights"| node_analytics
node_authz -->|"checks identities and grants"| node_orm
node_orm -->|"persists"| node_database
node_upload_extract -->|"uses"| node_ocr_runtime
node_upload_extract -->|"extracted text"| node_lab_parse
node_lab_parse -->|"candidates"| node_normalize_validate
node_normalize_validate -->|"stores reports and lab values"| node_orm
node_orm -->|"lab history"| node_analytics
node_analytics -->|"calculates"| node_risk_engine
node_ai_routes -->|"scopes requester"| node_authz
node_ai_routes -->|"chat and comparison"| node_agent
node_agent -->|"selects tools"| node_mcp_tools
node_mcp_tools -->|"retrieves authorized records"| node_orm
node_agent -->|"gathers context"| node_rag
node_rag -->|"grounds in clinical data"| node_orm
node_agent -->|"generates response"| node_llm
node_llm -->|"invokes"| node_llm_endpoint

click node_spa "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/frontend/src/main.jsx"
click node_client_auth "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/frontend/src/contexts/AuthContext.jsx"
click node_client_api "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/frontend/src/services/reportService.js"
click node_clinical_views "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/frontend/src/pages/PatientDashboard.jsx"
click node_api_app "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/main.py"
click node_authz "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/auth.py"
click node_domain_routes "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/routes/reports.py"
click node_ai_routes "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/routes/ai_routes.py"
click node_orm "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/models.py"
click node_upload_extract "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/services/ocr_service.py"
click node_lab_parse "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/services/lab_candidate_extractor.py"
click node_normalize_validate "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/services/normalizer.py"
click node_analytics "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/services/analytics_service.py"
click node_risk_engine "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/services/risk_engine.py"
click node_agent "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/ai/agent.py"
click node_mcp_tools "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/mcp/tools.py"
click node_rag "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/ai/rag_service.py"
click node_llm "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/ai/llm_service.py"
click node_edge_proxy "https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/nginx/nginx.conf"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_spa,node_client_auth,node_client_api,node_clinical_views toneBlue
class node_api_app,node_authz,node_domain_routes,node_ai_routes,node_orm toneAmber
class node_upload_extract,node_lab_parse,node_normalize_validate toneMint
class node_analytics,node_risk_engine toneRose
class node_agent,node_mcp_tools,node_rag,node_llm toneIndigo
class node_database,node_ocr_runtime,node_llm_endpoint,node_edge_proxy toneTeal
```

## Components

### React SPA

- [React/Vite app](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/frontend/src/main.jsx): SPA · Patient and doctor workflows. · `frontend/src/main.jsx`
- [Session and role gates](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/frontend/src/contexts/AuthContext.jsx): client auth · `frontend/src/contexts/AuthContext.jsx`
- [API service modules](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/frontend/src/services/reportService.js): client API · Reports, analytics, and AI requests. · `frontend/src/services/reportService.js`
- [Clinical dashboards](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/frontend/src/pages/PatientDashboard.jsx): views · Patient, doctor, and trend views. · `frontend/src/pages/PatientDashboard.jsx`

### FastAPI API

- [FastAPI application](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/main.py): API assembly · Startup and modular router registration. · `backend/main.py`
- [JWT identity and consent](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/auth.py): authorization · Enforces roles and approved doctor-patient access. · `backend/auth.py`
- [Clinical REST routes](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/routes/reports.py): route modules · Reports, analytics, patient, doctor, and notes domains. · `backend/routes/reports.py`
- [AI chat routes](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/routes/ai_routes.py): route module · `backend/routes/ai_routes.py`
- [SQLAlchemy models](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/models.py): domain model · Users, records, grants, reports, lab values, medicines, and notes. · `backend/models.py`

### Report ingestion

- [OCR extraction](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/services/ocr_service.py): OCR stage · Reads uploaded PDF and image reports with multiple engines. · `backend/services/ocr_service.py`
- [Lab candidate parsing](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/services/lab_candidate_extractor.py): parser stage · Identifies candidate lab results. · `backend/services/lab_candidate_extractor.py`
- [Normalize and validate](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/services/normalizer.py): quality stage · Standardizes units/ranges and classifies usable or abnormal values. · `backend/services/normalizer.py`

### Clinical intelligence

- [Analytics pipeline](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/services/analytics_service.py): clinical analytics · Comparison, trends, risk scoring, and observations. · `backend/services/analytics_service.py`
- [Risk scoring](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/services/risk_engine.py): risk engine · `backend/services/risk_engine.py`

### AI assistant

- [LangGraph assistant](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/ai/agent.py): AI orchestrator · Scopes target, classifies intent, and returns grounded answers. · `backend/ai/agent.py`
- [Security-aware MCP tools](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/mcp/tools.py): tool registry · `backend/mcp/tools.py`
- [Grounded context](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/ai/rag_service.py): RAG service · `backend/ai/rag_service.py`
- [LLM abstraction](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/backend/ai/llm_service.py): model gateway · Uses local Ollama or Groq. · `backend/ai/llm_service.py`

### Runtime dependencies

- **SQLite / MySQL**: datastore · SQLite default; MySQL optional.
- **OCR engines**: external runtime · Tesseract, EasyOCR, PyMuPDF, and optional Poppler.
- **Ollama or Groq**: external AI
- [Nginx deployment edge](https://github.com/saurabhdvdi/medical-report-analyzer/blob/main/nginx/nginx.conf): reverse proxy · Serves the SPA and proxies application traffic. · `nginx/nginx.conf`

## Connections

- React/Vite app → Session and role gates: initializes
- React/Vite app → API service modules: uses
- React/Vite app → Clinical dashboards: renders
- Session and role gates → JWT identity and consent: JWT
- API service modules → FastAPI application: REST requests
- Clinical dashboards → API service modules: loads data
- Nginx deployment edge → React/Vite app: serves
- Nginx deployment edge → FastAPI application: proxies
- FastAPI application → Clinical REST routes: mounts
- FastAPI application → AI chat routes: mounts
- Clinical REST routes → JWT identity and consent: authorizes
- Clinical REST routes → OCR extraction: uploads report
- Clinical REST routes → Analytics pipeline: requests insights
- JWT identity and consent → SQLAlchemy models: checks identities and grants
- SQLAlchemy models → SQLite / MySQL: persists
- OCR extraction → OCR engines: uses
- OCR extraction → Lab candidate parsing: extracted text
- Lab candidate parsing → Normalize and validate: candidates
- Normalize and validate → SQLAlchemy models: stores reports and lab values
- SQLAlchemy models → Analytics pipeline: lab history
- Analytics pipeline → Risk scoring: calculates
- AI chat routes → JWT identity and consent: scopes requester
- AI chat routes → LangGraph assistant: chat and comparison
- LangGraph assistant → Security-aware MCP tools: selects tools
- Security-aware MCP tools → SQLAlchemy models: retrieves authorized records
- LangGraph assistant → Grounded context: gathers context
- Grounded context → SQLAlchemy models: grounds in clinical data
- LangGraph assistant → LLM abstraction: generates response
- LLM abstraction → Ollama or Groq: invokes
