An advanced OCR system for medical prescriptions using a multi-agent architecture with privacy-first PHI filtering and automated drug information extraction.
This system processes medical prescription images through a sophisticated multi-agent pipeline that:
- Extracts text from prescription images using Azure Vision OCR
- Detects and redacts PHI (Protected Health Information) automatically
- Identifies medications and queries multiple drug databases for alternatives
- Provides drug information from FDA, RxNorm, and AI-powered sources
- π€ 6-Agent Architecture - Orchestrated multi-agent system for specialized tasks
- π HIPAA-Compliant PHI Filtering - Automatic detection and redaction of sensitive information
- π Drug Information Extraction - Automated medication detection with database queries
- π Multi-Database Drug Lookup - RxNorm (NIH), FDA openFDA, and LLaMA AI fallback
- πΌοΈ Image Segmentation - SAM2-powered region detection (with fallback)
- π± Modern React UI - Beautiful, responsive interface for image upload and results display
The system uses 6 specialized agents coordinated by an orchestrator:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β OrchestratorAgent β
β (Routes tasks to specialized agents) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β OCRAgent β
β (Coordinates full pipeline workflow) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β β
ββββββββββββββ ββββββββββββββ ββββββββββββββ ββββββββββββββ
βSegmentationβ β Text β β PHI β β Drug β
β Agent β βRecognition β β Filter β βInformation β
β β β Agent β β Agent β β Agent β
ββββββββββββββ ββββββββββββββ ββββββββββββββ ββββββββββββββ
Image Upload
β
βββββββββββββββββββββββββββββββββββββββ
β STEP 1: Image Segmentation β
β Agent: SegmentationAgent β
β Tools: SAM2 / Fallback Contours β
β Output: Detected regions β
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β STEP 2: Text Recognition β
β Agent: TextRecognitionAgent β
β Tools: Azure Vision OCR / TrOCR β
β Output: Extracted text β
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β STEP 3: PHI Filtering β
β Agent: PHIFilterAgent β
β Tools: HuggingFace NER + Regex β
β Output: Redacted text, PHI list β
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β STEP 4: Drug Information β
β Agent: DrugInformationAgent β
β Tools: RxNorm, FDA, LLaMA AI β
β Output: Medications + Alternatives β
βββββββββββββββββββββββββββββββββββββββ
β
Final Response to UI
- Purpose: Routes incoming tasks to the appropriate specialized agent
- Routing Rules:
- "prescription" β OCRAgent
- "segment" β SegmentationAgent
- "phi" / "hipaa" β PHIFilterAgent
- "drug" / "medication" β DrugInformationAgent
- Capabilities: Task delegation, agent discovery, priority-based routing
- Purpose: Coordinates the entire OCR pipeline
- Workflow:
- Delegates segmentation to SegmentationAgent
- Delegates text extraction to TextRecognitionAgent
- Delegates PHI filtering to PHIFilterAgent
- Delegates drug extraction to DrugInformationAgent
- Processing Modes:
full- Complete pipeline (default)ocr_only- Text extraction onlysegment_only- Image segmentation only
- Purpose: Detects and extracts regions from prescription images
- Tools:
- SAM2 (Segment Anything Model 2) - Advanced AI segmentation
- Fallback Contour Detection - OpenCV-based region detection
- Region Extraction - Crops and preprocesses detected regions
- Output: List of regions with bounding boxes and cropped images
- Purpose: Extracts text from images using OCR
- Tools:
- Azure Vision OCR - Microsoft's cloud OCR API (primary)
- TrOCR - Transformer-based handwriting recognition (optional)
- Methods:
auto- Tries all available methodsazure- Azure Vision onlytrocr- TrOCR only
- Output: Extracted text with confidence scores
- Purpose: Detects and redacts Protected Health Information
- Tools:
- HuggingFace NER - Named Entity Recognition for person names
- Regex Patterns - Pattern matching for structured PHI
- Detects:
- π€ Names - Patient and doctor names
- π Dates - Birth dates, appointment dates
- π Phone Numbers - All formats
- π§ Email Addresses
- π Addresses - Street addresses
- π’ SSN - Social Security Numbers
- π Medical IDs - MRNs, Patient IDs
- π³ Insurance Numbers
- Output: Redacted text (PHI replaced with
[TYPE_REDACTED]), PHI entity list
- Purpose: Extracts medications and queries drug databases
- Tools:
- FAISS Vector Database - Local database of 106 essential medications with semantic search
- Medication Extractor - Regex-based pattern matching
- RxNorm API - NIH drug database (free, international)
- FDA openFDA API - US FDA drug labels database
- LLaMA AI - AI-powered fallback for unknown drugs
- Query Priority:
- Vector Database (local, 10ms response time)
- RxNorm API (NIH, international coverage)
- FDA openFDA (US drug labels)
- LLaMA AI (AI-generated fallback)
- Extraction Patterns:
Tab. Augmentin 625mgCap. Amoxicillin 500mg- Drug names with common suffixes (cillin, mycin, pril, etc.)
- 100+ common medication names
- Output:
- Medication list (name + dosage)
- Drug alternatives from multiple sources
- Manufacturer information
- Indications and usage
- Category and usage classification
- Multi-source information combining all databases
- Framework: FastAPI (Python)
- Agent System: Custom multi-agent framework with async/await
- OCR: Azure Vision API
- Segmentation: SAM2 (Meta AI) + OpenCV fallback
- NLP: HuggingFace Transformers (NER models)
- Vector Database: FAISS + SentenceTransformers (all-MiniLM-L6-v2)
- Drug APIs: RxNorm (NIH), openFDA, HuggingFace LLaMA
- Image Processing: OpenCV, NumPy, PIL
- Framework: React 18
- Build Tool: Vite
- Styling: CSS3 with modern features
- State Management: React Hooks
- Azure Vision API - Text extraction
- RxNorm REST API - Drug information
- FDA openFDA API - US drug labels
- HuggingFace Inference API - NER and LLaMA
- Meta SAM2 - Image segmentation
- FAISS Vector Database - Local medication database (106 drugs)
ocr/
βββ backend/ # Backend API server
β βββ agent_system.py # Agent system initialization
β βββ main_agent_api.py # FastAPI server with agent routes
β βββ main.py # Legacy API (reference)
β βββ requirements.txt # Python dependencies
β βββ .env # Configuration (keys, tokens)
β βββ drugs.json # Essential medications dataset (106 drugs)
β βββ load_drugs_json.py # Load medications into vector DB
β βββ medication_vector_db.py # Vector database implementation
β βββ agents/ # Agent implementations
β β βββ __init__.py
β β βββ base_agent.py # Base agent class
β β βββ orchestrator.py # Task routing agent
β β βββ ocr_agent.py # Pipeline coordinator
β β βββ segmentation_agent.py # Image segmentation
β β βββ text_recognition_agent.py # Text extraction
β β βββ phi_filter_agent.py # PHI detection/redaction
β β βββ drug_information_agent.py # Medication extraction
β β βββ tools.py # Tool implementations
β βββ medication_db/ # Vector database storage
β β βββ faiss_index.bin # FAISS vector index
β β βββ metadata.json # Medication metadata
β βββ checkpoints/ # Model checkpoints
β β βββ sam2_hiera_large.pt # SAM2 model (900MB)
β βββ segment-anything-2/ # SAM2 library
β
βββ src/ # React frontend
β βββ components/
β β βββ LandingPage.jsx # Main UI component
β β βββ LandingPage.css # Styling
β βββ App.jsx
β βββ main.jsx
β
βββ index.html
βββ package.json
βββ vite.config.js
βββ README.md
- Python 3.8+
- Node.js 16+
- Azure Vision API credentials
- HuggingFace API token (optional, for LLaMA)
- Install Python dependencies:
cd backend
pip install -r requirements.txt- Build Vector Database (essential medications):
# Load 106 essential medications from drugs.json into vector database
python load_drugs_json.py drugs.jsonThis creates a FAISS vector database in medication_db/ with semantic search capabilities.
- Install SAM2 (optional, for advanced segmentation):
cd segment-anything-2
pip install -e .- Download SAM2 checkpoint (optional):
cd ..
python download_sam2_checkpoint.py- Configure environment variables (
.envfile):
# Azure Vision API (Required)
AZURE_VISION_ENDPOINT=https://your-resource.cognitiveservices.azure.com/
AZURE_VISION_KEY=your_azure_key
# HuggingFace API (Optional - for LLaMA AI fallback)
HF_TOKEN=your_huggingface_token- Start the agent API server:
python main_agent_api.pyServer will be available at http://localhost:8000
- Install Node dependencies:
npm install- Start development server:
npm run devApp will be available at http://localhost:5173
Process an image through the full agent pipeline.
Request:
curl -X POST http://localhost:8000/api/process-image \
-F "file=@prescription.jpg" \
-F "mode=full" \
-F "filter_phi=true"Parameters:
file- Image file (JPEG, PNG)mode- Processing mode:full,ocr_only,segment_onlyfilter_phi- Enable PHI filtering (default: true)include_regions- Include region details (default: false)
Response:
{
"success": true,
"mode": "full",
"agent_used": "OCRAgent",
"tools_used": ["azure_vision_ocr", "filter_phi", "extract_medications"],
"regions_detected": 3,
"extracted_text": "Tab. Augmentin 625mg...",
"redacted_text": "[NAME_REDACTED]...",
"phi_summary": [
{"type": "NAME", "original": "John Doe"},
{"type": "DATE", "original": "12-09-2025"}
],
"medications": [
{"name": "augmentin", "dosage": "625mg"}
],
"drug_alternatives": [
{
"original_drug": {"name": "augmentin", "dosage": "625mg"},
"drug_info": {
"found": true,
"alternatives": [...],
"source": "RxNorm (NIH)"
}
}
]
}Filter PHI from text directly (without image).
Request:
curl -X POST http://localhost:8000/api/phi/filter \
-H "Content-Type: application/json" \
-d '{"text": "Patient: John Doe, Age: 45, Phone: 555-1234"}'Check system health and status.
Response:
{
"status": "healthy",
"agent_system_initialized": true,
"sam2_loaded": false,
"trocr_loaded": false
}Get detailed agent system status.
-
full- Complete pipeline (recommended)- Segmentation β OCR β PHI Filtering β Drug Extraction
-
ocr_only- Text extraction only- Skips segmentation, directly extracts text
-
segment_only- Image segmentation only- Returns detected regions without text extraction
Edit agent_system.py to:
- Enable/disable SAM2 segmentation
- Enable/disable TrOCR handwriting recognition
- Configure model checkpoints
- Adjust agent routing rules
Customize PHI detection in agents/phi_filter_agent.py:
- Add custom regex patterns
- Configure NER model
- Adjust redaction format
Customize medication extraction in agents/drug_information_agent.py:
- Add medication name patterns
- Configure database priorities
- Adjust extraction rules
# Backend
cd backend
python main_agent_api.py
# In another terminal
curl -X POST http://localhost:8000/api/process-image \
-F "file=@test_prescription.jpg" \
-F "mode=full"from agent_system import get_agent_system
import asyncio
async def test():
# Initialize system
agent_system = await get_agent_system()
# Test PHI filtering
response = await agent_system.phi_filter_agent.process(
"Filter PHI",
{"text": "Patient: John Doe, DOB: 01/15/1980"}
)
print(response.data)
asyncio.run(test())- All PHI is detected and redacted before drug information queries
- No PHI is sent to external APIs (RxNorm, FDA, LLaMA)
- Redacted text uses placeholder format:
[TYPE_REDACTED]
- β Automatic PHI detection and redaction
- β No PHI logging in agent responses
- β Privacy-first design (PHI filtered before external API calls)
β οΈ Note: This is a demonstration system. For production HIPAA compliance, additional measures required:- Encrypted storage
- Access logging
- Audit trails
- BAA with cloud providers
- Drag & drop support
- Format support: JPEG, PNG
- Real-time processing feedback
- Agent Badge - Shows which agent processed the image
- Tools Badge - Lists tools used in pipeline
- Text Display - Original extracted text
- Redacted Text - PHI-filtered version
- PHI Summary - Detailed list of detected PHI entities
- Medications - Extracted drugs with dosages
- Drug Alternatives - Database results for each medication
- Toggle between original/segmented image view
- Copy text to clipboard
- Download full report with metadata
- Show/hide detailed metadata
- Region statistics display
Solution: Wait a few seconds after server start for initialization.
Solutions:
- Verify Azure Vision API credentials in
.env - Check image quality and resolution
- Ensure prescription is clearly visible
Solution: This is optional. System uses fallback segmentation. To enable:
cd backend/segment-anything-2
pip install -e .
cd ..
python download_sam2_checkpoint.pySolution: Optional for handwriting. To enable:
pip install "huggingface-hub>=0.24.0,<1.0"
pip install transformers --upgrade- Segmentation: 1-3 seconds (with fallback)
- SAM2 Segmentation: 5-10 seconds (if enabled)
- Azure Vision OCR: 2-5 seconds
- PHI Filtering: <1 second
- Drug Information: 1-3 seconds per medication
Total Pipeline: 5-15 seconds per image
- Use
ocr_onlymode if segmentation not needed - Disable SAM2 for faster processing (fallback is sufficient)
- Cache drug information results
- Process multiple images in batch mode
- Multi-language support
- Batch processing UI
- Drug interaction checker
- Dosage validation
- Prescription history tracking
- Export to PDF/JSON
- Advanced handwriting recognition
- Custom agent creation API
This project is for educational and demonstration purposes.
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Submit a pull request
For issues or questions, please open an issue on GitHub.
- Azure Vision API - Microsoft Cognitive Services
- SAM2 - Meta AI Research
- RxNorm - National Library of Medicine (NLM)
- openFDA - U.S. Food & Drug Administration
- HuggingFace - Transformers and Inference API
- FastAPI - Modern Python web framework
- React - Facebook Open Source