# Handwritten Marathi Hospital Form Extraction > Extract handwritten Marathi (मराठी) text from hospital forms using **Sarvam AI Vision** Document Intelligence. ![Python](https://img.shields.io/badge/Python-3.9+-blue) ![Flask](https://img.shields.io/badge/Flask-3.1-green) ![Sarvam AI](https://img.shields.io/badge/Sarvam_AI-Vision-orange) --- ## 🎯 Purpose This application evaluates how accurately **Sarvam Vision** reads handwritten Marathi text written in Devanagari script on hospital documents. It supports: - Handwritten Marathi hospital registration forms - Patient information forms - Handwritten medical notes and prescriptions - Scanned documents and mobile photographs - JPG, JPEG, PNG, PDF, BMP, and TIFF files ## 🏗️ Architecture ``` ┌─────────────────┐ ┌──────────────┐ ┌─────────────────────┐ │ Flask Frontend │────▶│ Flask API │────▶│ Sarvam AI Doc-AI │ │ (HTML/CSS/JS) │◀────│ (Python) │◀────│ Vision API │ └─────────────────┘ └──────┬───────┘ └─────────────────────┘ │ ┌──────┴───────┐ │ OpenCV │ │ Preprocessor│ └──────────────┘ ``` **API Endpoints Used:** | Endpoint | Purpose | |----------|---------| | `POST /doc-ai/v1/job/extract` | Schema-based key-value extraction | | `POST /doc-ai/v1/job/digitise` | Full OCR / raw transcription | | `GET /doc-ai/v1/job/{id}/status` | Poll job completion | | `GET /doc-ai/v1/job/{id}/results` | Fetch extraction results | ## 📁 Project Structure ``` handwritten_extraction/ ├── app.py # Flask application & routes ├── config.py # Configuration from .env ├── sarvam_client.py # Sarvam AI API client ├── extraction_schema.py # JSON schema & response builder ├── image_preprocessor.py # OpenCV preprocessing pipeline ├── requirements.txt # Python dependencies ├── sample_output.json # Sample extraction output (fictional) ├── .env.example # Environment template ├── .gitignore ├── README.md ├── templates/ │ └── index.html # Dashboard UI template └── static/ ├── css/ │ └── style.css # Dark theme stylesheet └── js/ └── app.js # Frontend logic ``` ## 🚀 Setup & Run ### 1. Prerequisites - Python 3.9 or higher - A Sarvam AI API key ([Sign up here](https://dashboard.sarvam.ai/)) ### 2. Clone & Install ```bash cd handwritten_extraction # Create virtual environment python -m venv venv # Activate it # Windows: venv\Scripts\activate # macOS/Linux: source venv/bin/activate # Install dependencies pip install -r requirements.txt ``` ### 3. Configure API Key ```bash # Copy the example env file copy .env.example .env # Windows # cp .env.example .env # macOS/Linux # Edit .env and set your API key: # SARVAM_API_KEY=your_actual_api_key_here ``` ### 4. Run the Application ```bash python app.py ``` Open your browser at: **http://localhost:5000** ## 🖥️ Dashboard Features | Feature | Description | |---------|-------------| | **Document Upload** | Drag & drop or browse. Supports JPG, PNG, PDF, TIFF, BMP | | **Image Preprocessing** | Toggle OpenCV enhancement (deskew, contrast, denoise, sharpen) | | **Extraction Method** | Choose Auto, Schema-based Extract, or Raw OCR Digitise | | **Extracted Fields** | Visual grid showing all parsed fields with Marathi text | | **JSON Output** | Syntax-highlighted JSON viewer with download | | **Raw Transcription** | Full Marathi text in Devanagari script | | **Accuracy Comparison** | Compare against reference JSON for field-level matching | | **Test History** | Track all extractions in the current session | | **Download** | Export JSON or plain text transcription | ## 📝 Extracted Fields The application extracts these fields when present: | Category | Fields | |----------|--------| | **Patient** | Name, Age, Gender, Address, Mobile Number | | **Hospital** | Hospital Name, Department, Doctor Name, Visit Date | | **Medical** | Symptoms, Medical History, Diagnosis, Medicines & Dosage, Notes | | **Meta** | Document Type, Raw Transcription, Unreadable Fields, Warnings | ## 🔧 Image Preprocessing Optional OpenCV pipeline (toggle on/off to compare quality): 1. **Resize** — Scale down oversized images (>4096px) 2. **Auto-Rotate** — Correct skew using Hough line detection 3. **Noise Reduction** — Non-local means denoising (gentle) 4. **Contrast Enhancement** — CLAHE on luminance channel 5. **Sharpening** — Unsharp mask for clearer strokes > ⚠️ Preprocessing uses conservative parameters to preserve handwriting strokes. ## 🔒 Security - API key stored in `.env` (never exposed to frontend) - `.env` excluded via `.gitignore` - Uploaded files processed in-memory (not saved to disk by default) - No real patient data included — sample uses fictional data - API errors handled without leaking keys ## 📊 Sample Output See [`sample_output.json`](sample_output.json) for a complete example using fictional Marathi hospital data. Key structure: ```json { "document_type": "hospital_registration_form", "language": "mr", "patient_details": { "patient_name": "राम विठ्ठल शिंदे", ... }, "hospital_details": { "hospital_name": "जिल्हा रुग्णालय", ... }, "medical_details": { "symptoms": "ताप, डोकेदुखी", ... }, "raw_transcription": "...", "unreadable_fields": [], "validation_warnings": [] } ``` ## ⚙️ Configuration All settings are in `.env`: | Variable | Default | Description | |----------|---------|-------------| | `SARVAM_API_KEY` | — | Your Sarvam AI API key (required) | | `FLASK_PORT` | `5000` | Server port | | `FLASK_DEBUG` | `True` | Debug mode | | `MAX_CONTENT_LENGTH_MB` | `16` | Max upload size in MB | | `SARVAM_JOB_POLL_INTERVAL` | `3` | Seconds between status polls | | `SARVAM_JOB_MAX_WAIT` | `120` | Max seconds to wait for job | ## 🧪 Testing 1. Upload a handwritten Marathi document 2. Optionally enable preprocessing 3. Click **Extract Marathi Text** 4. Review the extracted fields, JSON, and raw transcription 5. Paste a reference JSON in the **Compare** tab for accuracy measurement 6. Check **Test History** for all session results > Accuracy percentages are calculated only from actual test comparisons — never fabricated. ## 📜 License This project is for evaluation and testing purposes. Do not use real patient data without appropriate authorization and data protection measures. --- **Built with ❤️ for Marathi (मराठी) language technology**