handwritten ocr
This commit is contained in:
+37
@@ -0,0 +1,37 @@
|
|||||||
|
# Environment
|
||||||
|
.env
|
||||||
|
|
||||||
|
# Python
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
*.so
|
||||||
|
*.egg-info/
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
*.egg
|
||||||
|
|
||||||
|
# Virtual Environment
|
||||||
|
venv/
|
||||||
|
.venv/
|
||||||
|
env/
|
||||||
|
|
||||||
|
# Uploads (patient data)
|
||||||
|
uploads/
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# Test results and persistent history
|
||||||
|
test_results/
|
||||||
|
data/
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
# Handwritten Marathi Hospital Form Extraction
|
||||||
|
|
||||||
|
> Extract handwritten Marathi (मराठी) text from hospital forms using **Sarvam AI Vision** Document Intelligence.
|
||||||
|
|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 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**
|
||||||
@@ -0,0 +1,743 @@
|
|||||||
|
"""
|
||||||
|
Flask application — Handwritten Marathi Hospital Form Extraction
|
||||||
|
using Sarvam AI Vision Document Intelligence API.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
import logging
|
||||||
|
import base64
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from flask import (
|
||||||
|
Flask, render_template, request, jsonify,
|
||||||
|
send_from_directory, redirect, url_for, send_file, Response
|
||||||
|
)
|
||||||
|
from werkzeug.utils import secure_filename
|
||||||
|
|
||||||
|
from config import Config
|
||||||
|
from sarvam_client import SarvamClient, SarvamAPIError
|
||||||
|
from gemini_client import GeminiClient, GeminiAPIError
|
||||||
|
from image_preprocessor import ImagePreprocessor
|
||||||
|
from extraction_schema import EMPTY_RESPONSE_TEMPLATE
|
||||||
|
from history_manager import HistoryManager
|
||||||
|
import concurrent.futures
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
# Logging
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s"
|
||||||
|
)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
# Flask App
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.secret_key = Config.SECRET_KEY
|
||||||
|
app.config["MAX_CONTENT_LENGTH"] = Config.MAX_CONTENT_LENGTH
|
||||||
|
|
||||||
|
# Ensure upload directory exists
|
||||||
|
os.makedirs(Config.UPLOAD_FOLDER, exist_ok=True)
|
||||||
|
|
||||||
|
# Persistent test history is handled by HistoryManager (stored in data/test_history.json)
|
||||||
|
|
||||||
|
|
||||||
|
def allowed_file(filename: str) -> bool:
|
||||||
|
"""Check if the file extension is allowed."""
|
||||||
|
return (
|
||||||
|
"." in filename
|
||||||
|
and filename.rsplit(".", 1)[1].lower() in Config.ALLOWED_EXTENSIONS
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_mime_type(filename: str) -> str:
|
||||||
|
"""Get MIME type from filename extension."""
|
||||||
|
ext = filename.rsplit(".", 1)[1].lower() if "." in filename else ""
|
||||||
|
mime_map = {
|
||||||
|
"jpg": "image/jpeg",
|
||||||
|
"jpeg": "image/jpeg",
|
||||||
|
"png": "image/png",
|
||||||
|
"bmp": "image/bmp",
|
||||||
|
"tiff": "image/tiff",
|
||||||
|
"tif": "image/tiff",
|
||||||
|
"pdf": "application/pdf",
|
||||||
|
}
|
||||||
|
return mime_map.get(ext, "application/octet-stream")
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
# Model Runners
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _run_sarvam(extraction_bytes, filename, mime_type, api_lang, method="auto"):
|
||||||
|
"""Execute document extraction using Sarvam Vision API."""
|
||||||
|
client = SarvamClient()
|
||||||
|
if method == "extract":
|
||||||
|
return client.extract(extraction_bytes, filename, mime_type, language=api_lang)
|
||||||
|
elif method == "digitise":
|
||||||
|
return client.digitise(extraction_bytes, filename, mime_type, language=api_lang)
|
||||||
|
else:
|
||||||
|
return client.extract_with_fallback(extraction_bytes, filename, mime_type, language=api_lang)
|
||||||
|
|
||||||
|
|
||||||
|
def _run_gemini(extraction_bytes, filename, mime_type, api_lang, model_name=None):
|
||||||
|
"""Execute document extraction using Google Gemini Vision API."""
|
||||||
|
client = GeminiClient(model=model_name)
|
||||||
|
return client.extract(extraction_bytes, filename, mime_type, language=api_lang)
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
# Routes
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@app.route("/")
|
||||||
|
def index():
|
||||||
|
"""Render the main dashboard."""
|
||||||
|
config_errors = Config.validate()
|
||||||
|
models_status = Config.get_configured_models()
|
||||||
|
return render_template(
|
||||||
|
"index.html",
|
||||||
|
config_errors=config_errors,
|
||||||
|
models_status=models_status,
|
||||||
|
gemini_model=Config.get_gemini_model()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/models", methods=["GET"])
|
||||||
|
def api_models():
|
||||||
|
"""Return available and configured AI Vision models."""
|
||||||
|
configured = Config.get_configured_models()
|
||||||
|
return jsonify({
|
||||||
|
"configured": configured,
|
||||||
|
"default_gemini_model": Config.get_gemini_model(),
|
||||||
|
"available_gemini_models": [
|
||||||
|
"gemini-3.8-flash",
|
||||||
|
"gemini-flash-latest",
|
||||||
|
"gemini-3.6-flash",
|
||||||
|
"gemini-3.5-flash",
|
||||||
|
"gemini-2.5-flash"
|
||||||
|
]
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/extract", methods=["POST"])
|
||||||
|
def api_extract():
|
||||||
|
"""
|
||||||
|
Handle document upload and extraction.
|
||||||
|
Accepts multipart form data with:
|
||||||
|
- file: The document image/PDF
|
||||||
|
- preprocess: "true" or "false"
|
||||||
|
- method: "extract", "digitise", or "auto" (default: "auto")
|
||||||
|
"""
|
||||||
|
start_time = time.time()
|
||||||
|
|
||||||
|
# ── Validate file ──
|
||||||
|
if "file" not in request.files:
|
||||||
|
return jsonify({"error": "No file uploaded."}), 400
|
||||||
|
|
||||||
|
file = request.files["file"]
|
||||||
|
if file.filename == "" or not file.filename:
|
||||||
|
return jsonify({"error": "No file selected."}), 400
|
||||||
|
|
||||||
|
if not allowed_file(file.filename):
|
||||||
|
return jsonify({
|
||||||
|
"error": f"File type not allowed. Supported: {', '.join(Config.ALLOWED_EXTENSIONS)}"
|
||||||
|
}), 400
|
||||||
|
|
||||||
|
filename = secure_filename(file.filename)
|
||||||
|
file_bytes = file.read()
|
||||||
|
mime_type = get_mime_type(filename)
|
||||||
|
|
||||||
|
# ── Options ──
|
||||||
|
do_preprocess = request.form.get("preprocess", "false").lower() == "true"
|
||||||
|
method = request.form.get("method", "auto").lower()
|
||||||
|
selected_language = request.form.get("language", "auto")
|
||||||
|
model_choice = request.form.get("model", "auto").lower()
|
||||||
|
gemini_model_custom = request.form.get("gemini_model", "").strip() or Config.get_gemini_model()
|
||||||
|
|
||||||
|
api_lang = None
|
||||||
|
if selected_language in ("mr-IN", "mr", "marathi"):
|
||||||
|
api_lang = "mr-IN"
|
||||||
|
elif selected_language in ("en-IN", "en", "english"):
|
||||||
|
api_lang = "en-IN"
|
||||||
|
|
||||||
|
# ── Preprocessing ──
|
||||||
|
preprocessing_info = None
|
||||||
|
original_b64 = None
|
||||||
|
processed_b64 = None
|
||||||
|
|
||||||
|
if mime_type.startswith("image/"):
|
||||||
|
# Always provide original preview
|
||||||
|
original_b64 = base64.b64encode(file_bytes).decode("utf-8")
|
||||||
|
|
||||||
|
if do_preprocess:
|
||||||
|
try:
|
||||||
|
processed_bytes, preprocessing_info = ImagePreprocessor.preprocess(file_bytes)
|
||||||
|
processed_b64 = base64.b64encode(processed_bytes).decode("utf-8")
|
||||||
|
# Use processed image for extraction
|
||||||
|
extraction_bytes = processed_bytes
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Preprocessing failed, using original: {e}")
|
||||||
|
preprocessing_info = {"error": str(e), "steps_applied": []}
|
||||||
|
extraction_bytes = file_bytes
|
||||||
|
else:
|
||||||
|
extraction_bytes = file_bytes
|
||||||
|
else:
|
||||||
|
# PDF or other — skip preprocessing
|
||||||
|
extraction_bytes = file_bytes
|
||||||
|
|
||||||
|
ext = filename.rsplit(".", 1)[1].lower() if "." in filename else "jpg"
|
||||||
|
|
||||||
|
# ── MODE 1: Dual-Model Comparison Benchmark (Run Both Parallel) ──
|
||||||
|
if model_choice == "compare":
|
||||||
|
logger.info(f"Initiating dual-model comparison benchmark: Gemini ({gemini_model_custom}) vs Sarvam DocVision AI")
|
||||||
|
gemini_res = None
|
||||||
|
sarvam_res = None
|
||||||
|
gemini_err = None
|
||||||
|
sarvam_err = None
|
||||||
|
|
||||||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
|
||||||
|
fut_gemini = executor.submit(_run_gemini, extraction_bytes, filename, mime_type, api_lang, gemini_model_custom)
|
||||||
|
fut_sarvam = executor.submit(_run_sarvam, extraction_bytes, filename, mime_type, api_lang, method)
|
||||||
|
|
||||||
|
try:
|
||||||
|
gemini_res = fut_gemini.result()
|
||||||
|
except Exception as e:
|
||||||
|
gemini_err = str(e)
|
||||||
|
logger.warning(f"Gemini comparison branch error: {e}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
sarvam_res = fut_sarvam.result()
|
||||||
|
except Exception as e:
|
||||||
|
sarvam_err = str(e)
|
||||||
|
logger.warning(f"Sarvam comparison branch error: {e}")
|
||||||
|
|
||||||
|
# If both failed
|
||||||
|
if not gemini_res and not sarvam_res:
|
||||||
|
return jsonify({
|
||||||
|
"error": f"Both vision models failed to extract. Gemini: {gemini_err} | Sarvam: {sarvam_err}"
|
||||||
|
}), 500
|
||||||
|
|
||||||
|
total_time = round(time.time() - start_time, 2)
|
||||||
|
gemini_hist_id = None
|
||||||
|
sarvam_hist_id = None
|
||||||
|
|
||||||
|
# Store Gemini run in history if successful
|
||||||
|
if gemini_res:
|
||||||
|
gem_entry = {
|
||||||
|
"id": str(uuid.uuid4())[:8],
|
||||||
|
"filename": filename,
|
||||||
|
"timestamp": datetime.now().isoformat(),
|
||||||
|
"model": gemini_res.get("_meta", {}).get("model", f"Gemini ({gemini_model_custom})"),
|
||||||
|
"method": "gemini_vision",
|
||||||
|
"status": "success",
|
||||||
|
"api_response_time": gemini_res.get("_meta", {}).get("api_response_time_seconds"),
|
||||||
|
"total_time": total_time,
|
||||||
|
"fields_extracted": _count_extracted_fields(gemini_res),
|
||||||
|
"fields_missing": len(gemini_res.get("unreadable_fields", [])),
|
||||||
|
"raw_transcription": gemini_res.get("raw_transcription", ""),
|
||||||
|
"result": gemini_res,
|
||||||
|
"preprocessing": preprocessing_info
|
||||||
|
}
|
||||||
|
saved_gem = HistoryManager.add_entry(
|
||||||
|
gem_entry,
|
||||||
|
original_bytes=file_bytes if mime_type.startswith("image/") else None,
|
||||||
|
file_ext=ext
|
||||||
|
)
|
||||||
|
gemini_hist_id = saved_gem["id"]
|
||||||
|
|
||||||
|
# Store Sarvam run in history if successful
|
||||||
|
if sarvam_res:
|
||||||
|
sar_entry = {
|
||||||
|
"id": str(uuid.uuid4())[:8],
|
||||||
|
"filename": filename,
|
||||||
|
"timestamp": datetime.now().isoformat(),
|
||||||
|
"model": sarvam_res.get("_meta", {}).get("model", "DocVision AI"),
|
||||||
|
"method": sarvam_res.get("_meta", {}).get("method", method),
|
||||||
|
"status": "success",
|
||||||
|
"api_response_time": sarvam_res.get("_meta", {}).get("api_response_time_seconds"),
|
||||||
|
"total_time": total_time,
|
||||||
|
"fields_extracted": _count_extracted_fields(sarvam_res),
|
||||||
|
"fields_missing": len(sarvam_res.get("unreadable_fields", [])),
|
||||||
|
"raw_transcription": sarvam_res.get("raw_transcription", ""),
|
||||||
|
"result": sarvam_res,
|
||||||
|
"preprocessing": preprocessing_info
|
||||||
|
}
|
||||||
|
saved_sar = HistoryManager.add_entry(
|
||||||
|
sar_entry,
|
||||||
|
original_bytes=file_bytes if mime_type.startswith("image/") else None,
|
||||||
|
file_ext=ext
|
||||||
|
)
|
||||||
|
sarvam_hist_id = saved_sar["id"]
|
||||||
|
|
||||||
|
# Perform side-by-side comparison breakdown if both succeeded
|
||||||
|
comparison_data = None
|
||||||
|
if gemini_res and sarvam_res:
|
||||||
|
comparison_data = _compare_models(
|
||||||
|
gemini_res,
|
||||||
|
sarvam_res,
|
||||||
|
label_a=f"Gemini ({gemini_model_custom})",
|
||||||
|
label_b="DocVision AI (Sarvam)"
|
||||||
|
)
|
||||||
|
|
||||||
|
primary_result = gemini_res if gemini_res else sarvam_res
|
||||||
|
|
||||||
|
return jsonify({
|
||||||
|
"success": True,
|
||||||
|
"is_comparison": True,
|
||||||
|
"filename": filename,
|
||||||
|
"extraction": primary_result,
|
||||||
|
"gemini_result": gemini_res,
|
||||||
|
"sarvam_result": sarvam_res,
|
||||||
|
"gemini_error": gemini_err,
|
||||||
|
"sarvam_error": sarvam_err,
|
||||||
|
"comparison": comparison_data,
|
||||||
|
"gemini_history_id": gemini_hist_id,
|
||||||
|
"sarvam_history_id": sarvam_hist_id,
|
||||||
|
"history_id": gemini_hist_id or sarvam_hist_id,
|
||||||
|
"preprocessing": preprocessing_info,
|
||||||
|
"original_image_b64": original_b64,
|
||||||
|
"processed_image_b64": processed_b64,
|
||||||
|
"total_time_seconds": total_time,
|
||||||
|
"timestamp": datetime.now().isoformat()
|
||||||
|
})
|
||||||
|
|
||||||
|
# ── MODE 2: Single-Model Extraction ──
|
||||||
|
target_model = model_choice
|
||||||
|
configured = Config.get_configured_models()
|
||||||
|
|
||||||
|
if target_model == "auto":
|
||||||
|
if configured["gemini"] and not configured["sarvam"]:
|
||||||
|
target_model = "gemini"
|
||||||
|
elif configured["sarvam"] and not configured["gemini"]:
|
||||||
|
target_model = "sarvam"
|
||||||
|
elif configured["gemini"] and configured["sarvam"]:
|
||||||
|
target_model = "gemini"
|
||||||
|
else:
|
||||||
|
return jsonify({
|
||||||
|
"error": "No Vision API key configured. Please set SARVAM_API_KEY or GEMINI_API_KEY in your .env file."
|
||||||
|
}), 400
|
||||||
|
|
||||||
|
try:
|
||||||
|
if target_model == "gemini":
|
||||||
|
result = _run_gemini(extraction_bytes, filename, mime_type, api_lang, gemini_model_custom)
|
||||||
|
else:
|
||||||
|
result = _run_sarvam(extraction_bytes, filename, mime_type, api_lang, method)
|
||||||
|
|
||||||
|
except (GeminiAPIError, SarvamAPIError) as e:
|
||||||
|
logger.error(f"Vision API error ({target_model}): {e}")
|
||||||
|
model_name_tag = f"Gemini ({gemini_model_custom})" if target_model == "gemini" else "DocVision AI"
|
||||||
|
fail_entry = {
|
||||||
|
"id": str(uuid.uuid4())[:8],
|
||||||
|
"filename": filename,
|
||||||
|
"timestamp": datetime.now().isoformat(),
|
||||||
|
"model": model_name_tag,
|
||||||
|
"method": method,
|
||||||
|
"status": "failed",
|
||||||
|
"error": str(e),
|
||||||
|
"api_response_time": None,
|
||||||
|
"total_time": round(time.time() - start_time, 2),
|
||||||
|
"fields_extracted": 0,
|
||||||
|
"fields_missing": 0,
|
||||||
|
"raw_transcription": "",
|
||||||
|
"result": None
|
||||||
|
}
|
||||||
|
HistoryManager.add_entry(fail_entry)
|
||||||
|
return jsonify({
|
||||||
|
"error": str(e),
|
||||||
|
"status_code": getattr(e, "status_code", 500),
|
||||||
|
"model": model_name_tag
|
||||||
|
}), getattr(e, "status_code", 500) or 500
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.exception(f"Unexpected error during extraction: {e}")
|
||||||
|
fail_entry = {
|
||||||
|
"id": str(uuid.uuid4())[:8],
|
||||||
|
"filename": filename,
|
||||||
|
"timestamp": datetime.now().isoformat(),
|
||||||
|
"model": "DocVision AI" if target_model != "gemini" else f"Gemini ({gemini_model_custom})",
|
||||||
|
"method": method,
|
||||||
|
"status": "failed",
|
||||||
|
"error": str(e),
|
||||||
|
"api_response_time": None,
|
||||||
|
"total_time": round(time.time() - start_time, 2),
|
||||||
|
"fields_extracted": 0,
|
||||||
|
"fields_missing": 0,
|
||||||
|
"raw_transcription": "",
|
||||||
|
"result": None
|
||||||
|
}
|
||||||
|
HistoryManager.add_entry(fail_entry)
|
||||||
|
return jsonify({"error": f"Internal error: {str(e)}"}), 500
|
||||||
|
|
||||||
|
total_time = round(time.time() - start_time, 2)
|
||||||
|
|
||||||
|
# ── Build response ──
|
||||||
|
response = {
|
||||||
|
"success": True,
|
||||||
|
"is_comparison": False,
|
||||||
|
"filename": filename,
|
||||||
|
"extraction": result,
|
||||||
|
"preprocessing": preprocessing_info,
|
||||||
|
"original_image_b64": original_b64,
|
||||||
|
"processed_image_b64": processed_b64,
|
||||||
|
"total_time_seconds": total_time,
|
||||||
|
"timestamp": datetime.now().isoformat()
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Store test result in persistent history ──
|
||||||
|
test_entry = {
|
||||||
|
"id": str(uuid.uuid4())[:8],
|
||||||
|
"filename": filename,
|
||||||
|
"timestamp": response["timestamp"],
|
||||||
|
"model": result.get("_meta", {}).get("model", "DocVision AI"),
|
||||||
|
"method": result.get("_meta", {}).get("method", method),
|
||||||
|
"status": "success",
|
||||||
|
"api_response_time": result.get("_meta", {}).get("api_response_time_seconds"),
|
||||||
|
"total_time": total_time,
|
||||||
|
"fields_extracted": _count_extracted_fields(result),
|
||||||
|
"fields_missing": len(result.get("unreadable_fields", [])),
|
||||||
|
"raw_transcription": result.get("raw_transcription", ""),
|
||||||
|
"result": result,
|
||||||
|
"preprocessing": preprocessing_info
|
||||||
|
}
|
||||||
|
|
||||||
|
saved_entry = HistoryManager.add_entry(
|
||||||
|
test_entry,
|
||||||
|
original_bytes=file_bytes if mime_type.startswith("image/") else None,
|
||||||
|
processed_bytes=processed_bytes if (do_preprocess and 'processed_bytes' in locals()) else None,
|
||||||
|
file_ext=ext
|
||||||
|
)
|
||||||
|
response["history_id"] = saved_entry["id"]
|
||||||
|
|
||||||
|
return jsonify(response)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/test-results", methods=["GET"])
|
||||||
|
def api_test_results():
|
||||||
|
"""Return all persistent test results."""
|
||||||
|
return jsonify({"results": HistoryManager.get_all()})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/test-results/<result_id>", methods=["GET"])
|
||||||
|
def api_get_test_result(result_id):
|
||||||
|
"""Return full details for a specific test result."""
|
||||||
|
result = HistoryManager.get_by_id(result_id)
|
||||||
|
if not result:
|
||||||
|
return jsonify({"error": "Test result not found"}), 404
|
||||||
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/test-results/<result_id>/image/<image_type>", methods=["GET"])
|
||||||
|
def api_get_test_image(result_id, image_type):
|
||||||
|
"""Serve the saved image (original or processed) for a history test."""
|
||||||
|
if image_type not in ("original", "processed"):
|
||||||
|
return jsonify({"error": "Invalid image type"}), 400
|
||||||
|
path = HistoryManager.get_image_path(result_id, image_type)
|
||||||
|
if not path or not os.path.exists(path):
|
||||||
|
return jsonify({"error": "Image not found"}), 404
|
||||||
|
return send_file(path)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/test-results/<result_id>", methods=["DELETE"])
|
||||||
|
def api_delete_test_result(result_id):
|
||||||
|
"""Delete a specific test result from persistent history."""
|
||||||
|
success = HistoryManager.delete_entry(result_id)
|
||||||
|
return jsonify({"success": success})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/test-results/clear", methods=["POST", "DELETE"])
|
||||||
|
def api_clear_test_results():
|
||||||
|
"""Clear all test results from persistent history."""
|
||||||
|
HistoryManager.clear_all()
|
||||||
|
return jsonify({"success": True, "message": "All history cleared."})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/test-results/export/csv", methods=["GET"])
|
||||||
|
def api_export_history_csv():
|
||||||
|
"""Export all test history summary as a downloadable CSV."""
|
||||||
|
csv_data = HistoryManager.export_csv()
|
||||||
|
return Response(
|
||||||
|
csv_data,
|
||||||
|
mimetype="text/csv",
|
||||||
|
headers={"Content-Disposition": f"attachment;filename=marathi_ocr_history_{int(time.time())}.csv"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/test-results/export/json", methods=["GET"])
|
||||||
|
def api_export_history_json():
|
||||||
|
"""Export all test history and full extractions as downloadable JSON."""
|
||||||
|
records = HistoryManager.get_all()
|
||||||
|
return Response(
|
||||||
|
json.dumps(records, ensure_ascii=False, indent=2),
|
||||||
|
mimetype="application/json",
|
||||||
|
headers={"Content-Disposition": f"attachment;filename=marathi_ocr_history_{int(time.time())}.json"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/compare", methods=["POST"])
|
||||||
|
def api_compare():
|
||||||
|
"""
|
||||||
|
Compare extraction result against a manually provided reference JSON.
|
||||||
|
Calculates field-level match statistics.
|
||||||
|
"""
|
||||||
|
data = request.get_json()
|
||||||
|
if not data:
|
||||||
|
return jsonify({"error": "No JSON body provided."}), 400
|
||||||
|
|
||||||
|
extracted = data.get("extracted", {})
|
||||||
|
reference = data.get("reference", {})
|
||||||
|
|
||||||
|
comparison = _compare_results(extracted, reference)
|
||||||
|
return jsonify(comparison)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/compare-models", methods=["POST"])
|
||||||
|
def api_compare_models():
|
||||||
|
"""
|
||||||
|
Compare two specific extraction runs (e.g., Gemini vs Sarvam) side-by-side.
|
||||||
|
Accepts JSON body with:
|
||||||
|
- id_a: History ID of first run (e.g. Gemini)
|
||||||
|
- id_b: History ID of second run (e.g. Sarvam)
|
||||||
|
or
|
||||||
|
- result_a: Direct result dict
|
||||||
|
- result_b: Direct result dict
|
||||||
|
"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
result_a = data.get("result_a")
|
||||||
|
result_b = data.get("result_b")
|
||||||
|
label_a = data.get("label_a", "Model A")
|
||||||
|
label_b = data.get("label_b", "Model B")
|
||||||
|
|
||||||
|
if not result_a and data.get("id_a"):
|
||||||
|
entry_a = HistoryManager.get_by_id(data["id_a"])
|
||||||
|
if entry_a:
|
||||||
|
result_a = entry_a.get("result")
|
||||||
|
label_a = entry_a.get("model", "Model A")
|
||||||
|
|
||||||
|
if not result_b and data.get("id_b"):
|
||||||
|
entry_b = HistoryManager.get_by_id(data["id_b"])
|
||||||
|
if entry_b:
|
||||||
|
result_b = entry_b.get("result")
|
||||||
|
label_b = entry_b.get("model", "Model B")
|
||||||
|
|
||||||
|
if not result_a or not result_b:
|
||||||
|
return jsonify({"error": "Could not locate both results to compare."}), 400
|
||||||
|
|
||||||
|
comparison = _compare_models(result_a, result_b, label_a=label_a, label_b=label_b)
|
||||||
|
return jsonify(comparison)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/health", methods=["GET"])
|
||||||
|
def api_health():
|
||||||
|
"""Health check endpoint."""
|
||||||
|
config_errors = Config.validate()
|
||||||
|
configured_models = Config.get_configured_models()
|
||||||
|
return jsonify({
|
||||||
|
"status": "ok" if not config_errors else "warning",
|
||||||
|
"config_errors": config_errors,
|
||||||
|
"configured_models": configured_models,
|
||||||
|
"language": Config.DOCUMENT_LANGUAGE,
|
||||||
|
"content_type": Config.CONTENT_TYPE
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
# Helper Functions
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _count_extracted_fields(result: dict) -> int:
|
||||||
|
"""Count non-null fields in the extraction result."""
|
||||||
|
count = 0
|
||||||
|
sections = (
|
||||||
|
"patient_details", "hospital_details", "address_details",
|
||||||
|
"billing_details", "representative_details", "medical_details"
|
||||||
|
)
|
||||||
|
for section in sections:
|
||||||
|
section_data = result.get(section, {})
|
||||||
|
if isinstance(section_data, dict):
|
||||||
|
for key, val in section_data.items():
|
||||||
|
if val is not None and val != "" and val != []:
|
||||||
|
count += 1
|
||||||
|
if result.get("document_type"):
|
||||||
|
count += 1
|
||||||
|
if result.get("raw_transcription"):
|
||||||
|
count += 1
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
def _compare_models(result_a: dict, result_b: dict, label_a: str = "Gemini", label_b: str = "Sarvam") -> dict:
|
||||||
|
"""
|
||||||
|
Compare two model extraction outputs field-by-field.
|
||||||
|
Classifies each field into MATCH, DIFFERENT, ONLY_IN_A, ONLY_IN_B, or BOTH_EMPTY.
|
||||||
|
"""
|
||||||
|
sections = [
|
||||||
|
("hospital_details", "Hospital & Registration"),
|
||||||
|
("patient_details", "Patient Identification"),
|
||||||
|
("address_details", "Address Information"),
|
||||||
|
("billing_details", "Billing & Financial"),
|
||||||
|
("representative_details", "Representative Details"),
|
||||||
|
("medical_details", "Clinical & Medical")
|
||||||
|
]
|
||||||
|
|
||||||
|
repaired_a = {r["field"]: r for r in result_a.get("repaired_fields", [])}
|
||||||
|
repaired_b = {r["field"]: r for r in result_b.get("repaired_fields", [])}
|
||||||
|
|
||||||
|
matches = 0
|
||||||
|
mismatches = 0
|
||||||
|
only_a = 0
|
||||||
|
only_b = 0
|
||||||
|
both_empty = 0
|
||||||
|
field_rows = []
|
||||||
|
|
||||||
|
for sec_key, sec_title in sections:
|
||||||
|
sec_a = result_a.get(sec_key, {}) or {}
|
||||||
|
sec_b = result_b.get(sec_key, {}) or {}
|
||||||
|
all_keys = sorted(set(list(sec_a.keys()) + list(sec_b.keys())))
|
||||||
|
|
||||||
|
for field in all_keys:
|
||||||
|
val_a = sec_a.get(field)
|
||||||
|
val_b = sec_b.get(field)
|
||||||
|
|
||||||
|
is_empty_a = val_a is None or val_a == "" or val_a == []
|
||||||
|
is_empty_b = val_b is None or val_b == "" or val_b == []
|
||||||
|
|
||||||
|
if is_empty_a and is_empty_b:
|
||||||
|
both_empty += 1
|
||||||
|
status = "BOTH_EMPTY"
|
||||||
|
elif is_empty_a and not is_empty_b:
|
||||||
|
only_b += 1
|
||||||
|
status = "ONLY_IN_B"
|
||||||
|
elif not is_empty_a and is_empty_b:
|
||||||
|
only_a += 1
|
||||||
|
status = "ONLY_IN_A"
|
||||||
|
else:
|
||||||
|
norm_a = str(val_a).strip().lower()
|
||||||
|
norm_b = str(val_b).strip().lower()
|
||||||
|
if norm_a == norm_b:
|
||||||
|
matches += 1
|
||||||
|
status = "MATCH"
|
||||||
|
else:
|
||||||
|
mismatches += 1
|
||||||
|
status = "DIFFERENT"
|
||||||
|
|
||||||
|
field_rows.append({
|
||||||
|
"section": sec_key,
|
||||||
|
"section_title": sec_title,
|
||||||
|
"field": field,
|
||||||
|
"value_a": val_a,
|
||||||
|
"value_b": val_b,
|
||||||
|
"status": status,
|
||||||
|
"repaired_a": field in repaired_a,
|
||||||
|
"repaired_b": field in repaired_b,
|
||||||
|
"note_a": repaired_a.get(field, {}).get("note"),
|
||||||
|
"note_b": repaired_b.get(field, {}).get("note")
|
||||||
|
})
|
||||||
|
|
||||||
|
active_fields = matches + mismatches + only_a + only_b
|
||||||
|
agreement_pct = round((matches / (matches + mismatches) * 100), 1) if (matches + mismatches) > 0 else 0
|
||||||
|
overall_match_pct = round((matches / active_fields * 100), 1) if active_fields > 0 else 0
|
||||||
|
|
||||||
|
return {
|
||||||
|
"model_a": label_a,
|
||||||
|
"model_b": label_b,
|
||||||
|
"time_a_seconds": result_a.get("_meta", {}).get("api_response_time_seconds"),
|
||||||
|
"time_b_seconds": result_b.get("_meta", {}).get("api_response_time_seconds"),
|
||||||
|
"fields_a_count": _count_extracted_fields(result_a),
|
||||||
|
"fields_b_count": _count_extracted_fields(result_b),
|
||||||
|
"repairs_a_count": len(result_a.get("repaired_fields", [])),
|
||||||
|
"repairs_b_count": len(result_b.get("repaired_fields", [])),
|
||||||
|
"matches": matches,
|
||||||
|
"mismatches": mismatches,
|
||||||
|
"only_a": only_a,
|
||||||
|
"only_b": only_b,
|
||||||
|
"both_empty": both_empty,
|
||||||
|
"active_fields": active_fields,
|
||||||
|
"agreement_percent": agreement_pct,
|
||||||
|
"overall_match_percent": overall_match_pct,
|
||||||
|
"field_rows": field_rows
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _compare_results(extracted: dict, reference: dict) -> dict:
|
||||||
|
"""
|
||||||
|
Compare extracted fields against reference JSON.
|
||||||
|
Dynamically compares all fields present across all sections.
|
||||||
|
Returns per-field match results and overall statistics.
|
||||||
|
"""
|
||||||
|
sections = [
|
||||||
|
"hospital_details", "patient_details", "address_details",
|
||||||
|
"billing_details", "representative_details", "medical_details"
|
||||||
|
]
|
||||||
|
matches = 0
|
||||||
|
mismatches = 0
|
||||||
|
field_results = []
|
||||||
|
|
||||||
|
for section in sections:
|
||||||
|
ext_sec = extracted.get(section, {}) or {}
|
||||||
|
ref_sec = reference.get(section, {}) or {}
|
||||||
|
all_keys = sorted(set(list(ext_sec.keys()) + list(ref_sec.keys())))
|
||||||
|
|
||||||
|
for field in all_keys:
|
||||||
|
ext_val = ext_sec.get(field)
|
||||||
|
ref_val = ref_sec.get(field)
|
||||||
|
|
||||||
|
# Skip if both are null or empty
|
||||||
|
if (ext_val is None or ext_val == "") and (ref_val is None or ref_val == ""):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Normalize strings for comparison (whitespace & casing)
|
||||||
|
ext_norm = (ext_val or "").strip().lower() if isinstance(ext_val, str) else ext_val
|
||||||
|
ref_norm = (ref_val or "").strip().lower() if isinstance(ref_val, str) else ref_val
|
||||||
|
|
||||||
|
is_match = ext_norm == ref_norm
|
||||||
|
if is_match:
|
||||||
|
matches += 1
|
||||||
|
else:
|
||||||
|
mismatches += 1
|
||||||
|
|
||||||
|
field_results.append({
|
||||||
|
"section": section,
|
||||||
|
"field": field,
|
||||||
|
"extracted": ext_val,
|
||||||
|
"reference": ref_val,
|
||||||
|
"match": is_match
|
||||||
|
})
|
||||||
|
|
||||||
|
total = matches + mismatches
|
||||||
|
accuracy = round((matches / total * 100), 1) if total > 0 else 0
|
||||||
|
|
||||||
|
return {
|
||||||
|
"total_fields": total,
|
||||||
|
"matches": matches,
|
||||||
|
"mismatches": mismatches,
|
||||||
|
"accuracy_percent": accuracy,
|
||||||
|
"field_results": field_results,
|
||||||
|
"note": "Accuracy is calculated from field-level value matching against reference values."
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
# Main
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
logger.info("=" * 60)
|
||||||
|
logger.info("Handwritten Marathi Hospital Form Extraction")
|
||||||
|
logger.info("Powered by DocVision AI")
|
||||||
|
logger.info("=" * 60)
|
||||||
|
|
||||||
|
errors = Config.validate()
|
||||||
|
if errors:
|
||||||
|
for err in errors:
|
||||||
|
logger.warning(f"⚠ {err}")
|
||||||
|
|
||||||
|
app.run(
|
||||||
|
host="0.0.0.0",
|
||||||
|
port=Config.PORT,
|
||||||
|
debug=Config.DEBUG
|
||||||
|
)
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"""
|
||||||
|
Configuration module for the Handwritten Marathi Extraction Application.
|
||||||
|
Loads settings from environment variables and provides defaults.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
# Load environment variables from .env file
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
"""Application configuration loaded from environment variables."""
|
||||||
|
|
||||||
|
# Flask
|
||||||
|
SECRET_KEY = os.getenv("FLASK_SECRET_KEY", "dev-secret-key-change-in-production")
|
||||||
|
DEBUG = os.getenv("FLASK_DEBUG", "True").lower() in ("true", "1", "yes")
|
||||||
|
PORT = int(os.getenv("FLASK_PORT", 5000))
|
||||||
|
|
||||||
|
# Upload
|
||||||
|
MAX_CONTENT_LENGTH = int(os.getenv("MAX_CONTENT_LENGTH_MB", 16)) * 1024 * 1024
|
||||||
|
UPLOAD_FOLDER = os.getenv("UPLOAD_FOLDER", "uploads")
|
||||||
|
ALLOWED_EXTENSIONS = {"jpg", "jpeg", "png", "pdf", "bmp", "tiff", "tif"}
|
||||||
|
|
||||||
|
# Sarvam AI API
|
||||||
|
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
|
||||||
|
SARVAM_API_BASE_URL = os.getenv("SARVAM_API_BASE_URL", "https://api.sarvam.ai")
|
||||||
|
SARVAM_JOB_POLL_INTERVAL = int(os.getenv("SARVAM_JOB_POLL_INTERVAL", 3))
|
||||||
|
SARVAM_JOB_MAX_WAIT = int(os.getenv("SARVAM_JOB_MAX_WAIT", 120))
|
||||||
|
|
||||||
|
# Sarvam Doc-AI Endpoints
|
||||||
|
SARVAM_DIGITISE_URL = f"{SARVAM_API_BASE_URL}/doc-ai/v1/job/digitise"
|
||||||
|
SARVAM_EXTRACT_URL = f"{SARVAM_API_BASE_URL}/doc-ai/v1/job/extract"
|
||||||
|
SARVAM_JOB_STATUS_URL = f"{SARVAM_API_BASE_URL}/doc-ai/v1/job/{{job_id}}/status"
|
||||||
|
SARVAM_JOB_RESULTS_URL = f"{SARVAM_API_BASE_URL}/doc-ai/v1/job/{{job_id}}/results"
|
||||||
|
|
||||||
|
# Google Gemini Vision Configuration
|
||||||
|
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
|
||||||
|
GEMINI_MODEL = os.getenv("GEMINI_MODEL", "gemini-3.8-flash")
|
||||||
|
GEMINI_API_BASE_URL = os.getenv("GEMINI_API_BASE_URL", "https://generativelanguage.googleapis.com/v1beta")
|
||||||
|
|
||||||
|
# Language settings
|
||||||
|
DOCUMENT_LANGUAGE = "mr-IN" # Marathi (BCP-47)
|
||||||
|
CONTENT_TYPE = "handwritten" # handwritten, printed, or mixed
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_sarvam_api_key(cls):
|
||||||
|
"""Get the current Sarvam API key, reloading from .env if updated."""
|
||||||
|
load_dotenv(override=True)
|
||||||
|
return os.getenv("SARVAM_API_KEY", "")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_gemini_api_key(cls):
|
||||||
|
"""Get the current Google Gemini API key, reloading from .env if updated."""
|
||||||
|
load_dotenv(override=True)
|
||||||
|
return os.getenv("GEMINI_API_KEY", "")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_gemini_model(cls):
|
||||||
|
"""Get the configured Gemini vision model name (e.g. gemini-3.8-flash, gemini-3.6-flash)."""
|
||||||
|
load_dotenv(override=True)
|
||||||
|
return os.getenv("GEMINI_MODEL", "gemini-3.8-flash")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_configured_models(cls):
|
||||||
|
"""Return status of which vision models are configured and available."""
|
||||||
|
sarvam_key = cls.get_sarvam_api_key()
|
||||||
|
gemini_key = cls.get_gemini_api_key()
|
||||||
|
return {
|
||||||
|
"sarvam": bool(sarvam_key and sarvam_key != "your_sarvam_api_key_here"),
|
||||||
|
"gemini": bool(gemini_key and gemini_key != "your_gemini_api_key_here"),
|
||||||
|
"gemini_model": cls.get_gemini_model(),
|
||||||
|
}
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate(cls):
|
||||||
|
"""Validate that at least one vision API key is configured."""
|
||||||
|
configured = cls.get_configured_models()
|
||||||
|
errors = []
|
||||||
|
if not configured["sarvam"] and not configured["gemini"]:
|
||||||
|
errors.append(
|
||||||
|
"Neither Sarvam Vision API key nor Google Gemini API key is configured. "
|
||||||
|
"Please configure at least one in your .env file."
|
||||||
|
)
|
||||||
|
return errors
|
||||||
@@ -0,0 +1,864 @@
|
|||||||
|
"""
|
||||||
|
Extraction schema definition for Marathi & English hospital forms.
|
||||||
|
Tailored for Deenanath Mangeshkar Hospital & Research Centre Patient Registration Forms:
|
||||||
|
1. English Form: 'DEENANATH MANGESHKAR HOSPITAL & RESEARCH CENTRE / PATIENT REGISTRATION FORM'
|
||||||
|
2. Marathi Form: 'दीनानाथ मंगेशकर रुग्णालय आणि संशोधन केंद्र / रुग्ण नावनोंदणी अर्ज'
|
||||||
|
|
||||||
|
Incorporates comprehensive alphabet grounding (Marathi Devanagari + English Latin)
|
||||||
|
and multi-tier anti-hallucination safeguards to eliminate synthetic/invented data on unfilled fields.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import copy
|
||||||
|
import re
|
||||||
|
from text_repair_engine import TextRepairEngine
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
# Alphabet & Character Grounding Sets (मराठी वर्णमाला व इंग्रजी मुळाक्षरे)
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
MARATHI_VOWELS = "अ आ इ ई उ ऊ ऋ ऌ ए ऐ ओ औ अं अः ॲ ऑ"
|
||||||
|
MARATHI_CONSONANTS = (
|
||||||
|
"क ख ग घ ङ "
|
||||||
|
"च छ ज झ ञ "
|
||||||
|
"ट ठ ड ढ ण "
|
||||||
|
"त थ द ध न "
|
||||||
|
"प फ ब भ म "
|
||||||
|
"य र ल व श ष स ह ळ क्ष ज्ञ"
|
||||||
|
)
|
||||||
|
MARATHI_MATRAS = "ा ि ी ु ू ृ ॄ े ै ो ौ ं ः ् ॅ ॉ ़"
|
||||||
|
MARATHI_DIGITS_MAP = {
|
||||||
|
"०": "0", "१": "1", "२": "2", "३": "3", "४": "4",
|
||||||
|
"५": "5", "६": "6", "७": "7", "८": "8", "९": "9"
|
||||||
|
}
|
||||||
|
|
||||||
|
ENGLISH_UPPERCASE = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
|
||||||
|
ENGLISH_LOWERCASE = "a b c d e f g h i j k l m n o p q r s t u v w x y z"
|
||||||
|
ENGLISH_DIGITS = "0 1 2 3 4 5 6 7 8 9"
|
||||||
|
|
||||||
|
# Known printed form labels to prevent label-to-value hallucination
|
||||||
|
PRINTED_LABELS_BLACKLIST = {
|
||||||
|
# English form labels
|
||||||
|
"last name / surname", "last name", "surname", "first name", "middle name",
|
||||||
|
"date of birth (dd-mm-yyyy)", "date of birth", "dob", "approximate age in years",
|
||||||
|
"approximate age", "age in years", "age",
|
||||||
|
"flat / room / block no.", "flat / room / block no", "flat/room/block no.",
|
||||||
|
"premises / building / village", "premises / building", "nearby landmark",
|
||||||
|
"road / lane / post office", "road / lane", "area / locality / taluka",
|
||||||
|
"town / city / district", "town / city", "city / district",
|
||||||
|
"state / union territory", "state", "country name", "country",
|
||||||
|
"pincode / zip code", "pincode", "zip code",
|
||||||
|
"telephone no. with area / std code", "telephone no.", "mobile number",
|
||||||
|
"alternate mobile number", "email id", "email",
|
||||||
|
"aadhaar number", "aadhaar", "permanent account number (pan)", "pan",
|
||||||
|
"source of income", "monthly income", "who will pay bills?", "who will pay bills",
|
||||||
|
"name of the company", "company name", "consultant's name", "consultant name",
|
||||||
|
"remark", "remarks", "name of the representative", "representative name",
|
||||||
|
"representative's relation to patient", "representative's relation",
|
||||||
|
"audited by", "entered by", "date", "mrd no.", "mrd no", "registration form",
|
||||||
|
"signature", "patient", "representative", "relation to patient",
|
||||||
|
"name & age of patient (full expanded name as appearing in proof of identity)",
|
||||||
|
"local address (in pune)", "permanent address", "contact numbers, email id, aadhaar and pan",
|
||||||
|
|
||||||
|
# Marathi form labels
|
||||||
|
"आडनाव", "पहिले नाव", "वडिलांचे वा पतीचे वा मधले नाव", "वडिलांचे नाव",
|
||||||
|
"जन्मतारीख (dd-mm-yyyy)", "जन्मतारीख", "किंवा अंदाजे वय वर्षे", "अंदाजे वय वर्षे", "वय वर्षे", "वय",
|
||||||
|
"स्थानिक पत्ता (पुण्यातील)", "स्थानिक पत्ता", "कायमचा पत्ता",
|
||||||
|
"फ्लॅट / खोली / गट क्र.", "फ्लॅट / खोली / गट क्र", "फ्लॅट/खोली/गट क्र.",
|
||||||
|
"परिसर / इमारत / गाव", "परिसर / इमारत", "घराजवळची खूण",
|
||||||
|
"रस्ता / आळी / पोस्ट", "रस्ता / आळी", "विभाग / तालुका", "शहर / जिल्हा",
|
||||||
|
"राज्य / केंद्रशासित प्रदेश", "पिनकोड / झिपकोड", "पिनकोड", "झिपकोड", "देश",
|
||||||
|
"एसटीडी कोडसह दूरध्वनी क्रमांक", "दूरध्वनी क्रमांक", "दूरध्वनी",
|
||||||
|
"भ्रमणध्वनी (मोबाईल) क्रमांक", "भ्रमणध्वनी", "मोबाईल क्रमांक", "मोबाईल",
|
||||||
|
"पर्यायी भ्रमणध्वनी (मोबाईल) क्रमांक", "पर्यायी भ्रमणध्वनी",
|
||||||
|
"ईमेल", "ईमेल आयडी", "आधार क्रमांक", "आधार", "पॅन :", "पॅन क्रमांक", "पॅन",
|
||||||
|
"उत्पन्नाचा स्रोत निवडा", "उत्पन्नाचा स्रोत", "मासिक उत्पन्न - ₹", "मासिक उत्पन्न",
|
||||||
|
"शुल्क कोण भरणार आहे? निवडा", "शुल्क कोण भरणार आहे?", "शुल्क कोण भरणार",
|
||||||
|
"कंपनीचे नाव", "डॉक्टरांचे नाव", "शेरा",
|
||||||
|
"स्वाक्षरी", "रुग्ण", "प्रतिनिधी", "प्रतिनिधीचे नाव", "प्रतिनिधीचे रुग्णाशी असलेले नाते",
|
||||||
|
"तपासणीसाचे नाव", "नोंद घेणाऱ्याचे नाव", "दिनांक", "एमआरडी क्र.", "एमआरडी क्र"
|
||||||
|
}
|
||||||
|
|
||||||
|
GENERIC_DUMMY_VALUES = {
|
||||||
|
"null", "none", "nil", "n/a", "na", "undefined", "-", "—", "unknown",
|
||||||
|
"john doe", "jane doe", "test patient", "sample", "xyz", "abc", "lorem ipsum"
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
# Doc-AI Extract Schema Definition
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
EXTRACTION_SCHEMA = {
|
||||||
|
"type": "object",
|
||||||
|
"description": (
|
||||||
|
"Hospital patient registration form extraction with dual-script grounding (Marathi Devanagari & English Latin) "
|
||||||
|
"and strict zero-hallucination constraints for Deenanath Mangeshkar Hospital & Research Centre registration forms."
|
||||||
|
),
|
||||||
|
"properties": {
|
||||||
|
"anti_hallucination_character_grounding": {
|
||||||
|
"type": "string",
|
||||||
|
"description": (
|
||||||
|
"STRICT DUAL-SCRIPT GROUNDING & ANTI-HALLUCINATION PROTOCOL: "
|
||||||
|
"1. SCRIPT CONSTRAINTS: "
|
||||||
|
" - Marathi Devanagari Letters: स्वर [अ, आ, इ, ई, उ, ऊ, ऋ, ऌ, ए, ऐ, ओ, औ, अं, अः, ॲ, ऑ], "
|
||||||
|
" व्यंजने [क, ख, ग, घ, ङ, च, छ, ज, झ, ञ, ट, ठ, ड, ढ, ण, त, थ, द, ध, न, प, फ, ब, भ, म, य, र, ल, व, श, ष, स, ह, ळ, क्ष, ज्ञ], "
|
||||||
|
" मात्रा [ा, ि, ी, ु, ू, ृ, ॄ, े, ै, ो, ौ, ं, ः, ्, ॅ, ॉ, ़], "
|
||||||
|
" अंक [०=0, १=1, २=2, ३=3, ४=4, ५=5, ६=6, ७=7, ८=8, ९=9]. "
|
||||||
|
" - English Latin Letters: Uppercase [A-Z], Lowercase [a-z], Digits [0-9]. "
|
||||||
|
"2. BLANK BOX & UNFILLED FIELD MANDATE: "
|
||||||
|
" If any character box, dotted line, or text field has NO visible handwritten ink or typed entry, you MUST return null. "
|
||||||
|
" DO NOT guess, fabricate, autocomplete, or invent any patient names, birth dates, phone numbers, or addresses. "
|
||||||
|
"3. BLANK FORM TEMPLATE RULE: "
|
||||||
|
" If the uploaded image is a blank template with no handwritten or patient-entered data, ALL patient details MUST be null. "
|
||||||
|
"4. LABEL NON-DUPLICATION RULE: "
|
||||||
|
" Never output printed prompt labels (e.g. 'Last Name / Surname', 'Flat / Room / Block No.', 'आडनाव') as patient data. "
|
||||||
|
"5. NUMERIC RIGOR: "
|
||||||
|
" Never confuse Marathi ४ with 9 or 5; never confuse Marathi ३ with 9 or 6; never confuse Marathi ५ with 4 or 7. "
|
||||||
|
"6. CHECKBOX INTEGRITY: "
|
||||||
|
" Only extract a checkbox choice if an explicit checkmark [✓] or [x] is visibly drawn. If unchecked, return null. "
|
||||||
|
"7. ENGLISH SPELLINGS & PATIENT MISTAKE REPAIR MANDATE: "
|
||||||
|
" - Convert to English Spellings: Even if the form is filled in Marathi Devanagari script, extract and provide all patient details, names, addresses, and relations in proper ENGLISH spellings (e.g. 'शिंदे' -> 'SHINDE', 'राम' -> 'RAM', 'पुणे' -> 'Pune', 'एरंडवणे' -> 'Erandwane', 'पुरुष' -> 'Male', 'आधार कार्ड' -> 'Aadhaar Card'). "
|
||||||
|
" - Repair Handwriting Slips: If the patient made spelling errors, omitted characters, phonetic slips, or format mistakes in their handwriting (e.g. 'एरंडवना' -> 'Erandwane', 'शिदे' -> 'SHINDE', incomplete date '5/6/80' -> '05/06/1980'), intelligently REPAIR and correct it into standard, clean, well-spelled English. "
|
||||||
|
" - Preserve raw handwritten text exactly in raw_transcription."
|
||||||
|
)
|
||||||
|
},
|
||||||
|
"form_language": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Detected primary printed language of this form: 'en' for English ('PATIENT REGISTRATION FORM') or 'mr' for Marathi ('रुग्ण नावनोंदणी अर्ज')."
|
||||||
|
},
|
||||||
|
"document_type": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Type of document: 'hospital_registration_form', 'medical_note', or 'prescription'."
|
||||||
|
},
|
||||||
|
"hospital_name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Hospital name printed at the top (e.g., 'DEENANATH MANGESHKAR HOSPITAL & RESEARCH CENTRE' or 'दीनानाथ मंगेशकर रुग्णालय आणि संशोधन केंद्र')."
|
||||||
|
},
|
||||||
|
"mrd_number": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "MRD No. / एमआरडी क्र. printed or written in the top-right audit header box. If blank in the top box, return null. Do not hallucinate."
|
||||||
|
},
|
||||||
|
"barcode_number": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Registration barcode number printed at bottom-left under 'Registration Form' barcode (e.g., 'C00000039')."
|
||||||
|
},
|
||||||
|
"visit_date": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Date / दिनांक as written in the top audit header. Read exact digits only. Return null if blank."
|
||||||
|
},
|
||||||
|
"examiner_name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Audited by / तपासणीसाचे नाव as written in top header box. Return null if blank."
|
||||||
|
},
|
||||||
|
"registrar_name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Entered by / नोंद घेणाऱ्याचे नाव as written in top header box. Return null if blank."
|
||||||
|
},
|
||||||
|
"id_proof_type": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Selected ID proof checkbox: 'Aadhaar Card' (आधार कार्ड), 'Pan Card' (पॅन कार्ड), 'Driving License' (चालक परवाना), 'Election Card' (मतदार ओळखपत्र), 'Passport' (पासपोर्ट), 'Birth Certificate' (जन्म प्रमाणपत्र). Only extract if marked."
|
||||||
|
},
|
||||||
|
"gender": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Selected gender: 'Male'/'पुरुष', 'Female'/'स्त्री', 'Transgender'/'तृतीयपंथी'. Only extract if marked."
|
||||||
|
},
|
||||||
|
"salutation": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Selected title/salutation: Mr., Mrs., Mast., Miss., Smt., Dr., Mx, B/o, Fetus of. Only extract if marked."
|
||||||
|
},
|
||||||
|
"surname": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Last Name / Surname / आडनाव as handwritten inside the individual character boxes. Transcribe visible characters only (English A-Z or Marathi क-ज्ञ). Return null if boxes are blank."
|
||||||
|
},
|
||||||
|
"first_name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "First Name / पहिले नाव as handwritten inside the individual character boxes. Transcribe visible characters only (English A-Z or Marathi क-ज्ञ). Return null if boxes are blank."
|
||||||
|
},
|
||||||
|
"middle_name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Middle Name / वडिलांचे वा पतीचे वा मधले नाव as handwritten inside the individual character boxes. Return null if blank."
|
||||||
|
},
|
||||||
|
"patient_name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Full expanded patient name as written. If written separately in boxes, combine First Name + Middle Name + Surname. Return null if blank."
|
||||||
|
},
|
||||||
|
"dob": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Date of Birth / जन्मतारीख (dd-mm-yyyy) as handwritten in the boxes. Transcribe exact digits only. Return null if blank."
|
||||||
|
},
|
||||||
|
"age": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Approximate Age in Years / अंदाजे वय वर्षे as handwritten on the form line or box. Read exact digits only (e.g., '46' or '४६'). Return null if blank."
|
||||||
|
},
|
||||||
|
"local_address": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Local Address (in Pune) / स्थानिक पत्ता (पुण्यातील) including flat/room no, premises/building, landmark, road/lane, area/taluka, and pincode. Return null if blank."
|
||||||
|
},
|
||||||
|
"local_flat_room": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Local Flat / Room / Block No. (फ्लॅट / खोली / गट क्र.). Return null if blank."
|
||||||
|
},
|
||||||
|
"local_premises": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Local Premises / Building / Village (परिसर / इमारत / गाव). Return null if blank."
|
||||||
|
},
|
||||||
|
"local_landmark": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Local Nearby Landmark (घराजवळची खूण). Return null if blank."
|
||||||
|
},
|
||||||
|
"local_road": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Local Road / Lane / Post Office (रस्ता / आळी / पोस्ट). Return null if blank."
|
||||||
|
},
|
||||||
|
"local_taluka": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Local Area / Locality / Taluka (विभाग / तालुका). Return null if blank."
|
||||||
|
},
|
||||||
|
"local_pincode": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Local Pincode / Zip Code (पिनकोड) 6 digits as handwritten in the boxes. Return null if blank."
|
||||||
|
},
|
||||||
|
"permanent_address": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Permanent Address / कायमचा पत्ता including flat/room no, premises/building, landmark, road/lane, area/taluka, city/district, state, country, and pincode. Return null if blank."
|
||||||
|
},
|
||||||
|
"perm_flat_room": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Permanent Flat / Room / Block No. (फ्लॅट / खोली / गट क्र.). Return null if blank."
|
||||||
|
},
|
||||||
|
"perm_premises": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Permanent Premises / Building / Village (परिसर / इमारत / गाव). Return null if blank."
|
||||||
|
},
|
||||||
|
"perm_landmark": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Permanent Nearby Landmark (घराजवळची खूण). Return null if blank."
|
||||||
|
},
|
||||||
|
"perm_road": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Permanent Road / Lane / Post Office (रस्ता / आळी / पोस्ट). Return null if blank."
|
||||||
|
},
|
||||||
|
"perm_taluka": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Permanent Area / Locality / Taluka (विभाग / तालुका). Return null if blank."
|
||||||
|
},
|
||||||
|
"city_district": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Town / City / District / शहर / जिल्हा. Return null if blank."
|
||||||
|
},
|
||||||
|
"perm_state": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "State / Union Territory / राज्य / केंद्रशासित प्रदेश. Return null if blank."
|
||||||
|
},
|
||||||
|
"perm_country": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Country Name / देश. Return null if blank."
|
||||||
|
},
|
||||||
|
"nationality": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Nationality / राष्ट्रीयत्व: 'Indian'/'भारतीय' or specified other. Return null if blank."
|
||||||
|
},
|
||||||
|
"pincode": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Permanent Pincode / Zip Code (पिनकोड/झिपकोड) 6 digits as handwritten in boxes. Return null if blank."
|
||||||
|
},
|
||||||
|
"telephone": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Telephone No. with Area / STD Code / एसटीडी कोडसह दूरध्वनी क्रमांक. Return null if blank."
|
||||||
|
},
|
||||||
|
"mobile_number": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Mobile Number / भ्रमणध्वनी (मोबाईल) क्रमांक (10 digits as written in boxes). Read exact digits only. Return null if blank."
|
||||||
|
},
|
||||||
|
"alternate_mobile": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Alternate Mobile Number / पर्यायी भ्रमणध्वनी (मोबाईल) क्रमांक (10 digits as written in boxes). Return null if blank."
|
||||||
|
},
|
||||||
|
"email": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Email ID / ईमेल as written in boxes in English characters. Return null if blank."
|
||||||
|
},
|
||||||
|
"aadhaar_number": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "AADHAAR Number / आधार क्रमांक (12 digits as written in boxes). Read exact digits only. Return null if blank."
|
||||||
|
},
|
||||||
|
"pan_number": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Permanent Account Number (PAN) / पॅन क्रमांक (10 alphanumeric characters as written in boxes). Return null if blank."
|
||||||
|
},
|
||||||
|
"income_source": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Selected Source of Income / उत्पन्नाचा स्रोत: 'Salary'/'पगार', 'Other Sources'/'अन्य स्रोत', 'Business / Profession'/'उद्योग वा व्यवसाय', 'No Income'/'उत्पन्न नाही'. Return null if not marked."
|
||||||
|
},
|
||||||
|
"monthly_income": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Monthly Income / मासिक उत्पन्न ₹ as written. Return null if blank."
|
||||||
|
},
|
||||||
|
"bill_payer": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Who will pay bills? / शुल्क कोण भरणार आहे?: 'Self'/'स्वतः', 'Company'/'कंपनी'. Return null if not marked."
|
||||||
|
},
|
||||||
|
"company_name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Name of the Company / कंपनीचे नाव if bills paid by company. Return null if blank."
|
||||||
|
},
|
||||||
|
"doctor_name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Consultant's Name / डॉक्टरांचे नाव as written on form. Return null if blank."
|
||||||
|
},
|
||||||
|
"remarks": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Remark / शेरा as handwritten on form. Return null if blank."
|
||||||
|
},
|
||||||
|
"signatory": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Signature / स्वाक्षरी: 'Patient'/'रुग्ण' or 'Representative'/'प्रतिनिधी'. Return null if not marked."
|
||||||
|
},
|
||||||
|
"representative_name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Name of the Representative / प्रतिनिधीचे नाव if signed by representative. Return null if blank."
|
||||||
|
},
|
||||||
|
"representative_relation": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Representative's Relation to Patient / प्रतिनिधीचे रुग्णाशी असलेले नाते. Return null if blank."
|
||||||
|
},
|
||||||
|
"symptoms": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Patient symptoms or complaints if written in clinical notes area. Return null if blank."
|
||||||
|
},
|
||||||
|
"medical_history": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Medical history or past illnesses if written. Return null if blank."
|
||||||
|
},
|
||||||
|
"diagnosis": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Doctor's diagnosis if written. Return null if blank."
|
||||||
|
},
|
||||||
|
"medicines": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "Prescribed medicines and dosages if present on document.",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"name": {"type": "string", "description": "Medicine name"},
|
||||||
|
"dosage": {"type": "string", "description": "Dosage frequency / quantity"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"additional_notes": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Any additional handwritten notes found anywhere on document. Return null if blank."
|
||||||
|
},
|
||||||
|
"raw_transcription": {
|
||||||
|
"type": "string",
|
||||||
|
"description": (
|
||||||
|
"Complete readable text transcribed verbatim from top to bottom, preserving original line breaks. "
|
||||||
|
"For English forms, transcribe English Latin letters. For Marathi forms, transcribe Marathi Devanagari script. "
|
||||||
|
"DO NOT hallucinate or insert words not visible on document. Mark unclear words with [illegible] or [अस्पष्ट]."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
# Standard Structured Response Template
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
EMPTY_RESPONSE_TEMPLATE = {
|
||||||
|
"document_type": "hospital_registration_form",
|
||||||
|
"form_language": "mr",
|
||||||
|
"hospital_details": {
|
||||||
|
"hospital_name": None,
|
||||||
|
"mrd_number": None,
|
||||||
|
"barcode_number": None,
|
||||||
|
"visit_date": None,
|
||||||
|
"examiner_name": None,
|
||||||
|
"registrar_name": None,
|
||||||
|
"department": None,
|
||||||
|
"doctor_name": None,
|
||||||
|
"remarks": None
|
||||||
|
},
|
||||||
|
"patient_details": {
|
||||||
|
"patient_name": None,
|
||||||
|
"surname": None,
|
||||||
|
"first_name": None,
|
||||||
|
"father_or_husband_name": None,
|
||||||
|
"middle_name": None,
|
||||||
|
"salutation": None,
|
||||||
|
"gender": None,
|
||||||
|
"dob": None,
|
||||||
|
"age": None,
|
||||||
|
"id_proof_type": None,
|
||||||
|
"mobile_number": None,
|
||||||
|
"alternate_mobile": None,
|
||||||
|
"telephone": None,
|
||||||
|
"email": None,
|
||||||
|
"aadhaar_number": None,
|
||||||
|
"pan_number": None,
|
||||||
|
"address": None
|
||||||
|
},
|
||||||
|
"address_details": {
|
||||||
|
"local_address": None,
|
||||||
|
"local_flat_room": None,
|
||||||
|
"local_premises": None,
|
||||||
|
"local_landmark": None,
|
||||||
|
"local_road": None,
|
||||||
|
"local_taluka": None,
|
||||||
|
"local_pincode": None,
|
||||||
|
"permanent_address": None,
|
||||||
|
"perm_flat_room": None,
|
||||||
|
"perm_premises": None,
|
||||||
|
"perm_landmark": None,
|
||||||
|
"perm_road": None,
|
||||||
|
"perm_taluka": None,
|
||||||
|
"city_district": None,
|
||||||
|
"perm_state": None,
|
||||||
|
"perm_country": None,
|
||||||
|
"nationality": None,
|
||||||
|
"pincode": None
|
||||||
|
},
|
||||||
|
"billing_details": {
|
||||||
|
"income_source": None,
|
||||||
|
"monthly_income": None,
|
||||||
|
"bill_payer": None,
|
||||||
|
"company_name": None
|
||||||
|
},
|
||||||
|
"representative_details": {
|
||||||
|
"signatory": None,
|
||||||
|
"representative_name": None,
|
||||||
|
"relationship": None
|
||||||
|
},
|
||||||
|
"medical_details": {
|
||||||
|
"symptoms": None,
|
||||||
|
"medical_history": None,
|
||||||
|
"diagnosis": None,
|
||||||
|
"medicines": [],
|
||||||
|
"additional_notes": None
|
||||||
|
},
|
||||||
|
"raw_transcription": "",
|
||||||
|
"repaired_fields": [],
|
||||||
|
"unreadable_fields": [],
|
||||||
|
"validation_warnings": []
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
# Anti-Hallucination & Sanitization Helpers
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def devanagari_to_arabic(text: str) -> str:
|
||||||
|
"""Convert Marathi Devanagari digits (०-९) to standard digits (0-9)."""
|
||||||
|
if not text or not isinstance(text, str):
|
||||||
|
return text
|
||||||
|
result = []
|
||||||
|
for ch in text:
|
||||||
|
result.append(MARATHI_DIGITS_MAP.get(ch, ch))
|
||||||
|
return "".join(result)
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize_extracted_value(val: any) -> any:
|
||||||
|
"""
|
||||||
|
Sanitize an extracted string value against hallucinations:
|
||||||
|
1. Nullify if value matches printed form labels (e.g. 'Last Name / Surname', 'आडनाव').
|
||||||
|
2. Nullify if value is a generic placeholder ('null', 'n/a', 'John Doe').
|
||||||
|
3. Strip whitespace.
|
||||||
|
"""
|
||||||
|
if val is None:
|
||||||
|
return None
|
||||||
|
if isinstance(val, (int, float)):
|
||||||
|
return str(val)
|
||||||
|
if not isinstance(val, str):
|
||||||
|
return val
|
||||||
|
|
||||||
|
cleaned = val.strip()
|
||||||
|
if not cleaned:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Check case-insensitive blacklist
|
||||||
|
lower_val = cleaned.lower()
|
||||||
|
if lower_val in GENERIC_DUMMY_VALUES:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Check against printed form labels
|
||||||
|
cleaned_label_test = re.sub(r'[\:\.\,\-_/\(\)]+', ' ', lower_val).strip()
|
||||||
|
if cleaned_label_test in PRINTED_LABELS_BLACKLIST or lower_val in PRINTED_LABELS_BLACKLIST:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
|
def reconcile_field_against_raw(
|
||||||
|
field_name: str,
|
||||||
|
extracted_val: str,
|
||||||
|
raw_text: str,
|
||||||
|
patterns: list,
|
||||||
|
normalize_digits: bool = True
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Check if raw handwritten transcription contains ground-truth text matching the field.
|
||||||
|
If extracted value contradicts raw text, reconcile it and produce an anti-hallucination warning.
|
||||||
|
"""
|
||||||
|
if not raw_text or not isinstance(raw_text, str):
|
||||||
|
return extracted_val, None
|
||||||
|
|
||||||
|
for pat in patterns:
|
||||||
|
m = re.search(pat, raw_text, re.IGNORECASE)
|
||||||
|
if m:
|
||||||
|
ground_raw = m.group(1).strip()
|
||||||
|
ground_normalized = devanagari_to_arabic(ground_raw) if normalize_digits else ground_raw
|
||||||
|
|
||||||
|
ext_normalized = devanagari_to_arabic(str(extracted_val)).strip() if (extracted_val and normalize_digits) else (str(extracted_val).strip() if extracted_val else "")
|
||||||
|
|
||||||
|
# If extracted value is missing but found in raw handwriting
|
||||||
|
if not ext_normalized:
|
||||||
|
warning = f"Anti-Hallucination Guard: Ground-truth value for '{field_name}' retrieved from raw handwriting: '{ground_raw}'."
|
||||||
|
return ground_normalized, warning
|
||||||
|
|
||||||
|
# If extracted value contradicts raw handwriting
|
||||||
|
if ext_normalized != ground_normalized:
|
||||||
|
warning = (
|
||||||
|
f"Anti-Hallucination Guard: Extracted value '{extracted_val}' for '{field_name}' contradicted "
|
||||||
|
f"raw handwriting ('{ground_raw}'). Auto-corrected to '{ground_normalized}'."
|
||||||
|
)
|
||||||
|
return ground_normalized, warning
|
||||||
|
|
||||||
|
return extracted_val, None
|
||||||
|
|
||||||
|
|
||||||
|
def detect_form_language(raw_text: str, extract_result: dict) -> str:
|
||||||
|
"""
|
||||||
|
Detect whether the form is English ('en') or Marathi ('mr') based on text features.
|
||||||
|
"""
|
||||||
|
# Check explicit result field first
|
||||||
|
explicit_lang = (extract_result.get("form_language") or extract_result.get("language") or "").lower()
|
||||||
|
if explicit_lang in ("en", "english", "en-in"):
|
||||||
|
return "en"
|
||||||
|
if explicit_lang in ("mr", "marathi", "mr-in"):
|
||||||
|
return "mr"
|
||||||
|
|
||||||
|
text_to_check = (raw_text or "") + " " + (extract_result.get("hospital_name") or "")
|
||||||
|
|
||||||
|
# Look for unmistakable markers
|
||||||
|
if "DEENANATH MANGESHKAR HOSPITAL" in text_to_check.upper() or "PATIENT REGISTRATION FORM" in text_to_check.upper():
|
||||||
|
return "en"
|
||||||
|
if "दीनानाथ मंगेशकर रुग्णालय" in text_to_check or "रुग्ण नावनोंदणी अर्ज" in text_to_check:
|
||||||
|
return "mr"
|
||||||
|
|
||||||
|
# Count Devanagari characters vs Latin characters
|
||||||
|
devanagari_count = len(re.findall(r'[\u0900-\u097F]', text_to_check))
|
||||||
|
latin_count = len(re.findall(r'[a-zA-Z]', text_to_check))
|
||||||
|
|
||||||
|
if devanagari_count > latin_count:
|
||||||
|
return "mr"
|
||||||
|
elif latin_count > devanagari_count:
|
||||||
|
return "en"
|
||||||
|
return "mr"
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
# Response Builder
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def build_structured_response(extract_result: dict) -> dict:
|
||||||
|
"""
|
||||||
|
Transform raw extract result into the structured nested response matching both forms.
|
||||||
|
Applies multi-tier anti-hallucination checks, label sanitization, and digit normalization.
|
||||||
|
"""
|
||||||
|
response = copy.deepcopy(EMPTY_RESPONSE_TEMPLATE)
|
||||||
|
|
||||||
|
if not extract_result or not isinstance(extract_result, dict):
|
||||||
|
response["validation_warnings"].append("No extraction result received from Vision API.")
|
||||||
|
return response
|
||||||
|
|
||||||
|
# Flatten nested structures if passed an already-structured dictionary
|
||||||
|
flat_data = {}
|
||||||
|
for k, v in extract_result.items():
|
||||||
|
if isinstance(v, dict) and k.endswith("_details"):
|
||||||
|
for sub_k, sub_v in v.items():
|
||||||
|
if sub_k not in flat_data or flat_data[sub_k] is None:
|
||||||
|
flat_data[sub_k] = sub_v
|
||||||
|
else:
|
||||||
|
if k not in flat_data or flat_data[k] is None:
|
||||||
|
flat_data[k] = v
|
||||||
|
|
||||||
|
response["document_type"] = sanitize_extracted_value(flat_data.get("document_type")) or "hospital_registration_form"
|
||||||
|
|
||||||
|
# Raw Transcription
|
||||||
|
raw_text = flat_data.get("raw_transcription") or ""
|
||||||
|
response["raw_transcription"] = raw_text
|
||||||
|
|
||||||
|
# Form Language
|
||||||
|
lang = detect_form_language(raw_text, flat_data)
|
||||||
|
response["form_language"] = lang
|
||||||
|
|
||||||
|
# Hospital & Registration Details
|
||||||
|
h = response["hospital_details"]
|
||||||
|
h["hospital_name"] = sanitize_extracted_value(flat_data.get("hospital_name"))
|
||||||
|
# Barcode registration number at bottom left
|
||||||
|
barcode = sanitize_extracted_value(flat_data.get("barcode_number")) or sanitize_extracted_value(flat_data.get("barcode"))
|
||||||
|
h["barcode_number"] = barcode
|
||||||
|
|
||||||
|
# MRD Number: Top right box
|
||||||
|
mrd = sanitize_extracted_value(flat_data.get("mrd_number")) or sanitize_extracted_value(flat_data.get("mrp_number"))
|
||||||
|
# If top right MRD number is empty, check if barcode number is the registration ID
|
||||||
|
if not mrd and barcode:
|
||||||
|
mrd = barcode
|
||||||
|
h["mrd_number"] = mrd
|
||||||
|
|
||||||
|
h["visit_date"] = sanitize_extracted_value(flat_data.get("visit_date"))
|
||||||
|
h["examiner_name"] = sanitize_extracted_value(flat_data.get("examiner_name") or flat_data.get("audited_by"))
|
||||||
|
h["registrar_name"] = sanitize_extracted_value(flat_data.get("registrar_name") or flat_data.get("entered_by"))
|
||||||
|
h["department"] = sanitize_extracted_value(flat_data.get("department"))
|
||||||
|
h["doctor_name"] = sanitize_extracted_value(flat_data.get("doctor_name") or flat_data.get("consultant_name"))
|
||||||
|
h["remarks"] = sanitize_extracted_value(flat_data.get("remarks") or flat_data.get("remark"))
|
||||||
|
|
||||||
|
# Patient Identification
|
||||||
|
p = response["patient_details"]
|
||||||
|
p["surname"] = sanitize_extracted_value(flat_data.get("surname") or flat_data.get("last_name"))
|
||||||
|
p["first_name"] = sanitize_extracted_value(flat_data.get("first_name"))
|
||||||
|
p["middle_name"] = sanitize_extracted_value(flat_data.get("middle_name") or flat_data.get("father_or_husband_name"))
|
||||||
|
p["father_or_husband_name"] = p["middle_name"]
|
||||||
|
p["salutation"] = sanitize_extracted_value(flat_data.get("salutation") or flat_data.get("title"))
|
||||||
|
p["gender"] = sanitize_extracted_value(flat_data.get("gender"))
|
||||||
|
p["dob"] = sanitize_extracted_value(flat_data.get("dob") or flat_data.get("date_of_birth"))
|
||||||
|
p["age"] = sanitize_extracted_value(flat_data.get("age") or flat_data.get("approximate_age"))
|
||||||
|
p["id_proof_type"] = sanitize_extracted_value(flat_data.get("id_proof_type"))
|
||||||
|
p["mobile_number"] = sanitize_extracted_value(flat_data.get("mobile_number"))
|
||||||
|
p["alternate_mobile"] = sanitize_extracted_value(flat_data.get("alternate_mobile"))
|
||||||
|
p["telephone"] = sanitize_extracted_value(flat_data.get("telephone"))
|
||||||
|
p["email"] = sanitize_extracted_value(flat_data.get("email"))
|
||||||
|
p["aadhaar_number"] = sanitize_extracted_value(flat_data.get("aadhaar_number"))
|
||||||
|
p["pan_number"] = sanitize_extracted_value(flat_data.get("pan_number"))
|
||||||
|
|
||||||
|
# Compute Composite Patient Name
|
||||||
|
patient_full = sanitize_extracted_value(flat_data.get("patient_name"))
|
||||||
|
if not patient_full:
|
||||||
|
parts = [p["salutation"], p["first_name"], p["middle_name"], p["surname"]]
|
||||||
|
non_empty = [part.strip() for part in parts if part and isinstance(part, str) and part.strip()]
|
||||||
|
if non_empty:
|
||||||
|
patient_full = " ".join(non_empty)
|
||||||
|
p["patient_name"] = patient_full
|
||||||
|
|
||||||
|
# Address Details
|
||||||
|
a = response["address_details"]
|
||||||
|
a["local_flat_room"] = sanitize_extracted_value(flat_data.get("local_flat_room") or flat_data.get("flat_room_no"))
|
||||||
|
a["local_premises"] = sanitize_extracted_value(flat_data.get("local_premises") or flat_data.get("premises_building"))
|
||||||
|
a["local_landmark"] = sanitize_extracted_value(flat_data.get("local_landmark") or flat_data.get("nearby_landmark"))
|
||||||
|
a["local_road"] = sanitize_extracted_value(flat_data.get("local_road") or flat_data.get("road_lane"))
|
||||||
|
a["local_taluka"] = sanitize_extracted_value(flat_data.get("local_taluka") or flat_data.get("area_locality_taluka"))
|
||||||
|
a["local_pincode"] = sanitize_extracted_value(flat_data.get("local_pincode"))
|
||||||
|
|
||||||
|
# Local address composite or direct string
|
||||||
|
loc_addr = sanitize_extracted_value(flat_data.get("local_address"))
|
||||||
|
if not loc_addr:
|
||||||
|
loc_parts = [a["local_flat_room"], a["local_premises"], a["local_landmark"], a["local_road"], a["local_taluka"], a["local_pincode"]]
|
||||||
|
loc_non_empty = [part.strip() for part in loc_parts if part and isinstance(part, str) and part.strip()]
|
||||||
|
if loc_non_empty:
|
||||||
|
loc_addr = ", ".join(loc_non_empty)
|
||||||
|
a["local_address"] = loc_addr
|
||||||
|
|
||||||
|
# Permanent address components
|
||||||
|
a["perm_flat_room"] = sanitize_extracted_value(flat_data.get("perm_flat_room"))
|
||||||
|
a["perm_premises"] = sanitize_extracted_value(flat_data.get("perm_premises"))
|
||||||
|
a["perm_landmark"] = sanitize_extracted_value(flat_data.get("perm_landmark"))
|
||||||
|
a["perm_road"] = sanitize_extracted_value(flat_data.get("perm_road"))
|
||||||
|
a["perm_taluka"] = sanitize_extracted_value(flat_data.get("perm_taluka"))
|
||||||
|
a["city_district"] = sanitize_extracted_value(flat_data.get("city_district") or flat_data.get("town_city_district"))
|
||||||
|
a["perm_state"] = sanitize_extracted_value(flat_data.get("perm_state") or flat_data.get("state"))
|
||||||
|
a["perm_country"] = sanitize_extracted_value(flat_data.get("perm_country") or flat_data.get("country"))
|
||||||
|
a["nationality"] = sanitize_extracted_value(flat_data.get("nationality"))
|
||||||
|
a["pincode"] = sanitize_extracted_value(flat_data.get("pincode"))
|
||||||
|
|
||||||
|
# Permanent address composite or direct string
|
||||||
|
perm_addr = sanitize_extracted_value(flat_data.get("permanent_address"))
|
||||||
|
if not perm_addr:
|
||||||
|
perm_parts = [a["perm_flat_room"], a["perm_premises"], a["perm_landmark"], a["perm_road"], a["perm_taluka"], a["city_district"], a["perm_state"], a["pincode"], a["perm_country"]]
|
||||||
|
perm_non_empty = [part.strip() for part in perm_parts if part and isinstance(part, str) and part.strip()]
|
||||||
|
if perm_non_empty:
|
||||||
|
perm_addr = ", ".join(perm_non_empty)
|
||||||
|
a["permanent_address"] = perm_addr
|
||||||
|
|
||||||
|
# Backward compatibility address field on patient_details
|
||||||
|
p["address"] = a["permanent_address"] or a["local_address"]
|
||||||
|
|
||||||
|
# Billing Details
|
||||||
|
b = response["billing_details"]
|
||||||
|
b["income_source"] = sanitize_extracted_value(flat_data.get("income_source"))
|
||||||
|
b["monthly_income"] = sanitize_extracted_value(flat_data.get("monthly_income"))
|
||||||
|
b["bill_payer"] = sanitize_extracted_value(flat_data.get("bill_payer"))
|
||||||
|
b["company_name"] = sanitize_extracted_value(flat_data.get("company_name"))
|
||||||
|
|
||||||
|
# Representative Details
|
||||||
|
r = response["representative_details"]
|
||||||
|
r["signatory"] = sanitize_extracted_value(flat_data.get("signatory"))
|
||||||
|
r["representative_name"] = sanitize_extracted_value(flat_data.get("representative_name"))
|
||||||
|
r["relationship"] = sanitize_extracted_value(flat_data.get("representative_relation") or flat_data.get("relationship"))
|
||||||
|
|
||||||
|
# Medical Details
|
||||||
|
m = response["medical_details"]
|
||||||
|
m["symptoms"] = sanitize_extracted_value(flat_data.get("symptoms"))
|
||||||
|
m["medical_history"] = sanitize_extracted_value(flat_data.get("medical_history"))
|
||||||
|
m["diagnosis"] = sanitize_extracted_value(flat_data.get("diagnosis"))
|
||||||
|
m["additional_notes"] = sanitize_extracted_value(flat_data.get("additional_notes"))
|
||||||
|
raw_meds = flat_data.get("medicines", [])
|
||||||
|
m["medicines"] = raw_meds if isinstance(raw_meds, list) else []
|
||||||
|
|
||||||
|
# ── Multi-Tier Anti-Hallucination Cross-Verification ──
|
||||||
|
hallucination_warnings = []
|
||||||
|
|
||||||
|
if raw_text:
|
||||||
|
# Age reconciliation (Devanagari or English)
|
||||||
|
age_patterns = [
|
||||||
|
r'(?:वय|अंदाजे\s*वय|Approximate\s*Age|Age)\s*[:\-–=]+\s*([०-९0-9]+)',
|
||||||
|
r'(?:वय|Age)\s*[:\-–=]*\s*([०-९0-9]+)\s*(?:वर्षे?|Years?)'
|
||||||
|
]
|
||||||
|
p["age"], w_age = reconcile_field_against_raw("Age / वय", p["age"], raw_text, age_patterns)
|
||||||
|
if w_age:
|
||||||
|
hallucination_warnings.append(w_age)
|
||||||
|
|
||||||
|
# DOB reconciliation
|
||||||
|
dob_patterns = [
|
||||||
|
r'(?:जन्मतारीख|जन्म\s*तारीख|Date\s*of\s*Birth|DOB)\s*[:\-–=]+\s*([०-९0-9]{1,2}[\/\.\-][०-९0-9]{1,2}[\/\.\-][०-९0-9]{2,4})',
|
||||||
|
]
|
||||||
|
p["dob"], w_dob = reconcile_field_against_raw("Date of Birth / जन्मतारीख", p["dob"], raw_text, dob_patterns)
|
||||||
|
if w_dob:
|
||||||
|
hallucination_warnings.append(w_dob)
|
||||||
|
|
||||||
|
# PIN Code reconciliation
|
||||||
|
pincode_patterns = [
|
||||||
|
r'(?:पिनकोड|पिन\s*कोड|Pincode|Pin\s*Code|Zip\s*Code)\s*[:\-–=]+\s*([०-९0-9]{6})',
|
||||||
|
r'\b([०-९0-9]{6})\b'
|
||||||
|
]
|
||||||
|
a["pincode"], w_pin = reconcile_field_against_raw("PIN Code / पिनकोड", a["pincode"], raw_text, pincode_patterns)
|
||||||
|
if w_pin:
|
||||||
|
hallucination_warnings.append(w_pin)
|
||||||
|
|
||||||
|
# MRD Number reconciliation
|
||||||
|
mrd_patterns = [
|
||||||
|
r'(?:एम\s*आर\s*डी\s*क्र\.|MRD\s*No\.?|Registration\s*No\.?)\s*[:\-–=]+\s*([A-Za-z0-9०-९\-_]+)'
|
||||||
|
]
|
||||||
|
h["mrd_number"], w_mrd = reconcile_field_against_raw("MRD No. / एमआरडी क्र.", h["mrd_number"], raw_text, mrd_patterns, normalize_digits=False)
|
||||||
|
if w_mrd:
|
||||||
|
hallucination_warnings.append(w_mrd)
|
||||||
|
|
||||||
|
# Mobile Number reconciliation
|
||||||
|
mobile_patterns = [
|
||||||
|
r'(?:मोबाईल\s*क्रमांक|भ्रमणध्वनी|Mobile\s*Number|Mobile)\s*[:\-–=]+\s*([०-९0-9]{10})'
|
||||||
|
]
|
||||||
|
p["mobile_number"], w_mob = reconcile_field_against_raw("Mobile Number / मोबाईल क्रमांक", p["mobile_number"], raw_text, mobile_patterns)
|
||||||
|
if w_mob:
|
||||||
|
hallucination_warnings.append(w_mob)
|
||||||
|
|
||||||
|
# ── Marathi to English Conversion & Handwriting Mistake Repair ──
|
||||||
|
repairs_applied = []
|
||||||
|
repair_sections = [
|
||||||
|
("hospital_details", h),
|
||||||
|
("patient_details", p),
|
||||||
|
("address_details", a),
|
||||||
|
("billing_details", b),
|
||||||
|
("representative_details", r),
|
||||||
|
("medical_details", m)
|
||||||
|
]
|
||||||
|
|
||||||
|
for sec_name, sec_dict in repair_sections:
|
||||||
|
for field_key, original_val in list(sec_dict.items()):
|
||||||
|
if original_val is not None and not isinstance(original_val, (list, dict)):
|
||||||
|
repaired_val, repair_note = TextRepairEngine.convert_and_repair(field_key, original_val)
|
||||||
|
sec_dict[field_key] = repaired_val
|
||||||
|
if repair_note and str(repaired_val) != str(original_val):
|
||||||
|
repairs_applied.append({
|
||||||
|
"section": sec_name,
|
||||||
|
"field": field_key,
|
||||||
|
"original": str(original_val),
|
||||||
|
"repaired": str(repaired_val),
|
||||||
|
"note": repair_note
|
||||||
|
})
|
||||||
|
|
||||||
|
# Recompute Composite Patient Name with repaired English name parts
|
||||||
|
if p["first_name"] or p["surname"]:
|
||||||
|
name_parts = [p["salutation"], p["first_name"], p["middle_name"], p["surname"]]
|
||||||
|
valid_parts = [part.strip() for part in name_parts if part and isinstance(part, str) and part.strip()]
|
||||||
|
if valid_parts:
|
||||||
|
p["patient_name"] = " ".join(valid_parts)
|
||||||
|
|
||||||
|
# Recompute Address string if address components were converted/repaired
|
||||||
|
if a["local_flat_room"] or a["local_premises"] or a["local_road"]:
|
||||||
|
loc_parts = [a["local_flat_room"], a["local_premises"], a["local_landmark"], a["local_road"], a["local_taluka"], a["local_pincode"]]
|
||||||
|
loc_non_empty = [part.strip() for part in loc_parts if part and isinstance(part, str) and part.strip()]
|
||||||
|
if loc_non_empty:
|
||||||
|
a["local_address"] = ", ".join(loc_non_empty)
|
||||||
|
|
||||||
|
p["address"] = a["permanent_address"] or a["local_address"]
|
||||||
|
response["repaired_fields"] = repairs_applied
|
||||||
|
|
||||||
|
if repairs_applied:
|
||||||
|
for r_item in repairs_applied:
|
||||||
|
hallucination_warnings.append(
|
||||||
|
f"🔧 Auto-Repaired '{r_item['field']}': '{r_item['original']}' → '{r_item['repaired']}' ({r_item['note']})"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Calculate unreadable / unfilled fields
|
||||||
|
unreadable = []
|
||||||
|
tracked_fields = [
|
||||||
|
("patient_name", p["patient_name"]),
|
||||||
|
("first_name", p["first_name"]),
|
||||||
|
("surname", p["surname"]),
|
||||||
|
("age", p["age"]),
|
||||||
|
("dob", p["dob"]),
|
||||||
|
("gender", p["gender"]),
|
||||||
|
("mobile_number", p["mobile_number"]),
|
||||||
|
("local_address", a["local_address"]),
|
||||||
|
("permanent_address", a["permanent_address"]),
|
||||||
|
("mrd_number", h["mrd_number"]),
|
||||||
|
("visit_date", h["visit_date"]),
|
||||||
|
("aadhaar_number", p["aadhaar_number"]),
|
||||||
|
("pan_number", p["pan_number"])
|
||||||
|
]
|
||||||
|
for name, val in tracked_fields:
|
||||||
|
if val is None or (isinstance(val, str) and val.strip() == ""):
|
||||||
|
unreadable.append(name)
|
||||||
|
|
||||||
|
response["unreadable_fields"] = sorted(unreadable)
|
||||||
|
|
||||||
|
# Blank Form Template Detection & Warnings
|
||||||
|
warnings = []
|
||||||
|
is_blank_form = False
|
||||||
|
if not p["patient_name"] and not p["surname"] and not p["first_name"] and not p["mobile_number"] and not a["local_address"]:
|
||||||
|
is_blank_form = True
|
||||||
|
warnings.append("🛡️ Unfilled Form Template Detected: Character boxes and patient fields are blank (Zero Hallucination).")
|
||||||
|
|
||||||
|
if not response["raw_transcription"]:
|
||||||
|
warnings.append("Raw transcription is empty — document may be blank or low resolution.")
|
||||||
|
|
||||||
|
warnings.extend(hallucination_warnings)
|
||||||
|
response["validation_warnings"] = warnings
|
||||||
|
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
# Digitise Prompt for Bilingual Forms
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
DIGITISE_SYSTEM_PROMPT = """You are a precision document intelligence system specializing in handwritten and printed hospital registration forms in both Marathi (Devanagari script) and English (Latin script).
|
||||||
|
|
||||||
|
Supported Document Types:
|
||||||
|
1. रुग्ण नावनोंदणी अर्ज (Marathi Patient Registration Form - Deenanath Mangeshkar Hospital & Research Centre)
|
||||||
|
2. PATIENT REGISTRATION FORM (English Patient Registration Form - Deenanath Mangeshkar Hospital & Research Centre)
|
||||||
|
|
||||||
|
Grounding Alphabets:
|
||||||
|
- Marathi Devanagari Vowels: अ, आ, इ, ई, उ, ऊ, ऋ, ऌ, ए, ऐ, ओ, औ, अं, अः, ॲ, ऑ
|
||||||
|
- Marathi Devanagari Consonants: क, ख, ग, घ, ङ, च, छ, ज, झ, ञ, ट, ठ, ड, ढ, ण, त, थ, द, ध, न, प, फ, ब, भ, म, य, र, ल, व, श, ष, स, ह, ळ, क्ष, ज्ञ
|
||||||
|
- Marathi Matras: ा, ि, ी, ु, ू, ृ, ॄ, े, ै, ो, ौ, ं, ः, ्, ॅ, ॉ, ़
|
||||||
|
- Marathi Numerals: ०=0, १=1, २=2, ३=3, ४=4, ५=5, ६=6, ७=7, ८=8, ९=9
|
||||||
|
- English Alphabet: Uppercase A-Z, Lowercase a-z, Digits 0-9
|
||||||
|
|
||||||
|
STRICT ANTI-HALLUCINATION RULES:
|
||||||
|
1. Transcribe ONLY visible characters that actually appear on the document.
|
||||||
|
2. If character boxes or dotted lines are blank, leave them blank. DO NOT guess, synthesize, or invent names, dates, or phone numbers.
|
||||||
|
3. If an entire form template is blank and unfilled, transcribe only the printed hospital headers and labels. Never fabricate patient data.
|
||||||
|
4. If a word or number is partially illegible, mark it as [unclear] or [अस्पष्ट].
|
||||||
|
5. Carefully distinguish Devanagari numerals: ४=4 (NOT 9 or 5), ३=3 (NOT 9 or 6), ५=5 (NOT 4 or 7).
|
||||||
|
6. Maintain top-to-bottom reading order.
|
||||||
|
"""
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
"""
|
||||||
|
Google Gemini Vision API client for Document Intelligence.
|
||||||
|
Handles handwritten Marathi & English hospital registration forms using Gemini models
|
||||||
|
(e.g., gemini-2.0-flash, gemini-1.5-flash, gemini-1.5-pro).
|
||||||
|
|
||||||
|
Uses direct Google Generative Language REST API for maximum reliability and speed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
import base64
|
||||||
|
import logging
|
||||||
|
import requests
|
||||||
|
from config import Config
|
||||||
|
from extraction_schema import EXTRACTION_SCHEMA, build_structured_response
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class GeminiAPIError(Exception):
|
||||||
|
"""Custom exception for Gemini API errors."""
|
||||||
|
|
||||||
|
def __init__(self, message: str, status_code: int = None, response_body: str = None):
|
||||||
|
self.status_code = status_code
|
||||||
|
self.response_body = response_body
|
||||||
|
super().__init__(message)
|
||||||
|
|
||||||
|
|
||||||
|
class GeminiClient:
|
||||||
|
"""Client for interacting with Google Gemini Vision API."""
|
||||||
|
|
||||||
|
def __init__(self, model: str = None):
|
||||||
|
self.api_key = Config.get_gemini_api_key()
|
||||||
|
self.model = model or Config.get_gemini_model() or "gemini-2.0-flash"
|
||||||
|
self.base_url = Config.GEMINI_API_BASE_URL
|
||||||
|
|
||||||
|
if not self.api_key or self.api_key == "your_gemini_api_key_here":
|
||||||
|
raise GeminiAPIError(
|
||||||
|
"Google Gemini API key is not configured. "
|
||||||
|
"Please add GEMINI_API_KEY to your .env file (obtain from https://aistudio.google.com/)."
|
||||||
|
)
|
||||||
|
|
||||||
|
def _build_prompt(self, language: str = None) -> str:
|
||||||
|
"""Construct the rigorous zero-hallucination extraction prompt for Gemini."""
|
||||||
|
schema_str = json.dumps(EXTRACTION_SCHEMA, indent=2, ensure_ascii=False)
|
||||||
|
return f"""You are an elite hospital document extraction AI specializing in handwritten Marathi and English patient registration forms from Deenanath Mangeshkar Hospital & Research Centre (दीनानाथ मंगेशकर रुग्णालय आणि संशोधन केंद्र).
|
||||||
|
|
||||||
|
STRICT EXTRACTION RULES:
|
||||||
|
1. DUAL-SCRIPT GROUNDING & ANTI-HALLUCINATION:
|
||||||
|
- Marathi Devanagari script: स्वर (अ-ऑ), व्यंजने (क-ज्ञ), बाराखडी/मात्रा, अंक (०=0, १=1, २=2, ३=3, ४=4, ५=5, ६=6, ७=7, ८=8, ९=9).
|
||||||
|
- English Latin script: Uppercase (A-Z), Lowercase (a-z), Digits (0-9).
|
||||||
|
|
||||||
|
2. ZERO HALLUCINATION MANDATE (CRITICAL):
|
||||||
|
- If any character box, dotted line, or text field has NO visible handwritten ink or typed entry, you MUST return null.
|
||||||
|
- DO NOT fabricate, guess, predict, or autocomplete patient names, dates, phone numbers, or addresses.
|
||||||
|
- If the uploaded form is a blank form template, ALL patient fields MUST be null.
|
||||||
|
- Never output printed prompt labels (e.g., 'Last Name / Surname', 'Flat / Room / Block No.', 'आडनाव') as patient data.
|
||||||
|
|
||||||
|
3. CONVERT MARATHI HANDWRITING TO STANDARD ENGLISH SPELLINGS:
|
||||||
|
- Even if handwritten in Marathi Devanagari script, extract and provide patient names, surnames, addresses, relations, and options in standard, proper ENGLISH Latin spellings.
|
||||||
|
- Examples:
|
||||||
|
* 'शिंदे' -> 'SHINDE'
|
||||||
|
* 'विठ्ठल' -> 'VITTHAL'
|
||||||
|
* 'राम' -> 'RAM'
|
||||||
|
* 'पुणे' -> 'Pune'
|
||||||
|
* 'एरंडवणे' -> 'Erandwane'
|
||||||
|
* 'पुरुष' -> 'Male', 'स्त्री' -> 'Female'
|
||||||
|
* 'पगार' -> 'Salary', 'स्वतः' -> 'Self'
|
||||||
|
* 'आधार कार्ड' -> 'Aadhaar Card'
|
||||||
|
|
||||||
|
4. SMART REPAIR OF PATIENT HANDWRITING SLIPS:
|
||||||
|
- If the patient made spelling errors, omitted characters, phonetic slips, or format mistakes in their handwriting (e.g. 'एरंडवना' -> 'Erandwane', 'शिदे' -> 'SHINDE', 'विठ्ल' -> 'VITTHAL', incomplete date '15.6.80' -> '15/06/1980'), intelligently repair and correct it into standard, clean, well-spelled English.
|
||||||
|
|
||||||
|
5. RAW TRANSCRIPTION:
|
||||||
|
- In 'raw_transcription', provide the complete transcription of all visible handwritten and printed text exactly as written on the document.
|
||||||
|
|
||||||
|
6. OUTPUT FORMAT:
|
||||||
|
- You MUST output a SINGLE, VALID JSON object conforming to the following JSON schema:
|
||||||
|
{schema_str}
|
||||||
|
|
||||||
|
Return ONLY the raw JSON object. Do not include markdown codeblocks, explanations, or preface text.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def extract(
|
||||||
|
self,
|
||||||
|
file_bytes: bytes,
|
||||||
|
filename: str,
|
||||||
|
mime_type: str = "image/jpeg",
|
||||||
|
language: str = None
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
Extract structured information from a document using Gemini Vision.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
file_bytes: Raw binary bytes of the document.
|
||||||
|
filename: Original filename.
|
||||||
|
mime_type: MIME type of the document (image/jpeg, image/png, application/pdf).
|
||||||
|
language: Requested document language code (optional).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict containing the structured extraction result adhering to schema.
|
||||||
|
"""
|
||||||
|
start_time = time.time()
|
||||||
|
logger.info(f"Submitting document to Gemini Vision ({self.model}): {filename} ({len(file_bytes)} bytes)")
|
||||||
|
|
||||||
|
# Prepare base64 inline data
|
||||||
|
b64_data = base64.b64encode(file_bytes).decode("utf-8")
|
||||||
|
|
||||||
|
prompt_text = self._build_prompt(language)
|
||||||
|
|
||||||
|
# Gemini REST payload
|
||||||
|
payload = {
|
||||||
|
"contents": [
|
||||||
|
{
|
||||||
|
"parts": [
|
||||||
|
{"text": prompt_text},
|
||||||
|
{
|
||||||
|
"inline_data": {
|
||||||
|
"mime_type": mime_type,
|
||||||
|
"data": b64_data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"generationConfig": {
|
||||||
|
"response_mime_type": "application/json",
|
||||||
|
"temperature": 0.1,
|
||||||
|
"maxOutputTokens": 8192
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# List of verified fallback models in order of priority (only currently supported active models)
|
||||||
|
fallback_candidates = [
|
||||||
|
"gemini-3.8-flash",
|
||||||
|
"gemini-flash-latest",
|
||||||
|
"gemini-3.6-flash",
|
||||||
|
"gemini-3.5-flash",
|
||||||
|
"gemini-2.5-flash"
|
||||||
|
]
|
||||||
|
models_to_try = [self.model]
|
||||||
|
for m in fallback_candidates:
|
||||||
|
if m != self.model and m not in models_to_try:
|
||||||
|
models_to_try.append(m)
|
||||||
|
|
||||||
|
resp = None
|
||||||
|
used_model = self.model
|
||||||
|
fallback_used = False
|
||||||
|
fallback_note = None
|
||||||
|
last_error_msg = ""
|
||||||
|
last_status_code = None
|
||||||
|
primary_error_msg = None
|
||||||
|
primary_status_code = None
|
||||||
|
|
||||||
|
for idx, current_model in enumerate(models_to_try):
|
||||||
|
endpoint_url = f"{self.base_url}/models/{current_model}:generateContent?key={self.api_key}"
|
||||||
|
|
||||||
|
# Allow up to 2 attempts for 503 / 429 rate limit or demand spike
|
||||||
|
max_attempts = 2 if idx == 0 else 1
|
||||||
|
for attempt in range(max_attempts):
|
||||||
|
if attempt > 0:
|
||||||
|
time.sleep(1.8)
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = requests.post(
|
||||||
|
endpoint_url,
|
||||||
|
headers={"Content-Type": "application/json"},
|
||||||
|
json=payload,
|
||||||
|
timeout=90
|
||||||
|
)
|
||||||
|
except requests.exceptions.Timeout:
|
||||||
|
last_error_msg = f"Gemini API request timed out after 90 seconds for model {current_model}."
|
||||||
|
last_status_code = 408
|
||||||
|
continue
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
last_error_msg = f"Network error connecting to Gemini API: {str(e)}"
|
||||||
|
last_status_code = 500
|
||||||
|
continue
|
||||||
|
|
||||||
|
if resp.status_code == 200:
|
||||||
|
used_model = current_model
|
||||||
|
if idx > 0:
|
||||||
|
fallback_used = True
|
||||||
|
fallback_note = f"Auto-switched from {self.model} ({primary_status_code or last_status_code}) to active model {current_model}"
|
||||||
|
logger.warning(fallback_note)
|
||||||
|
break
|
||||||
|
|
||||||
|
# Inspect non-200 status
|
||||||
|
last_status_code = resp.status_code
|
||||||
|
try:
|
||||||
|
err_json = resp.json()
|
||||||
|
last_error_msg = err_json.get("error", {}).get("message", resp.text[:300])
|
||||||
|
except Exception:
|
||||||
|
last_error_msg = resp.text[:300]
|
||||||
|
|
||||||
|
if idx == 0 and attempt == 0:
|
||||||
|
primary_error_msg = last_error_msg
|
||||||
|
primary_status_code = last_status_code
|
||||||
|
|
||||||
|
logger.warning(f"Gemini model {current_model} returned {last_status_code}: {last_error_msg[:160]}")
|
||||||
|
|
||||||
|
# If 503 (High Demand) or 429, retry after backoff before next model
|
||||||
|
if resp.status_code in (503, 429) and attempt < max_attempts - 1:
|
||||||
|
logger.info(f"Model {current_model} returned {resp.status_code} on attempt {attempt+1}. Retrying in 1.8s...")
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
if resp is not None and resp.status_code == 200:
|
||||||
|
break
|
||||||
|
|
||||||
|
duration = time.time() - start_time
|
||||||
|
|
||||||
|
if resp is None or resp.status_code != 200:
|
||||||
|
err_detail = primary_error_msg if primary_error_msg else last_error_msg
|
||||||
|
code_detail = primary_status_code if primary_status_code else last_status_code
|
||||||
|
helpful_tip = ""
|
||||||
|
if code_detail == 429:
|
||||||
|
helpful_tip = " (Free Tier daily request quota exceeded for this model. Switch to 'gemini-3.8-flash' or 'gemini-flash-latest')."
|
||||||
|
raise GeminiAPIError(
|
||||||
|
f"Gemini API error for model '{self.model}' ({code_detail}): {err_detail}{helpful_tip}",
|
||||||
|
status_code=code_detail,
|
||||||
|
response_body=resp.text if resp is not None else ""
|
||||||
|
)
|
||||||
|
|
||||||
|
# Parse response
|
||||||
|
try:
|
||||||
|
resp_json = resp.json()
|
||||||
|
candidates = resp_json.get("candidates", [])
|
||||||
|
if not candidates:
|
||||||
|
raise GeminiAPIError("No response candidates returned by Gemini.")
|
||||||
|
|
||||||
|
candidate = candidates[0]
|
||||||
|
parts = candidate.get("content", {}).get("parts", [])
|
||||||
|
if not parts:
|
||||||
|
raise GeminiAPIError("Empty content parts in Gemini response.")
|
||||||
|
|
||||||
|
text_content = parts[0].get("text", "").strip()
|
||||||
|
|
||||||
|
# Strip markdown fences if present
|
||||||
|
if text_content.startswith("```json"):
|
||||||
|
text_content = text_content[7:]
|
||||||
|
elif text_content.startswith("```"):
|
||||||
|
text_content = text_content[3:]
|
||||||
|
if text_content.endswith("```"):
|
||||||
|
text_content = text_content[:-3]
|
||||||
|
text_content = text_content.strip()
|
||||||
|
|
||||||
|
raw_extracted = json.loads(text_content)
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
logger.error(f"Failed to parse Gemini JSON output: {e}\nRaw text: {text_content[:500]}")
|
||||||
|
raise GeminiAPIError(f"Gemini did not return valid JSON: {str(e)}")
|
||||||
|
except Exception as e:
|
||||||
|
raise GeminiAPIError(f"Failed processing Gemini output: {str(e)}")
|
||||||
|
|
||||||
|
# Structure through canonical pipeline (applies text repairs & grounding)
|
||||||
|
structured = build_structured_response(raw_extracted)
|
||||||
|
|
||||||
|
# Attach metadata
|
||||||
|
structured["_meta"] = {
|
||||||
|
"model": f"Gemini ({used_model})",
|
||||||
|
"model_family": "gemini",
|
||||||
|
"model_name": used_model,
|
||||||
|
"api_response_time_seconds": round(duration, 2),
|
||||||
|
"method": "gemini_vision",
|
||||||
|
"status": "completed",
|
||||||
|
"fallback_used": fallback_used,
|
||||||
|
"fallback_note": fallback_note
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(f"Gemini extraction completed in {duration:.2f}s for model {used_model} (fallback: {fallback_used})")
|
||||||
|
return structured
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
"""
|
||||||
|
History Manager for Handwritten Marathi Extraction App.
|
||||||
|
Persists test extraction runs, structured JSON results, raw Devanagari transcriptions,
|
||||||
|
and associated document images across server restarts.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import io
|
||||||
|
import csv
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
import shutil
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
|
||||||
|
DATA_DIR = os.path.join(BASE_DIR, "data")
|
||||||
|
IMAGES_DIR = os.path.join(DATA_DIR, "images")
|
||||||
|
HISTORY_FILE = os.path.join(DATA_DIR, "test_history.json")
|
||||||
|
|
||||||
|
|
||||||
|
class HistoryManager:
|
||||||
|
"""Thread-safe manager for persisting and querying document extraction history."""
|
||||||
|
|
||||||
|
_lock = threading.Lock()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _ensure_dirs(cls):
|
||||||
|
"""Ensure storage directories exist."""
|
||||||
|
os.makedirs(DATA_DIR, exist_ok=True)
|
||||||
|
os.makedirs(IMAGES_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def load_all(cls) -> list:
|
||||||
|
"""Load all history records from disk."""
|
||||||
|
cls._ensure_dirs()
|
||||||
|
if not os.path.exists(HISTORY_FILE):
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
with open(HISTORY_FILE, "r", encoding="utf-8") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
return data if isinstance(data, list) else []
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to load history from {HISTORY_FILE}: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def save_all(cls, records: list) -> bool:
|
||||||
|
"""Save history records to disk atomically."""
|
||||||
|
cls._ensure_dirs()
|
||||||
|
temp_file = f"{HISTORY_FILE}.tmp"
|
||||||
|
try:
|
||||||
|
with open(temp_file, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(records, f, ensure_ascii=False, indent=2)
|
||||||
|
# Atomic rename on Windows/Unix
|
||||||
|
os.replace(temp_file, HISTORY_FILE)
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to save history to {HISTORY_FILE}: {e}")
|
||||||
|
if os.path.exists(temp_file):
|
||||||
|
try:
|
||||||
|
os.remove(temp_file)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return False
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def add_entry(
|
||||||
|
cls,
|
||||||
|
entry: dict,
|
||||||
|
original_bytes: bytes = None,
|
||||||
|
processed_bytes: bytes = None,
|
||||||
|
file_ext: str = "jpg"
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
Add a new test result entry and optionally save document images.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
entry: Dict containing test metadata and extraction results.
|
||||||
|
original_bytes: Raw bytes of the uploaded image.
|
||||||
|
processed_bytes: Raw bytes of the preprocessed image.
|
||||||
|
file_ext: Extension of the image (default: jpg).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The saved entry dict.
|
||||||
|
"""
|
||||||
|
cls._ensure_dirs()
|
||||||
|
with cls._lock:
|
||||||
|
records = cls.load_all()
|
||||||
|
|
||||||
|
entry_id = entry.get("id") or str(uuid.uuid4())[:8]
|
||||||
|
entry["id"] = entry_id
|
||||||
|
if "timestamp" not in entry:
|
||||||
|
entry["timestamp"] = datetime.now().isoformat()
|
||||||
|
|
||||||
|
# Clean extension
|
||||||
|
ext = file_ext.lstrip(".").lower()
|
||||||
|
if ext not in ("jpg", "jpeg", "png", "bmp", "tiff", "pdf"):
|
||||||
|
ext = "jpg"
|
||||||
|
|
||||||
|
# Save original image if provided
|
||||||
|
entry["has_original_image"] = False
|
||||||
|
if original_bytes:
|
||||||
|
orig_filename = f"{entry_id}_orig.{ext}"
|
||||||
|
orig_path = os.path.join(IMAGES_DIR, orig_filename)
|
||||||
|
try:
|
||||||
|
with open(orig_path, "wb") as f:
|
||||||
|
f.write(original_bytes)
|
||||||
|
entry["has_original_image"] = True
|
||||||
|
entry["original_image_file"] = orig_filename
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Could not save original image: {e}")
|
||||||
|
|
||||||
|
# Save processed image if provided
|
||||||
|
entry["has_processed_image"] = False
|
||||||
|
if processed_bytes:
|
||||||
|
proc_filename = f"{entry_id}_proc.{ext}"
|
||||||
|
proc_path = os.path.join(IMAGES_DIR, proc_filename)
|
||||||
|
try:
|
||||||
|
with open(proc_path, "wb") as f:
|
||||||
|
f.write(processed_bytes)
|
||||||
|
entry["has_processed_image"] = True
|
||||||
|
entry["processed_image_file"] = proc_filename
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Could not save processed image: {e}")
|
||||||
|
|
||||||
|
# Prepend newest first
|
||||||
|
records.insert(0, entry)
|
||||||
|
cls.save_all(records)
|
||||||
|
logger.info(f"Saved test result {entry_id} for {entry.get('filename')} to persistent history.")
|
||||||
|
return entry
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_all(cls, limit: int = None) -> list:
|
||||||
|
"""Get all test results (optionally limited)."""
|
||||||
|
with cls._lock:
|
||||||
|
records = cls.load_all()
|
||||||
|
if limit and limit > 0:
|
||||||
|
return records[:limit]
|
||||||
|
return records
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_by_id(cls, entry_id: str) -> dict:
|
||||||
|
"""Get a single test result by ID."""
|
||||||
|
with cls._lock:
|
||||||
|
records = cls.load_all()
|
||||||
|
for r in records:
|
||||||
|
if r.get("id") == entry_id:
|
||||||
|
return r
|
||||||
|
return None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_image_path(cls, entry_id: str, image_type: str = "original") -> str:
|
||||||
|
"""Return the absolute path to a saved image file if it exists."""
|
||||||
|
entry = cls.get_by_id(entry_id)
|
||||||
|
if not entry:
|
||||||
|
return None
|
||||||
|
|
||||||
|
key = "original_image_file" if image_type == "original" else "processed_image_file"
|
||||||
|
filename = entry.get(key)
|
||||||
|
if filename:
|
||||||
|
path = os.path.join(IMAGES_DIR, filename)
|
||||||
|
if os.path.exists(path):
|
||||||
|
return path
|
||||||
|
return None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def delete_entry(cls, entry_id: str) -> bool:
|
||||||
|
"""Delete an entry and its associated stored images."""
|
||||||
|
with cls._lock:
|
||||||
|
records = cls.load_all()
|
||||||
|
found = False
|
||||||
|
new_records = []
|
||||||
|
|
||||||
|
for r in records:
|
||||||
|
if r.get("id") == entry_id:
|
||||||
|
found = True
|
||||||
|
# Remove saved image files
|
||||||
|
for key in ("original_image_file", "processed_image_file"):
|
||||||
|
fname = r.get(key)
|
||||||
|
if fname:
|
||||||
|
p = os.path.join(IMAGES_DIR, fname)
|
||||||
|
if os.path.exists(p):
|
||||||
|
try:
|
||||||
|
os.remove(p)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
new_records.append(r)
|
||||||
|
|
||||||
|
if found:
|
||||||
|
cls.save_all(new_records)
|
||||||
|
logger.info(f"Deleted test entry {entry_id} from history.")
|
||||||
|
return found
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def clear_all(cls) -> bool:
|
||||||
|
"""Clear all history and remove all stored images."""
|
||||||
|
with cls._lock:
|
||||||
|
cls.save_all([])
|
||||||
|
if os.path.exists(IMAGES_DIR):
|
||||||
|
shutil.rmtree(IMAGES_DIR, ignore_errors=True)
|
||||||
|
os.makedirs(IMAGES_DIR, exist_ok=True)
|
||||||
|
logger.info("Cleared all test history and saved images.")
|
||||||
|
return True
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def export_csv(cls) -> str:
|
||||||
|
"""Export history summary as CSV string."""
|
||||||
|
with cls._lock:
|
||||||
|
records = cls.load_all()
|
||||||
|
output = io.StringIO()
|
||||||
|
writer = csv.writer(output)
|
||||||
|
|
||||||
|
headers = [
|
||||||
|
"ID", "Timestamp", "Filename", "Model", "Method", "Status",
|
||||||
|
"API Response Time (s)", "Total Time (s)",
|
||||||
|
"Fields Extracted", "Fields Missing", "Patient Name",
|
||||||
|
"Hospital Name", "Diagnosis", "Raw Transcription Length"
|
||||||
|
]
|
||||||
|
writer.writerow(headers)
|
||||||
|
|
||||||
|
for r in records:
|
||||||
|
res = r.get("result", {})
|
||||||
|
patient = res.get("patient_details", {})
|
||||||
|
hospital = res.get("hospital_details", {})
|
||||||
|
med = res.get("medical_details", {})
|
||||||
|
|
||||||
|
writer.writerow([
|
||||||
|
r.get("id", ""),
|
||||||
|
r.get("timestamp", ""),
|
||||||
|
r.get("filename", ""),
|
||||||
|
r.get("model", ""),
|
||||||
|
r.get("method", ""),
|
||||||
|
r.get("status", ""),
|
||||||
|
r.get("api_response_time", ""),
|
||||||
|
r.get("total_time", ""),
|
||||||
|
r.get("fields_extracted", 0),
|
||||||
|
r.get("fields_missing", 0),
|
||||||
|
patient.get("patient_name") or "",
|
||||||
|
hospital.get("hospital_name") or "",
|
||||||
|
med.get("diagnosis") or "",
|
||||||
|
len(r.get("raw_transcription") or "")
|
||||||
|
])
|
||||||
|
|
||||||
|
return output.getvalue()
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
"""
|
||||||
|
Image preprocessing module using OpenCV.
|
||||||
|
Provides optional enhancements for scanned/photographed handwritten documents.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image
|
||||||
|
import io
|
||||||
|
import base64
|
||||||
|
|
||||||
|
|
||||||
|
class ImagePreprocessor:
|
||||||
|
"""Preprocesses images to improve handwritten text extraction quality."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def load_image_from_bytes(image_bytes: bytes) -> np.ndarray:
|
||||||
|
"""Load an image from raw bytes into an OpenCV array."""
|
||||||
|
nparr = np.frombuffer(image_bytes, np.uint8)
|
||||||
|
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
|
||||||
|
if img is None:
|
||||||
|
raise ValueError("Could not decode image from provided bytes.")
|
||||||
|
return img
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def to_bytes(img: np.ndarray, ext: str = ".jpg") -> bytes:
|
||||||
|
"""Convert an OpenCV image array back to bytes."""
|
||||||
|
success, buffer = cv2.imencode(ext, img)
|
||||||
|
if not success:
|
||||||
|
raise ValueError(f"Failed to encode image to {ext}")
|
||||||
|
return buffer.tobytes()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def to_base64(img: np.ndarray, ext: str = ".jpg") -> str:
|
||||||
|
"""Convert an OpenCV image to a base64-encoded string."""
|
||||||
|
img_bytes = ImagePreprocessor.to_bytes(img, ext)
|
||||||
|
return base64.b64encode(img_bytes).decode("utf-8")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def auto_rotate(img: np.ndarray) -> np.ndarray:
|
||||||
|
"""
|
||||||
|
Detect and correct image rotation/skew using text line detection.
|
||||||
|
Uses Hough line transform to find dominant text orientation.
|
||||||
|
"""
|
||||||
|
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
# Edge detection
|
||||||
|
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
|
||||||
|
# Detect lines
|
||||||
|
lines = cv2.HoughLinesP(
|
||||||
|
edges, 1, np.pi / 180, threshold=100,
|
||||||
|
minLineLength=100, maxLineGap=10
|
||||||
|
)
|
||||||
|
|
||||||
|
if lines is None or len(lines) == 0:
|
||||||
|
return img # No lines detected, return as-is
|
||||||
|
|
||||||
|
# Calculate angles of detected lines
|
||||||
|
angles = []
|
||||||
|
for line in lines:
|
||||||
|
pts = line.reshape(-1)
|
||||||
|
if len(pts) < 4:
|
||||||
|
continue
|
||||||
|
x1, y1, x2, y2 = pts[:4]
|
||||||
|
if x2 - x1 == 0:
|
||||||
|
continue
|
||||||
|
angle = np.degrees(np.arctan2(y2 - y1, x2 - x1))
|
||||||
|
# Only consider near-horizontal lines (text lines)
|
||||||
|
if abs(angle) < 45:
|
||||||
|
angles.append(angle)
|
||||||
|
|
||||||
|
if not angles:
|
||||||
|
return img
|
||||||
|
|
||||||
|
# Use median angle to avoid outlier influence
|
||||||
|
median_angle = np.median(angles)
|
||||||
|
|
||||||
|
# Only rotate if skew is significant (> 0.5 degrees)
|
||||||
|
if abs(median_angle) < 0.5:
|
||||||
|
return img
|
||||||
|
|
||||||
|
# Rotate to correct skew
|
||||||
|
(h, w) = img.shape[:2]
|
||||||
|
center = (w // 2, h // 2)
|
||||||
|
rotation_matrix = cv2.getRotationMatrix2D(center, median_angle, 1.0)
|
||||||
|
|
||||||
|
# Calculate new bounding box size
|
||||||
|
cos = np.abs(rotation_matrix[0, 0])
|
||||||
|
sin = np.abs(rotation_matrix[0, 1])
|
||||||
|
new_w = int(h * sin + w * cos)
|
||||||
|
new_h = int(h * cos + w * sin)
|
||||||
|
rotation_matrix[0, 2] += (new_w / 2) - center[0]
|
||||||
|
rotation_matrix[1, 2] += (new_h / 2) - center[1]
|
||||||
|
|
||||||
|
rotated = cv2.warpAffine(
|
||||||
|
img, rotation_matrix, (new_w, new_h),
|
||||||
|
borderMode=cv2.BORDER_REPLICATE
|
||||||
|
)
|
||||||
|
return rotated
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def enhance_contrast(img: np.ndarray) -> np.ndarray:
|
||||||
|
"""
|
||||||
|
Improve contrast using CLAHE (Contrast Limited Adaptive Histogram Equalization).
|
||||||
|
Applied gently to preserve handwriting strokes.
|
||||||
|
"""
|
||||||
|
# Convert to LAB color space for luminance-only enhancement
|
||||||
|
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
|
||||||
|
l_channel, a, b = cv2.split(lab)
|
||||||
|
|
||||||
|
# Apply CLAHE with conservative parameters to avoid destroying strokes
|
||||||
|
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
|
||||||
|
cl = clahe.apply(l_channel)
|
||||||
|
|
||||||
|
# Merge back
|
||||||
|
enhanced = cv2.merge((cl, a, b))
|
||||||
|
result = cv2.cvtColor(enhanced, cv2.COLOR_LAB2BGR)
|
||||||
|
return result
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def reduce_noise(img: np.ndarray) -> np.ndarray:
|
||||||
|
"""
|
||||||
|
Reduce noise while preserving handwriting edges.
|
||||||
|
Uses non-local means denoising — gentler than Gaussian blur.
|
||||||
|
"""
|
||||||
|
# fastNlMeansDenoisingColored with conservative strength
|
||||||
|
denoised = cv2.fastNlMeansDenoisingColored(
|
||||||
|
img, None, 6, 6, 7, 21
|
||||||
|
)
|
||||||
|
return denoised
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def resize_if_needed(img: np.ndarray, max_dimension: int = 4096) -> np.ndarray:
|
||||||
|
"""
|
||||||
|
Resize image if any dimension exceeds max_dimension.
|
||||||
|
Maintains aspect ratio.
|
||||||
|
"""
|
||||||
|
h, w = img.shape[:2]
|
||||||
|
if max(h, w) <= max_dimension:
|
||||||
|
return img
|
||||||
|
|
||||||
|
scale = max_dimension / max(h, w)
|
||||||
|
new_w = int(w * scale)
|
||||||
|
new_h = int(h * scale)
|
||||||
|
resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA)
|
||||||
|
return resized
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def sharpen(img: np.ndarray) -> np.ndarray:
|
||||||
|
"""
|
||||||
|
Gently sharpen the image to make handwriting strokes clearer.
|
||||||
|
Uses an unsharp mask approach.
|
||||||
|
"""
|
||||||
|
gaussian = cv2.GaussianBlur(img, (0, 0), 3)
|
||||||
|
sharpened = cv2.addWeighted(img, 1.3, gaussian, -0.3, 0)
|
||||||
|
return sharpened
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def preprocess(
|
||||||
|
cls,
|
||||||
|
image_bytes: bytes,
|
||||||
|
auto_rotate: bool = True,
|
||||||
|
enhance_contrast: bool = True,
|
||||||
|
reduce_noise: bool = True,
|
||||||
|
sharpen: bool = True,
|
||||||
|
resize: bool = True,
|
||||||
|
max_dimension: int = 4096
|
||||||
|
) -> tuple[bytes, dict]:
|
||||||
|
"""
|
||||||
|
Apply the full preprocessing pipeline.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
image_bytes: Raw image file bytes.
|
||||||
|
auto_rotate: Whether to correct skew/rotation.
|
||||||
|
enhance_contrast: Whether to apply CLAHE contrast enhancement.
|
||||||
|
reduce_noise: Whether to apply noise reduction.
|
||||||
|
sharpen: Whether to sharpen handwriting strokes.
|
||||||
|
resize: Whether to resize oversized images.
|
||||||
|
max_dimension: Maximum pixel dimension for resize.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (processed_image_bytes, processing_info_dict).
|
||||||
|
"""
|
||||||
|
steps_applied = []
|
||||||
|
|
||||||
|
try:
|
||||||
|
img = cls.load_image_from_bytes(image_bytes)
|
||||||
|
original_shape = img.shape[:2]
|
||||||
|
except Exception as e:
|
||||||
|
return image_bytes, {
|
||||||
|
"error": f"Could not load image: {str(e)}",
|
||||||
|
"steps_applied": [],
|
||||||
|
"original_size": None,
|
||||||
|
"processed_size": None
|
||||||
|
}
|
||||||
|
|
||||||
|
# Step 1: Resize if needed (do first to speed up subsequent operations)
|
||||||
|
if resize:
|
||||||
|
img = cls.resize_if_needed(img, max_dimension)
|
||||||
|
if img.shape[:2] != original_shape:
|
||||||
|
steps_applied.append("resize")
|
||||||
|
|
||||||
|
# Step 2: Auto-rotate / deskew
|
||||||
|
if auto_rotate:
|
||||||
|
before_shape = img.shape
|
||||||
|
img = cls.auto_rotate(img)
|
||||||
|
steps_applied.append("auto_rotate")
|
||||||
|
|
||||||
|
# Step 3: Noise reduction
|
||||||
|
if reduce_noise:
|
||||||
|
img = cls.reduce_noise(img)
|
||||||
|
steps_applied.append("noise_reduction")
|
||||||
|
|
||||||
|
# Step 4: Contrast enhancement
|
||||||
|
if enhance_contrast:
|
||||||
|
img = cls.enhance_contrast(img)
|
||||||
|
steps_applied.append("contrast_enhancement")
|
||||||
|
|
||||||
|
# Step 5: Sharpening
|
||||||
|
if sharpen:
|
||||||
|
img = cls.sharpen(img)
|
||||||
|
steps_applied.append("sharpen")
|
||||||
|
|
||||||
|
processed_bytes = cls.to_bytes(img, ".jpg")
|
||||||
|
processed_shape = img.shape[:2]
|
||||||
|
|
||||||
|
info = {
|
||||||
|
"steps_applied": steps_applied,
|
||||||
|
"original_size": {"height": original_shape[0], "width": original_shape[1]},
|
||||||
|
"processed_size": {"height": processed_shape[0], "width": processed_shape[1]},
|
||||||
|
"original_bytes": len(image_bytes),
|
||||||
|
"processed_bytes": len(processed_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
return processed_bytes, info
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
Flask>=3.0.0
|
||||||
|
requests>=2.31.0
|
||||||
|
python-dotenv>=1.0.0
|
||||||
|
opencv-python-headless>=4.10.0
|
||||||
|
numpy>=2.1.0
|
||||||
|
Pillow>=10.3.0
|
||||||
|
Werkzeug>=3.0.0
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
{
|
||||||
|
"document_type": "hospital_registration_form",
|
||||||
|
"form_language": "mr",
|
||||||
|
"hospital_details": {
|
||||||
|
"hospital_name": "DEENANATH MANGESHKAR HOSPITAL & RESEARCH CENTRE",
|
||||||
|
"mrd_number": "C00000039",
|
||||||
|
"barcode_number": "C00000039",
|
||||||
|
"visit_date": "14/10/2026",
|
||||||
|
"examiner_name": "SUNIL JOSHI",
|
||||||
|
"registrar_name": "ANITA KULKARNI",
|
||||||
|
"department": "OPD Registration",
|
||||||
|
"doctor_name": "Dr. Sachin Deshpande",
|
||||||
|
"remarks": "Urgent examination required"
|
||||||
|
},
|
||||||
|
"patient_details": {
|
||||||
|
"patient_name": "Mr. RAM VITTHAL SHINDE",
|
||||||
|
"surname": "SHINDE",
|
||||||
|
"first_name": "RAM",
|
||||||
|
"middle_name": "VITTHAL",
|
||||||
|
"father_or_husband_name": "VITTHAL",
|
||||||
|
"salutation": "Mr.",
|
||||||
|
"gender": "Male",
|
||||||
|
"dob": "15/06/1980",
|
||||||
|
"age": "46",
|
||||||
|
"id_proof_type": "Aadhaar Card",
|
||||||
|
"mobile_number": "9823456789",
|
||||||
|
"alternate_mobile": "9823456790",
|
||||||
|
"telephone": "020-25432100",
|
||||||
|
"email": "ram.shinde@example.com",
|
||||||
|
"aadhaar_number": "1234 5678 9012",
|
||||||
|
"pan_number": "ABCPS1234F",
|
||||||
|
"address": "Flat No. 4, Shree Ganesh Krupa, Tilak Road, Erandwane, Pune - 411004"
|
||||||
|
},
|
||||||
|
"address_details": {
|
||||||
|
"local_address": "Flat No. 4, Shree Ganesh Krupa, Tilak Road, Erandwane, Pune - 411004",
|
||||||
|
"local_flat_room": "Flat No. 4",
|
||||||
|
"local_premises": "Shree Ganesh Krupa",
|
||||||
|
"local_landmark": "Near Tilak Smarak",
|
||||||
|
"local_road": "Tilak Road",
|
||||||
|
"local_taluka": "Haveli",
|
||||||
|
"local_pincode": "411004",
|
||||||
|
"permanent_address": "At Post Baramati, Tal. Baramati, Dist. Pune, Maharashtra 413102",
|
||||||
|
"perm_flat_room": null,
|
||||||
|
"perm_premises": "At Post Baramati",
|
||||||
|
"perm_landmark": null,
|
||||||
|
"perm_road": null,
|
||||||
|
"perm_taluka": "Baramati",
|
||||||
|
"city_district": "Pune",
|
||||||
|
"perm_state": "Maharashtra",
|
||||||
|
"perm_country": "India",
|
||||||
|
"nationality": "Indian",
|
||||||
|
"pincode": "413102"
|
||||||
|
},
|
||||||
|
"billing_details": {
|
||||||
|
"income_source": "Salary",
|
||||||
|
"monthly_income": "35,000",
|
||||||
|
"bill_payer": "Self",
|
||||||
|
"company_name": null
|
||||||
|
},
|
||||||
|
"representative_details": {
|
||||||
|
"signatory": "Patient",
|
||||||
|
"representative_name": null,
|
||||||
|
"relationship": null
|
||||||
|
},
|
||||||
|
"medical_details": {
|
||||||
|
"symptoms": null,
|
||||||
|
"medical_history": null,
|
||||||
|
"diagnosis": null,
|
||||||
|
"medicines": [],
|
||||||
|
"additional_notes": null
|
||||||
|
},
|
||||||
|
"raw_transcription": "लता मंगेशकर मेडिकल फाऊंडेशनचे\nदीनानाथ मंगेशकर रुग्णालय आणि संशोधन केंद्र\nएरंडवणे, पुणे - ४११० ०४. दूरभाष : ०२० - ४०१५१००० / ४९१५३०००\n\nरुग्ण नावनोंदणी अर्ज (GEN007)\nएमआरडी क्र.: C00000039\nदिनांक: १४/१०/२०२६\n\nरुग्णाचे नाव: राम विठ्ठल शिंदे\nआडनाव: शिदे | पहिले नाव: राम | वडिलांचे नाव: विठ्ल\nलिंग: पुरूष | वय: ४६ वर्षे | जन्मतारीख: १५/६/८०\nस्थानिक पत्ता: फ्लॅट क्र. ४, श्री गणेश कृपा, टिळक रस्ता, एरंडवना, पुना - ४११ ००४\nभ्रमणध्वनी (मोबाईल) क्रमांक: ०९८२३४-५६७८९\nआधार क्रमांक: १२३४५६७८९०१२\nउत्पन्नाचा स्रोत: पगार | मासिक उत्पन्न: ३५,०००\nशुल्क: स्वतः\nRegistration Form [Barcode: C00000039]\nस्वाक्षरी: रुग्ण",
|
||||||
|
"repaired_fields": [
|
||||||
|
{
|
||||||
|
"field": "surname",
|
||||||
|
"original": "शिदे",
|
||||||
|
"repaired": "SHINDE",
|
||||||
|
"note": "Converted surname 'शिदे' to standard English 'SHINDE' (repaired patient handwriting slip)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"field": "middle_name",
|
||||||
|
"original": "विठ्ल",
|
||||||
|
"repaired": "VITTHAL",
|
||||||
|
"note": "Converted name 'विठ्ल' to standard English 'VITTHAL' (repaired missing halant)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"field": "gender",
|
||||||
|
"original": "पुरूष",
|
||||||
|
"repaired": "Male",
|
||||||
|
"note": "Converted 'पुरूष' to standard English 'Male' (corrected typo)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"field": "dob",
|
||||||
|
"original": "१५/६/८०",
|
||||||
|
"repaired": "15/06/1980",
|
||||||
|
"note": "Repaired date format '१५/६/८०' to standard '15/06/1980' (expanded 2-digit year & added leading zeros)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"field": "city_district",
|
||||||
|
"original": "पुना",
|
||||||
|
"repaired": "Pune",
|
||||||
|
"note": "Converted location 'पुना' to standard English 'Pune' (repaired colloquial typo)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"field": "local_address",
|
||||||
|
"original": "फ्लॅट क्र. ४, श्री गणेश कृपा, टिळक रस्ता, एरंडवना, पुना",
|
||||||
|
"repaired": "Flat No. 4, Shree Ganesh Krupa, Tilak Road, Erandwane, Pune",
|
||||||
|
"note": "Converted Marathi address & repaired 'एरंडवना' to standard English 'Erandwane'"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"field": "mobile_number",
|
||||||
|
"original": "०९८२३४-५६७८९",
|
||||||
|
"repaired": "9823456789",
|
||||||
|
"note": "Repaired mobile number to standard clean 10-digit format"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"field": "aadhaar_number",
|
||||||
|
"original": "१२३४५६७८९०१२",
|
||||||
|
"repaired": "1234 5678 9012",
|
||||||
|
"note": "Repaired Aadhaar format to standard 4-4-4 grouping"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"unreadable_fields": [
|
||||||
|
"company_name",
|
||||||
|
"representative_name",
|
||||||
|
"representative_relation"
|
||||||
|
],
|
||||||
|
"validation_warnings": [
|
||||||
|
"🔧 Auto-Repaired 'surname': 'शिदे' → 'SHINDE' (Converted surname 'शिदे' to standard English 'SHINDE' (repaired patient handwriting slip))",
|
||||||
|
"🔧 Auto-Repaired 'middle_name': 'विठ्ल' → 'VITTHAL' (Converted name 'विठ्ल' to standard English 'VITTHAL' (repaired missing halant))",
|
||||||
|
"🔧 Auto-Repaired 'gender': 'पुरूष' → 'Male' (Converted 'पुरूष' to standard English 'Male' (corrected typo))",
|
||||||
|
"🔧 Auto-Repaired 'dob': '१५/६/८०' → '15/06/1980' (Repaired date format '१५/६/८०' to standard '15/06/1980' (expanded 2-digit year & added leading zeros))",
|
||||||
|
"🔧 Auto-Repaired 'city_district': 'पुना' → 'Pune' (Converted location 'पुना' to standard English 'Pune' (repaired colloquial typo))"
|
||||||
|
],
|
||||||
|
"_meta": {
|
||||||
|
"job_id": "sample-dmh-mr-001",
|
||||||
|
"model": "DocVision AI",
|
||||||
|
"api_response_time_seconds": 5.42,
|
||||||
|
"method": "extract",
|
||||||
|
"status": "completed",
|
||||||
|
"fallback_used": false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
{
|
||||||
|
"document_type": "hospital_registration_form",
|
||||||
|
"form_language": "en",
|
||||||
|
"hospital_details": {
|
||||||
|
"hospital_name": "DEENANATH MANGESHKAR HOSPITAL & RESEARCH CENTRE",
|
||||||
|
"mrd_number": "C00000039",
|
||||||
|
"barcode_number": "C00000039",
|
||||||
|
"visit_date": "14/10/2026",
|
||||||
|
"examiner_name": "Sunil Joshi",
|
||||||
|
"registrar_name": "Anita Kulkarni",
|
||||||
|
"department": "OPD Registration",
|
||||||
|
"doctor_name": "Dr. Sachin Deshpande",
|
||||||
|
"remarks": "Urgent examination required"
|
||||||
|
},
|
||||||
|
"patient_details": {
|
||||||
|
"patient_name": "RAM VITTHAL SHINDE",
|
||||||
|
"surname": "SHINDE",
|
||||||
|
"first_name": "RAM",
|
||||||
|
"middle_name": "VITTHAL",
|
||||||
|
"father_or_husband_name": "VITTHAL",
|
||||||
|
"salutation": "Mr.",
|
||||||
|
"gender": "Male",
|
||||||
|
"dob": "15-06-1980",
|
||||||
|
"age": "46",
|
||||||
|
"id_proof_type": "Aadhaar Card",
|
||||||
|
"mobile_number": "9823456789",
|
||||||
|
"alternate_mobile": "9823456790",
|
||||||
|
"telephone": "020-25432100",
|
||||||
|
"email": "ram.shinde@example.com",
|
||||||
|
"aadhaar_number": "1234 5678 9012",
|
||||||
|
"pan_number": "ABCPS1234F",
|
||||||
|
"address": "Flat No 4, Shree Ganesh Krupa, Tilak Road, Erandwane, Pune 411004"
|
||||||
|
},
|
||||||
|
"address_details": {
|
||||||
|
"local_address": "Flat No 4, Shree Ganesh Krupa, Tilak Road, Erandwane, Pune 411004",
|
||||||
|
"local_flat_room": "Flat No 4",
|
||||||
|
"local_premises": "Shree Ganesh Krupa",
|
||||||
|
"local_landmark": "Near Tilak Smarak",
|
||||||
|
"local_road": "Tilak Road",
|
||||||
|
"local_taluka": "Haveli",
|
||||||
|
"local_pincode": "411004",
|
||||||
|
"permanent_address": "At Post Baramati, Tal Baramati, Dist Pune, Maharashtra 413102",
|
||||||
|
"perm_flat_room": null,
|
||||||
|
"perm_premises": "At Post Baramati",
|
||||||
|
"perm_landmark": null,
|
||||||
|
"perm_road": null,
|
||||||
|
"perm_taluka": "Baramati",
|
||||||
|
"city_district": "Pune",
|
||||||
|
"perm_state": "Maharashtra",
|
||||||
|
"perm_country": "India",
|
||||||
|
"nationality": "Indian",
|
||||||
|
"pincode": "413102"
|
||||||
|
},
|
||||||
|
"billing_details": {
|
||||||
|
"income_source": "Salary",
|
||||||
|
"monthly_income": "35,000",
|
||||||
|
"bill_payer": "Self",
|
||||||
|
"company_name": null
|
||||||
|
},
|
||||||
|
"representative_details": {
|
||||||
|
"signatory": "Patient",
|
||||||
|
"representative_name": null,
|
||||||
|
"relationship": null
|
||||||
|
},
|
||||||
|
"medical_details": {
|
||||||
|
"symptoms": null,
|
||||||
|
"medical_history": null,
|
||||||
|
"diagnosis": null,
|
||||||
|
"medicines": [],
|
||||||
|
"additional_notes": null
|
||||||
|
},
|
||||||
|
"raw_transcription": "Lata Mangeshkar Medical Foundation's\nDEENANATH MANGESHKAR HOSPITAL & RESEARCH CENTRE\nErandawane, Pune 411 004.\n\nPATIENT REGISTRATION FORM (GEN007)\nAudited by: Sunil Joshi | Entered by: Anita Kulkarni | Date: 14/10/2026 | MRD No.: C00000039\n\nPatient Name: RAM VITTHAL SHINDE\nLast Name / Surname: SHINDE | First Name: RAM | Middle Name: VITTHAL\nGender: Male | Approximate Age in Years: 46 | Date of Birth: 15-06-1980\nLocal Address: Flat No 4, Shree Ganesh Krupa, Erandwane, Pune 411004\nMobile Number: 9823456789\nAADHAAR Number: 1234 5678 9012\nSource of Income: Salary | Who will pay bills?: Self\nRegistration Form [Barcode: C00000039]\nSignature: Patient",
|
||||||
|
"unreadable_fields": [
|
||||||
|
"company_name",
|
||||||
|
"representative_name",
|
||||||
|
"representative_relation"
|
||||||
|
],
|
||||||
|
"validation_warnings": [],
|
||||||
|
"_meta": {
|
||||||
|
"job_id": "sample-dmh-en-001",
|
||||||
|
"model": "DocVision AI",
|
||||||
|
"api_response_time_seconds": 5.18,
|
||||||
|
"method": "extract",
|
||||||
|
"status": "completed",
|
||||||
|
"fallback_used": false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,367 @@
|
|||||||
|
"""
|
||||||
|
Sarvam AI API client for Document Intelligence.
|
||||||
|
Handles both Extract (schema-based) and Digitise (full OCR) workflows.
|
||||||
|
Both endpoints are asynchronous job-based: submit → poll → fetch results.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
import logging
|
||||||
|
import requests
|
||||||
|
from config import Config
|
||||||
|
from extraction_schema import EXTRACTION_SCHEMA, build_structured_response
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class SarvamAPIError(Exception):
|
||||||
|
"""Custom exception for Sarvam API errors."""
|
||||||
|
|
||||||
|
def __init__(self, message: str, status_code: int = None, response_body: str = None):
|
||||||
|
self.status_code = status_code
|
||||||
|
self.response_body = response_body
|
||||||
|
super().__init__(message)
|
||||||
|
|
||||||
|
|
||||||
|
class SarvamClient:
|
||||||
|
"""Client for interacting with Sarvam AI Document Intelligence API."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.api_key = Config.get_sarvam_api_key()
|
||||||
|
self.base_url = Config.SARVAM_API_BASE_URL
|
||||||
|
self.poll_interval = Config.SARVAM_JOB_POLL_INTERVAL
|
||||||
|
self.max_wait = Config.SARVAM_JOB_MAX_WAIT
|
||||||
|
|
||||||
|
if not self.api_key or self.api_key == "your_sarvam_api_key_here":
|
||||||
|
raise SarvamAPIError(
|
||||||
|
"Vision API key is not configured. "
|
||||||
|
"Please set it in your .env file."
|
||||||
|
)
|
||||||
|
|
||||||
|
def _get_headers(self) -> dict:
|
||||||
|
"""Return authentication headers (no Content-Type — multipart sets its own)."""
|
||||||
|
return {
|
||||||
|
"api-subscription-key": self.api_key
|
||||||
|
}
|
||||||
|
|
||||||
|
def _poll_job_status(self, job_id: str) -> dict:
|
||||||
|
"""
|
||||||
|
Poll the job status endpoint until the job reaches a terminal state.
|
||||||
|
|
||||||
|
Terminal states: completed, partially_completed, failed, rejected
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict with job status information.
|
||||||
|
"""
|
||||||
|
terminal_states = {"completed", "partially_completed", "failed", "rejected"}
|
||||||
|
status_url = f"{self.base_url}/doc-ai/v1/job/{job_id}/status"
|
||||||
|
elapsed = 0
|
||||||
|
|
||||||
|
logger.info(f"Polling job {job_id}...")
|
||||||
|
|
||||||
|
while elapsed < self.max_wait:
|
||||||
|
try:
|
||||||
|
resp = requests.get(status_url, headers=self._get_headers(), timeout=30)
|
||||||
|
resp.raise_for_status()
|
||||||
|
status_data = resp.json()
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
logger.warning(f"Status poll error for job {job_id}: {e}")
|
||||||
|
time.sleep(self.poll_interval)
|
||||||
|
elapsed += self.poll_interval
|
||||||
|
continue
|
||||||
|
|
||||||
|
current_status = status_data.get("status", "").lower()
|
||||||
|
# Also check nested fields — API may use 'job_state' or 'state'
|
||||||
|
if not current_status:
|
||||||
|
current_status = status_data.get("job_state", "").lower()
|
||||||
|
if not current_status:
|
||||||
|
current_status = status_data.get("state", "").lower()
|
||||||
|
|
||||||
|
logger.info(f"Job {job_id} status: {current_status}")
|
||||||
|
|
||||||
|
if current_status in terminal_states:
|
||||||
|
return status_data
|
||||||
|
|
||||||
|
time.sleep(self.poll_interval)
|
||||||
|
elapsed += self.poll_interval
|
||||||
|
|
||||||
|
raise SarvamAPIError(
|
||||||
|
f"Job {job_id} did not complete within {self.max_wait} seconds.",
|
||||||
|
status_code=408
|
||||||
|
)
|
||||||
|
|
||||||
|
def _fetch_job_results(self, job_id: str) -> dict:
|
||||||
|
"""Fetch the results of a completed job."""
|
||||||
|
results_url = f"{self.base_url}/doc-ai/v1/job/{job_id}/results"
|
||||||
|
try:
|
||||||
|
resp = requests.get(
|
||||||
|
results_url,
|
||||||
|
headers=self._get_headers(),
|
||||||
|
timeout=30
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
raise SarvamAPIError(
|
||||||
|
f"Failed to fetch results for job {job_id}: {str(e)}",
|
||||||
|
status_code=getattr(resp, "status_code", None) if 'resp' in dir() else None
|
||||||
|
)
|
||||||
|
|
||||||
|
def extract(
|
||||||
|
self,
|
||||||
|
file_bytes: bytes,
|
||||||
|
filename: str,
|
||||||
|
content_type_mime: str = "image/jpeg",
|
||||||
|
language: str = None
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
Submit a document to the Sarvam Extract endpoint for schema-based
|
||||||
|
key-value extraction of handwritten Marathi & English hospital form fields.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
file_bytes: Raw file bytes.
|
||||||
|
filename: Original filename.
|
||||||
|
content_type_mime: MIME type of the file.
|
||||||
|
language: Document language code (e.g. 'mr-IN', 'en-IN'). Defaults to Config.DOCUMENT_LANGUAGE.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: Structured extraction result matching the application schema.
|
||||||
|
"""
|
||||||
|
start_time = time.time()
|
||||||
|
doc_lang = language if language else Config.DOCUMENT_LANGUAGE
|
||||||
|
|
||||||
|
# Prepare multipart form data
|
||||||
|
files = {
|
||||||
|
"file": (filename, file_bytes, content_type_mime)
|
||||||
|
}
|
||||||
|
data = {
|
||||||
|
"schema": json.dumps(EXTRACTION_SCHEMA),
|
||||||
|
"language": doc_lang,
|
||||||
|
"content_type": Config.CONTENT_TYPE
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(f"Submitting extract job for: {filename} (language: {doc_lang})")
|
||||||
|
|
||||||
|
# Step 1: Submit the job
|
||||||
|
try:
|
||||||
|
resp = requests.post(
|
||||||
|
Config.SARVAM_EXTRACT_URL,
|
||||||
|
headers=self._get_headers(),
|
||||||
|
files=files,
|
||||||
|
data=data,
|
||||||
|
timeout=60
|
||||||
|
)
|
||||||
|
except requests.exceptions.Timeout:
|
||||||
|
raise SarvamAPIError("Request timed out while submitting extraction job.", status_code=408)
|
||||||
|
except requests.exceptions.ConnectionError:
|
||||||
|
raise SarvamAPIError("Could not connect to Vision API. Check your internet connection.", status_code=503)
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
raise SarvamAPIError(f"Request error: {str(e)}")
|
||||||
|
|
||||||
|
if resp.status_code not in (200, 201, 202):
|
||||||
|
raise SarvamAPIError(
|
||||||
|
f"Extract job submission failed: HTTP {resp.status_code}",
|
||||||
|
status_code=resp.status_code,
|
||||||
|
response_body=resp.text
|
||||||
|
)
|
||||||
|
|
||||||
|
job_data = resp.json()
|
||||||
|
job_id = job_data.get("job_id") or job_data.get("id")
|
||||||
|
if not job_id:
|
||||||
|
raise SarvamAPIError(
|
||||||
|
"No job_id returned from extract endpoint.",
|
||||||
|
response_body=json.dumps(job_data)
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(f"Extract job created: {job_id}")
|
||||||
|
|
||||||
|
# Step 2: Poll until completion
|
||||||
|
status_data = self._poll_job_status(job_id)
|
||||||
|
status = (
|
||||||
|
status_data.get("status", "").lower()
|
||||||
|
or status_data.get("job_state", "").lower()
|
||||||
|
or status_data.get("state", "").lower()
|
||||||
|
)
|
||||||
|
|
||||||
|
if status == "failed" or status == "rejected":
|
||||||
|
raise SarvamAPIError(
|
||||||
|
f"Extract job {job_id} {status}.",
|
||||||
|
response_body=json.dumps(status_data)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Step 3: Fetch results
|
||||||
|
results = self._fetch_job_results(job_id)
|
||||||
|
elapsed = round(time.time() - start_time, 2)
|
||||||
|
|
||||||
|
# Parse the extraction result
|
||||||
|
extract_result = results.get("result", results.get("data", results))
|
||||||
|
|
||||||
|
# Build structured response
|
||||||
|
structured = build_structured_response(extract_result)
|
||||||
|
structured["_meta"] = {
|
||||||
|
"job_id": job_id,
|
||||||
|
"model": "DocVision AI",
|
||||||
|
"api_response_time_seconds": elapsed,
|
||||||
|
"method": "extract",
|
||||||
|
"status": status
|
||||||
|
}
|
||||||
|
|
||||||
|
return structured
|
||||||
|
|
||||||
|
def digitise(
|
||||||
|
self,
|
||||||
|
file_bytes: bytes,
|
||||||
|
filename: str,
|
||||||
|
content_type_mime: str = "image/jpeg",
|
||||||
|
language: str = None
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
Submit a document to the Sarvam Digitise endpoint for full OCR.
|
||||||
|
Returns raw transcribed text preserving layout and reading order.
|
||||||
|
|
||||||
|
This is a fallback approach — use extract() for structured field extraction.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
file_bytes: Raw file bytes.
|
||||||
|
filename: Original filename.
|
||||||
|
content_type_mime: MIME type of the file.
|
||||||
|
language: Language code (e.g. 'mr-IN', 'en-IN'). Defaults to Config.DOCUMENT_LANGUAGE.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict with raw transcription and page data.
|
||||||
|
"""
|
||||||
|
start_time = time.time()
|
||||||
|
doc_lang = language if language else Config.DOCUMENT_LANGUAGE
|
||||||
|
|
||||||
|
files = {
|
||||||
|
"file": (filename, file_bytes, content_type_mime)
|
||||||
|
}
|
||||||
|
data = {
|
||||||
|
"language": doc_lang,
|
||||||
|
"content_type": Config.CONTENT_TYPE
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(f"Submitting digitise job for: {filename} (language: {doc_lang})")
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = requests.post(
|
||||||
|
Config.SARVAM_DIGITISE_URL,
|
||||||
|
headers=self._get_headers(),
|
||||||
|
files=files,
|
||||||
|
data=data,
|
||||||
|
timeout=60
|
||||||
|
)
|
||||||
|
except requests.exceptions.Timeout:
|
||||||
|
raise SarvamAPIError("Request timed out while submitting digitise job.", status_code=408)
|
||||||
|
except requests.exceptions.ConnectionError:
|
||||||
|
raise SarvamAPIError("Could not connect to Vision API. Check your internet connection.", status_code=503)
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
raise SarvamAPIError(f"Request error: {str(e)}")
|
||||||
|
|
||||||
|
if resp.status_code not in (200, 201, 202):
|
||||||
|
raise SarvamAPIError(
|
||||||
|
f"Digitise job submission failed: HTTP {resp.status_code}",
|
||||||
|
status_code=resp.status_code,
|
||||||
|
response_body=resp.text
|
||||||
|
)
|
||||||
|
|
||||||
|
job_data = resp.json()
|
||||||
|
job_id = job_data.get("job_id") or job_data.get("id")
|
||||||
|
if not job_id:
|
||||||
|
raise SarvamAPIError(
|
||||||
|
"No job_id returned from digitise endpoint.",
|
||||||
|
response_body=json.dumps(job_data)
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(f"Digitise job created: {job_id}")
|
||||||
|
|
||||||
|
# Poll until completion
|
||||||
|
status_data = self._poll_job_status(job_id)
|
||||||
|
status = (
|
||||||
|
status_data.get("status", "").lower()
|
||||||
|
or status_data.get("job_state", "").lower()
|
||||||
|
or status_data.get("state", "").lower()
|
||||||
|
)
|
||||||
|
|
||||||
|
if status in ("failed", "rejected"):
|
||||||
|
raise SarvamAPIError(
|
||||||
|
f"Digitise job {job_id} {status}.",
|
||||||
|
response_body=json.dumps(status_data)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Fetch results
|
||||||
|
results = self._fetch_job_results(job_id)
|
||||||
|
elapsed = round(time.time() - start_time, 2)
|
||||||
|
|
||||||
|
# Extract text from pages
|
||||||
|
raw_text_parts = []
|
||||||
|
pages = results.get("pages", [])
|
||||||
|
for page in pages:
|
||||||
|
blocks = page.get("blocks", [])
|
||||||
|
for block in blocks:
|
||||||
|
text = block.get("text", "")
|
||||||
|
if text:
|
||||||
|
raw_text_parts.append(text)
|
||||||
|
|
||||||
|
# If no pages structure, try flat text fields
|
||||||
|
if not raw_text_parts:
|
||||||
|
if isinstance(results.get("text"), str):
|
||||||
|
raw_text_parts.append(results["text"])
|
||||||
|
elif isinstance(results.get("content"), str):
|
||||||
|
raw_text_parts.append(results["content"])
|
||||||
|
elif isinstance(results.get("result"), str):
|
||||||
|
raw_text_parts.append(results["result"])
|
||||||
|
|
||||||
|
raw_transcription = "\n".join(raw_text_parts)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"raw_transcription": raw_transcription,
|
||||||
|
"pages": pages,
|
||||||
|
"_meta": {
|
||||||
|
"job_id": job_id,
|
||||||
|
"model": "DocVision AI",
|
||||||
|
"api_response_time_seconds": elapsed,
|
||||||
|
"method": "digitise",
|
||||||
|
"status": status,
|
||||||
|
"page_count": len(pages)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def extract_with_fallback(
|
||||||
|
self,
|
||||||
|
file_bytes: bytes,
|
||||||
|
filename: str,
|
||||||
|
content_type_mime: str = "image/jpeg",
|
||||||
|
language: str = None
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
Try the Extract endpoint first. If it fails, fall back to Digitise
|
||||||
|
for raw OCR transcription.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: Structured result or raw transcription.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
result = self.extract(file_bytes, filename, content_type_mime, language=language)
|
||||||
|
result["_meta"]["fallback_used"] = False
|
||||||
|
return result
|
||||||
|
except SarvamAPIError as e:
|
||||||
|
logger.warning(f"Extract failed, falling back to digitise: {e}")
|
||||||
|
try:
|
||||||
|
digitise_result = self.digitise(file_bytes, filename, content_type_mime, language=language)
|
||||||
|
# Wrap digitise result in the standard structure
|
||||||
|
from extraction_schema import EMPTY_RESPONSE_TEMPLATE
|
||||||
|
import copy
|
||||||
|
structured = copy.deepcopy(EMPTY_RESPONSE_TEMPLATE)
|
||||||
|
structured["raw_transcription"] = digitise_result.get("raw_transcription", "")
|
||||||
|
structured["validation_warnings"].append(
|
||||||
|
"Schema-based extraction failed. Falling back to raw OCR transcription."
|
||||||
|
)
|
||||||
|
structured["_meta"] = digitise_result.get("_meta", {})
|
||||||
|
structured["_meta"]["fallback_used"] = True
|
||||||
|
structured["_meta"]["extract_error"] = str(e)
|
||||||
|
return structured
|
||||||
|
except SarvamAPIError as e2:
|
||||||
|
raise SarvamAPIError(
|
||||||
|
f"Both extract and digitise failed. Extract: {e}. Digitise: {e2}"
|
||||||
|
)
|
||||||
File diff suppressed because it is too large
Load Diff
+1229
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,380 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Marathi Handwritten Hospital Form Extraction</title>
|
||||||
|
<meta name="description"
|
||||||
|
content="Extract handwritten Marathi text from hospital forms using AI Vision Document Intelligence. Supports patient registration, medical notes, and prescriptions in Devanagari script.">
|
||||||
|
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
|
||||||
|
<link rel="icon"
|
||||||
|
href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>📝</text></svg>">
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<!-- ═══ Loading Overlay ═══ -->
|
||||||
|
<div id="loading-overlay" class="loading-overlay">
|
||||||
|
<div class="loading-content">
|
||||||
|
<div class="loading-spinner-large"></div>
|
||||||
|
<div class="loading-text">Processing Document</div>
|
||||||
|
<div class="loading-subtext">Reading handwritten Marathi text...</div>
|
||||||
|
<div id="loading-step" class="loading-step">Initializing...</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="app-container">
|
||||||
|
<!-- ═══ Header ═══ -->
|
||||||
|
<header class="app-header">
|
||||||
|
<div class="header-left">
|
||||||
|
<div class="header-icon-box">📋</div>
|
||||||
|
<div>
|
||||||
|
<h1 class="app-title">
|
||||||
|
Hospital Form Extraction · <span class="marathi">मराठी व इंग्रजी नोंदणी अर्ज</span>
|
||||||
|
</h1>
|
||||||
|
<p class="app-subtitle">
|
||||||
|
Automated extraction for Marathi & English hospital forms with strict zero-hallucination grounding
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="header-badge">
|
||||||
|
<span class="dot"></span>
|
||||||
|
AI Vision · Bilingual OCR
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- ═══ Config Alerts ═══ -->
|
||||||
|
{% if config_errors %}
|
||||||
|
{% for err in config_errors %}
|
||||||
|
<div class="config-alert">
|
||||||
|
<span class="alert-icon">⚠️</span>
|
||||||
|
<div>
|
||||||
|
<strong>Configuration Required:</strong> {{ err }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<!-- ═══ Dashboard ═══ -->
|
||||||
|
<div class="dashboard">
|
||||||
|
|
||||||
|
<!-- ── Upload Card ── -->
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">
|
||||||
|
<div class="card-title">
|
||||||
|
<span class="icon">📄</span>
|
||||||
|
Upload Document
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div id="upload-zone" class="upload-zone">
|
||||||
|
<input type="file" id="file-input" accept=".jpg,.jpeg,.png,.pdf,.bmp,.tiff,.tif">
|
||||||
|
<span class="upload-icon">📋</span>
|
||||||
|
<div class="upload-title">Drop your document here</div>
|
||||||
|
<div class="upload-hint">or click to browse files (English or Marathi Form)</div>
|
||||||
|
<div class="upload-formats">
|
||||||
|
<span class="format-tag">JPG</span>
|
||||||
|
<span class="format-tag">PNG</span>
|
||||||
|
<span class="format-tag">PDF</span>
|
||||||
|
<span class="format-tag">TIFF</span>
|
||||||
|
<span class="format-tag">BMP</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="file-preview" class="file-preview">
|
||||||
|
<span style="font-size:28px">📎</span>
|
||||||
|
<div class="file-info">
|
||||||
|
<div id="file-name" class="file-name"></div>
|
||||||
|
<div id="file-size" class="file-size"></div>
|
||||||
|
</div>
|
||||||
|
<button id="remove-file" class="remove-file" title="Remove file">✕</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Options -->
|
||||||
|
<div class="options-panel">
|
||||||
|
<div class="option-group">
|
||||||
|
<span class="option-label">AI Vision Engine / Model</span>
|
||||||
|
<select id="model-select" class="select-styled">
|
||||||
|
<option value="auto">🤖 Auto (Best Configured Model)</option>
|
||||||
|
<option value="gemini" {% if models_status and models_status.gemini %}selected{% endif %}>🔷 Google Gemini Flash (Vision)</option>
|
||||||
|
<option value="sarvam" {% if models_status and not models_status.gemini and models_status.sarvam %}selected{% endif %}>🔶 DocVision AI (Sarvam Vision)</option>
|
||||||
|
<option value="compare">⚖️ Run Both Models & Compare (Benchmark)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="option-group" id="gemini-model-group">
|
||||||
|
<span class="option-label">Gemini Vision Model</span>
|
||||||
|
<select id="gemini-model-select" class="select-styled">
|
||||||
|
<option value="gemini-3.8-flash" selected>gemini-3.8-flash (Recommended • Active & Tested)</option>
|
||||||
|
<option value="gemini-flash-latest">gemini-flash-latest (Auto Latest Flash • Active)</option>
|
||||||
|
<option value="gemini-3.6-flash">gemini-3.6-flash (Fast • Auto-fallback if quota exceeded)</option>
|
||||||
|
<option value="gemini-3.5-flash">gemini-3.5-flash (Fast • Auto-fallback)</option>
|
||||||
|
<option value="gemini-2.5-flash">gemini-2.5-flash (Active & Stable)</option>
|
||||||
|
<option value="custom">✏️ Custom Model Name...</option>
|
||||||
|
</select>
|
||||||
|
<input type="text" id="gemini-custom-input" class="input-styled" placeholder="e.g. gemini-3.6-flash" style="display:none; margin-top:6px; font-size:12px; padding:6px 10px;">
|
||||||
|
</div>
|
||||||
|
<div class="option-group">
|
||||||
|
<span class="option-label">Form Language</span>
|
||||||
|
<select id="language-select" class="select-styled">
|
||||||
|
<option value="auto">🌐 Auto Detect (Marathi / English)</option>
|
||||||
|
<option value="mr-IN">🇮🇳 Marathi (रुग्ण नावनोंदणी अर्ज)</option>
|
||||||
|
<option value="en-IN">🇬🇧 English (Patient Registration Form)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="option-group">
|
||||||
|
<span class="option-label">Extraction Method</span>
|
||||||
|
<select id="method-select" class="select-styled">
|
||||||
|
<option value="auto">Auto (Extract → Fallback)</option>
|
||||||
|
<option value="extract">Schema-based Extract</option>
|
||||||
|
<option value="digitise">Raw OCR Digitise</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="option-group">
|
||||||
|
<span class="option-label">Preprocessing</span>
|
||||||
|
<div class="toggle-wrapper">
|
||||||
|
<label class="toggle">
|
||||||
|
<input type="checkbox" id="preprocess-toggle">
|
||||||
|
<span class="toggle-track"></span>
|
||||||
|
</label>
|
||||||
|
<span class="toggle-text">Enhance image quality</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Dual Alphabet & Anti-Hallucination Shield -->
|
||||||
|
<div class="anti-hallucination-banner">
|
||||||
|
<div class="banner-top">
|
||||||
|
<div class="banner-title">
|
||||||
|
<span>🛡️</span>
|
||||||
|
<strong>Anti-Hallucination & AI Auto-Repair Active</strong>
|
||||||
|
</div>
|
||||||
|
<span class="banner-tag">STRICT MODE</span>
|
||||||
|
</div>
|
||||||
|
<div class="banner-details">
|
||||||
|
<div><strong>Dual Script Grounding:</strong> Marathi Devanagari (स्वर, व्यंजने, बाराखडी, ०-९) & English Latin (A-Z, a-z, 0-9)</div>
|
||||||
|
<div><strong>Auto English Conversion:</strong> Marathi entries are converted to standard, capitalized English spellings</div>
|
||||||
|
<div><strong>Smart Error Repair:</strong> Corrects patient handwriting typos, phonetic slips, and formatting errors while extracting</div>
|
||||||
|
<div class="banner-rule">⚡ <em>Zero Hallucination: Unfilled boxes and blank dotted lines strictly evaluate to null</em></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Action Buttons -->
|
||||||
|
<div class="btn-group" style="margin-top:20px">
|
||||||
|
<button id="extract-btn" class="btn btn-primary flex-1" disabled>
|
||||||
|
<span class="spinner"></span>
|
||||||
|
<span class="btn-text">🔍 Extract Form Data</span>
|
||||||
|
</button>
|
||||||
|
<button id="reset-btn" class="btn btn-secondary">
|
||||||
|
🔄 Reset
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Error Display -->
|
||||||
|
<div id="error-display" class="error-display">
|
||||||
|
<div class="error-title">❌ Error</div>
|
||||||
|
<div id="error-message" class="error-message"></div>
|
||||||
|
<div id="error-details" class="error-details"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ── Preview Card ── -->
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">
|
||||||
|
<div class="card-title">
|
||||||
|
<span class="icon">🖼️</span>
|
||||||
|
Document Preview
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div id="image-preview-container" class="image-preview-container">
|
||||||
|
<div class="preview-panel">
|
||||||
|
<div class="preview-label">Original</div>
|
||||||
|
<img id="original-image" alt="Original document" src="">
|
||||||
|
</div>
|
||||||
|
<div id="processed-panel" class="preview-panel" style="display:none">
|
||||||
|
<div class="preview-label">Preprocessed</div>
|
||||||
|
<img id="processed-image" alt="Preprocessed document" src="">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="preprocess-info" class="preprocess-info" style="display:none"></div>
|
||||||
|
<div id="no-preview-msg" class="text-center text-muted" style="padding:60px 20px">
|
||||||
|
<span style="font-size:48px;display:block;margin-bottom:12px;opacity:0.3">🖼️</span>
|
||||||
|
Upload a document to see a preview
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ═══ Results Card (full width) ═══ -->
|
||||||
|
<div id="results-container" class="card full-width results-container">
|
||||||
|
<div class="card-header">
|
||||||
|
<div class="card-title">
|
||||||
|
<span class="icon">📊</span>
|
||||||
|
Extraction Results
|
||||||
|
</div>
|
||||||
|
<div class="btn-group">
|
||||||
|
<button id="download-json" class="btn btn-sm btn-secondary">⬇ JSON</button>
|
||||||
|
<button id="download-text" class="btn btn-sm btn-secondary">⬇ Text</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<!-- Stats -->
|
||||||
|
<div class="stats-bar">
|
||||||
|
<div class="stat-chip">
|
||||||
|
<span class="stat-icon">⏱️</span>
|
||||||
|
<div>
|
||||||
|
<div id="stat-time" class="stat-value">—</div>
|
||||||
|
<div class="stat-label">Response Time</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-chip">
|
||||||
|
<span class="stat-icon">🌐</span>
|
||||||
|
<div>
|
||||||
|
<div id="stat-lang" class="stat-value">—</div>
|
||||||
|
<div class="stat-label">Form Language</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-chip">
|
||||||
|
<span class="stat-icon">✅</span>
|
||||||
|
<div>
|
||||||
|
<div id="stat-fields" class="stat-value">—</div>
|
||||||
|
<div class="stat-label">Fields Extracted</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-chip">
|
||||||
|
<span class="stat-icon">✨</span>
|
||||||
|
<div>
|
||||||
|
<div id="stat-repairs" class="stat-value">0</div>
|
||||||
|
<div class="stat-label">Repaired Slips</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-chip">
|
||||||
|
<span class="stat-icon">⚠️</span>
|
||||||
|
<div>
|
||||||
|
<div id="stat-missing" class="stat-value">—</div>
|
||||||
|
<div class="stat-label">Unfilled Fields</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-chip">
|
||||||
|
<span class="stat-icon">🔧</span>
|
||||||
|
<div>
|
||||||
|
<div id="stat-method" class="stat-value">—</div>
|
||||||
|
<div class="stat-label">Method Used</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-chip">
|
||||||
|
<span class="stat-icon">🤖</span>
|
||||||
|
<div>
|
||||||
|
<div id="stat-model" class="stat-value">—</div>
|
||||||
|
<div class="stat-label">AI Engine</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tabs -->
|
||||||
|
<div class="tabs">
|
||||||
|
<button class="tab active" data-tab="fields">📋 Extracted Fields</button>
|
||||||
|
<button class="tab" data-tab="repairs">✨ Auto-Repairs (<span id="tab-repairs-count">0</span>)</button>
|
||||||
|
<button class="tab" data-tab="model-compare" id="tab-btn-model-compare" style="display:none">⚖️ Model Comparison (<span id="model-match-pct">0%</span>)</button>
|
||||||
|
<button class="tab" data-tab="json">🔤 JSON Output</button>
|
||||||
|
<button class="tab" data-tab="transcription">📝 Raw Transcription</button>
|
||||||
|
<button class="tab" data-tab="compare">🔀 Compare</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tab: Fields -->
|
||||||
|
<div id="tab-fields" class="tab-content active">
|
||||||
|
<div id="fields-grid" class="fields-grid"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tab: Repairs -->
|
||||||
|
<div id="tab-repairs" class="tab-content">
|
||||||
|
<div id="repairs-container" class="repairs-container"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tab: Model Comparison -->
|
||||||
|
<div id="tab-model-compare" class="tab-content">
|
||||||
|
<div id="model-compare-container" class="model-compare-container"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tab: JSON -->
|
||||||
|
<div id="tab-json" class="tab-content">
|
||||||
|
<pre id="json-viewer" class="json-viewer"></pre>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tab: Transcription -->
|
||||||
|
<div id="tab-transcription" class="tab-content">
|
||||||
|
<div id="transcription-box" class="transcription-box"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tab: Compare -->
|
||||||
|
<div id="tab-compare" class="tab-content">
|
||||||
|
<p class="text-sm text-muted" style="margin-bottom:12px">
|
||||||
|
Paste a reference JSON (with the same structure) to compare extraction accuracy:
|
||||||
|
</p>
|
||||||
|
<textarea id="compare-textarea" class="compare-textarea"
|
||||||
|
placeholder='{"patient_details":{"patient_name":"राम शिंदे","age":"45 वर्षे",...},...}'></textarea>
|
||||||
|
<button id="compare-btn" class="btn btn-secondary btn-block">
|
||||||
|
🔀 Compare Against Reference
|
||||||
|
</button>
|
||||||
|
<div id="compare-results" class="compare-results"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ═══ Test History Card (full width) ═══ -->
|
||||||
|
<div class="card full-width">
|
||||||
|
<div class="card-header">
|
||||||
|
<div class="card-title">
|
||||||
|
<span class="icon">📜</span>
|
||||||
|
Persistent Test History
|
||||||
|
<span id="history-count" class="badge-count">0 tests</span>
|
||||||
|
</div>
|
||||||
|
<div class="card-header-actions">
|
||||||
|
<a href="/api/test-results/export/csv" class="btn btn-sm btn-secondary"
|
||||||
|
title="Download CSV summary of test runs">📥 Export CSV</a>
|
||||||
|
<a href="/api/test-results/export/json" class="btn btn-sm btn-secondary"
|
||||||
|
title="Download full JSON dataset">📥 Export JSON</a>
|
||||||
|
<button id="clear-history-btn" class="btn btn-sm btn-danger" onclick="clearAllHistory()"
|
||||||
|
title="Clear all stored test history">🗑️ Clear History</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="history-table-wrapper">
|
||||||
|
<table class="history-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Document & Date</th>
|
||||||
|
<th>Model Engine</th>
|
||||||
|
<th>Method</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th>API Time</th>
|
||||||
|
<th>Extracted</th>
|
||||||
|
<th>Missing</th>
|
||||||
|
<th>Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="history-body">
|
||||||
|
<tr>
|
||||||
|
<td colspan="8" class="text-center text-muted" style="padding:40px">
|
||||||
|
No tests run yet. Upload a document and extract to begin.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
<!-- /dashboard -->
|
||||||
|
|
||||||
|
<!-- Footer -->
|
||||||
|
<footer class="app-footer">
|
||||||
|
Automated Healthcare Document Intelligence · <strong>Marathi (मराठी) Vision OCR</strong>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script src="{{ url_for('static', filename='js/app.js') }}"></script>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,551 @@
|
|||||||
|
"""
|
||||||
|
Text Repair & Marathi-to-English Conversion Engine.
|
||||||
|
Handles:
|
||||||
|
1. Converting Marathi Devanagari script into standard English spellings.
|
||||||
|
2. Smart error correction / repair of patient handwriting mistakes (typos, phonetic slips, missing letters).
|
||||||
|
3. Date, mobile, pincode, Aadhaar, and PAN normalization.
|
||||||
|
4. Checkbox & categorical options translation and standardization.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
from typing import Tuple, Optional, List, Dict, Any
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
# Devanagari Character Grounding Maps
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
DEVANAGARI_VOWELS = {
|
||||||
|
'अ': 'a', 'आ': 'aa', 'इ': 'i', 'ई': 'ee', 'उ': 'u', 'ऊ': 'oo',
|
||||||
|
'ऋ': 'ru', 'ऌ': 'lu', 'ए': 'e', 'ऐ': 'ai', 'ओ': 'o', 'औ': 'au',
|
||||||
|
'अं': 'am', 'अः': 'ah', 'ॲ': 'a', 'ऑ': 'o'
|
||||||
|
}
|
||||||
|
|
||||||
|
DEVANAGARI_CONSONANTS = {
|
||||||
|
'क': 'k', 'ख': 'kh', 'ग': 'g', 'घ': 'gh', 'ङ': 'ng',
|
||||||
|
'च': 'ch', 'छ': 'chh', 'ज': 'j', 'झ': 'jh', 'ञ': 'ny',
|
||||||
|
'ट': 't', 'ठ': 'th', 'ड': 'd', 'ढ': 'dh', 'ण': 'n',
|
||||||
|
'त': 't', 'थ': 'th', 'द': 'd', 'ध': 'dh', 'न': 'n',
|
||||||
|
'प': 'p', 'फ': 'ph', 'ब': 'b', 'भ': 'bh', 'म': 'm',
|
||||||
|
'य': 'y', 'र': 'r', 'ल': 'l', 'व': 'v', 'श': 'sh',
|
||||||
|
'ष': 'sh', 'स': 's', 'ह': 'h', 'ळ': 'l', 'क्ष': 'ksh', 'ज्ञ': 'dny'
|
||||||
|
}
|
||||||
|
|
||||||
|
DEVANAGARI_MATRAS = {
|
||||||
|
'ा': 'a', 'ि': 'i', 'ी': 'i', 'ु': 'u', 'ू': 'u', 'ृ': 'ru',
|
||||||
|
'ॄ': 'roo', 'े': 'e', 'ै': 'ai', 'ो': 'o', 'ौ': 'au', 'ं': 'n',
|
||||||
|
'ः': 'h', 'ॅ': 'a', 'ॉ': 'o', '़': '', '्': ''
|
||||||
|
}
|
||||||
|
|
||||||
|
MARATHI_DIGITS = {
|
||||||
|
'०': '0', '१': '1', '२': '2', '३': '3', '४': '4',
|
||||||
|
'५': '5', '६': '6', '७': '7', '८': '8', '९': '9'
|
||||||
|
}
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
# Common Misspelling & Patient Mistake Repair Dictionaries
|
||||||
|
# ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
# Known Surnames & Patient Misspelling Corrections -> Standard English
|
||||||
|
SURNAME_REPAIRS: Dict[str, str] = {
|
||||||
|
# Shinde variants
|
||||||
|
'शिंदे': 'SHINDE', 'शिदे': 'SHINDE', 'शिन्दे': 'SHINDE', 'shinde': 'SHINDE', 'sinde': 'SHINDE',
|
||||||
|
# Patil variants
|
||||||
|
'पाटील': 'PATIL', 'पाटिल': 'PATIL', 'patil': 'PATIL', 'paatil': 'PATIL',
|
||||||
|
# Pawar variants
|
||||||
|
'पवार': 'PAWAR', 'पवाऱ': 'PAWAR', 'pawar': 'PAWAR',
|
||||||
|
# Kadam variants
|
||||||
|
'कदम': 'KADAM', 'कदंम': 'KADAM', 'kadam': 'KADAM',
|
||||||
|
# Jadhav variants
|
||||||
|
'जाधव': 'JADHAV', 'जादव': 'JADHAV', 'jadhav': 'JADHAV', 'jadav': 'JADHAV',
|
||||||
|
# Deshmukh variants
|
||||||
|
'देशमुख': 'DESHMUKH', 'देशमुक': 'DESHMUKH', 'deshmukh': 'DESHMUKH',
|
||||||
|
# Kulkarni variants
|
||||||
|
'कुलकर्णी': 'KULKARNI', 'कुलकणी': 'KULKARNI', 'kulkarni': 'KULKARNI',
|
||||||
|
# Joshi variants
|
||||||
|
'जोशी': 'JOSHI', 'जोषी': 'JOSHI', 'joshi': 'JOSHI',
|
||||||
|
# Gaikwad variants
|
||||||
|
'गायकवाड': 'GAIKWAD', 'गायकुवाड': 'GAIKWAD', 'गायकवाड़': 'GAIKWAD', 'gaikwad': 'GAIKWAD',
|
||||||
|
# Chavan variants
|
||||||
|
'चव्हाण': 'CHAVAN', 'चव्हान': 'CHAVAN', 'चव्हण': 'CHAVAN', 'chavan': 'CHAVAN', 'chavhan': 'CHAVAN',
|
||||||
|
# More variants
|
||||||
|
'मोरे': 'MORE', 'मोऱे': 'MORE', 'more': 'MORE',
|
||||||
|
# Bhosale variants
|
||||||
|
'भोसले': 'BHOSALE', 'भोसलें': 'BHOSALE', 'भोसले': 'BHOSALE', 'bhosale': 'BHOSALE', 'bhosle': 'BHOSALE',
|
||||||
|
# Deshpande variants
|
||||||
|
'देशपांडे': 'DESHPANDE', 'देशपाडे': 'DESHPANDE', 'deshpande': 'DESHPANDE',
|
||||||
|
# Wagh variants
|
||||||
|
'वाघ': 'WAGH', 'वाग': 'WAGH', 'wagh': 'WAGH',
|
||||||
|
# Shah variants
|
||||||
|
'शहा': 'SHAH', 'शाह': 'SHAH', 'shah': 'SHAH',
|
||||||
|
# Mane variants
|
||||||
|
'माने': 'MANE', 'mane': 'MANE',
|
||||||
|
# Sawant variants
|
||||||
|
'सावंत': 'SAWANT', 'सावत': 'SAWANT', 'sawant': 'SAWANT',
|
||||||
|
# Tambade variants
|
||||||
|
'तांबडे': 'TAMBADE', 'तांबडे': 'TAMBADE', 'tambade': 'TAMBADE',
|
||||||
|
# Kamble variants
|
||||||
|
'कांबळे': 'KAMBLE', 'कांबले': 'KAMBLE', 'kamble': 'KAMBLE',
|
||||||
|
# Suryavanshi variants
|
||||||
|
'सूर्यवंशी': 'SURYAVANSHI', 'सुर्यवंशी': 'SURYAVANSHI', 'suryavanshi': 'SURYAVANSHI'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Known First / Middle Names & Patient Typo Corrections -> Standard English
|
||||||
|
NAME_REPAIRS: Dict[str, str] = {
|
||||||
|
'राम': 'RAM', 'ram': 'RAM',
|
||||||
|
'विठ्ठल': 'VITTHAL', 'विठ्ल': 'VITTHAL', 'विठल': 'VITTHAL', 'vitthal': 'VITTHAL', 'vithal': 'VITTHAL',
|
||||||
|
'सचिन': 'SACHIN', 'sachin': 'SACHIN',
|
||||||
|
'सुनील': 'SUNIL', 'सुनिल': 'SUNIL', 'sunil': 'SUNIL',
|
||||||
|
'अनिता': 'ANITA', 'anita': 'ANITA',
|
||||||
|
'गणेश': 'GANESH', 'गनेश': 'GANESH', 'ganesh': 'GANESH',
|
||||||
|
'दत्तात्रय': 'DATTATRAYA', 'दतात्रय': 'DATTATRAYA', 'dattatraya': 'DATTATRAYA', 'dattatreya': 'DATTATRAYA',
|
||||||
|
'ज्ञानेश्वर': 'DNYANESHWAR', 'ज्ञानेश्वर': 'DNYANESHWAR', 'dnyaneshwar': 'DNYANESHWAR',
|
||||||
|
'संतोष': 'SANTOSH', 'सतोष': 'SANTOSH', 'santosh': 'SANTOSH',
|
||||||
|
'संजय': 'SANJAY', 'sanjay': 'SANJAY',
|
||||||
|
'राहुल': 'RAHUL', 'rahul': 'RAHUL',
|
||||||
|
'अमित': 'AMIT', 'amit': 'AMIT',
|
||||||
|
'प्रदीप': 'PRADEEP', 'pradeep': 'PRADEEP',
|
||||||
|
'सुरेश': 'SURESH', 'suresh': 'SURESH',
|
||||||
|
'रमेश': 'RAMESH', 'ramesh': 'RAMESH',
|
||||||
|
'प्रशांत': 'PRASHANT', 'prashant': 'PRASHANT',
|
||||||
|
'विकास': 'VIKAS', 'vikas': 'VIKAS',
|
||||||
|
'अमोल': 'AMOL', 'amol': 'AMOL',
|
||||||
|
'सुप्रिया': 'SUPRIYA', 'supriya': 'SUPRIYA',
|
||||||
|
'प्रियांका': 'PRIYANKA', 'प्रियंका': 'PRIYANKA', 'priyanka': 'PRIYANKA',
|
||||||
|
'पूजा': 'POOJA', 'pooja': 'POOJA',
|
||||||
|
'स्नेहा': 'SNEHA', 'sneha': 'SNEHA',
|
||||||
|
'अजिंक्य': 'AJINKYA', 'ajinkya': 'AJINKYA',
|
||||||
|
'नितीन': 'NITIN', 'nitin': 'NITIN',
|
||||||
|
'अशोक': 'ASHOK', 'ashok': 'ASHOK',
|
||||||
|
'महेश': 'MAHESH', 'mahesh': 'MAHESH'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Known Locations & Address Parts -> Standard English
|
||||||
|
LOCATION_REPAIRS: Dict[str, str] = {
|
||||||
|
# Pune & variants
|
||||||
|
'पुणे': 'Pune', 'पुना': 'Pune', 'पुण': 'Pune', 'poona': 'Pune', 'pune': 'Pune',
|
||||||
|
# Erandwane & variants
|
||||||
|
'एरंडवणे': 'Erandwane', 'एरंडवना': 'Erandwane', 'एरंडवन': 'Erandwane', 'erandavane': 'Erandwane', 'erandwana': 'Erandwane',
|
||||||
|
# Kothrud & variants
|
||||||
|
'कोथरूड': 'Kothrud', 'कोतरुड': 'Kothrud', 'कोथरुड': 'Kothrud', 'kothrud': 'Kothrud', 'kotrud': 'Kothrud',
|
||||||
|
# Shivajinagar
|
||||||
|
'शिवाजीनगर': 'Shivajinagar', 'शिवाजी नगर': 'Shivajinagar', 'shivajinagar': 'Shivajinagar',
|
||||||
|
# Deccan
|
||||||
|
'डेक्कन': 'Deccan', 'डेकन': 'Deccan', 'deccan': 'Deccan',
|
||||||
|
# Swargate
|
||||||
|
'स्वारगेट': 'Swargate', 'स्वार गेट': 'Swargate', 'swargate': 'Swargate',
|
||||||
|
# Haveli
|
||||||
|
'हवेली': 'Haveli', 'haveli': 'Haveli',
|
||||||
|
# Baramati
|
||||||
|
'बारामती': 'Baramati', 'baramati': 'Baramati',
|
||||||
|
# Hadapsar
|
||||||
|
'हडपसर': 'Hadapsar', 'hadapsar': 'Hadapsar',
|
||||||
|
# Baner
|
||||||
|
'बाणेर': 'Baner', 'बानेर': 'Baner', 'baner': 'Baner',
|
||||||
|
# Wakad
|
||||||
|
'वाकड': 'Wakad', 'वाकड़': 'Wakad', 'wakad': 'Wakad',
|
||||||
|
# Aundh
|
||||||
|
'औंध': 'Aundh', 'aundh': 'Aundh',
|
||||||
|
# Katraj
|
||||||
|
'कात्रज': 'Katraj', 'katraj': 'Katraj',
|
||||||
|
# Sinhagad
|
||||||
|
'सिंहगड': 'Sinhagad', 'सिंहगड रस्ता': 'Sinhagad Road', 'sinhagad': 'Sinhagad',
|
||||||
|
# Tilak Road
|
||||||
|
'टिळक रस्ता': 'Tilak Road', 'टिळक रोड': 'Tilak Road', 'tilak road': 'Tilak Road',
|
||||||
|
# Karve Road
|
||||||
|
'कर्वे रस्ता': 'Karve Road', 'कर्वे नगर': 'Karve Nagar', 'karve road': 'Karve Road',
|
||||||
|
# FC Road
|
||||||
|
'फर्ग्युसन': 'FC Road', 'fc road': 'FC Road',
|
||||||
|
# Pimpri-Chinchwad
|
||||||
|
'पिंपरी': 'Pimpri', 'चिंचवड': 'Chinchwad', 'pimpri': 'Pimpri', 'chinchwad': 'Chinchwad',
|
||||||
|
# Satara, Solapur, Kolhapur
|
||||||
|
'सातारा': 'Satara', 'सोलापूर': 'Solapur', 'कोल्हापूर': 'Kolhapur',
|
||||||
|
# Nagpur, Nashik, Mumbai, Thane
|
||||||
|
'नागपूर': 'Nagpur', 'नाशिक': 'Nashik', 'मुंबई': 'Mumbai', 'ठाणे': 'Thane',
|
||||||
|
# State & Country
|
||||||
|
'महाराष्ट्र': 'Maharashtra', 'महाष्ट्र': 'Maharashtra', 'महाराट्र': 'Maharashtra', 'maharashtra': 'Maharashtra',
|
||||||
|
'भारत': 'India', 'इंडिया': 'India', 'india': 'India',
|
||||||
|
# Hospital names
|
||||||
|
'दीनानाथ मंगेशकर रुग्णालय आणि संशोधन केंद्र': 'DEENANATH MANGESHKAR HOSPITAL & RESEARCH CENTRE',
|
||||||
|
'दीनानाथ मंगेशकर रुग्णालय': 'DEENANATH MANGESHKAR HOSPITAL',
|
||||||
|
'लंगेशकर': 'Mangeshkar'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Categorical Checkboxes & Form Options
|
||||||
|
OPTIONS_MAP: Dict[str, str] = {
|
||||||
|
# Gender
|
||||||
|
'पुरुष': 'Male', 'पुरूष': 'Male', 'पूरुष': 'Male', 'male': 'Male', 'm': 'Male',
|
||||||
|
'स्त्री': 'Female', 'महिला': 'Female', 'स्त्रि': 'Female', 'female': 'Female', 'f': 'Female',
|
||||||
|
'तृतीयपंथी': 'Transgender', 'transgender': 'Transgender', 'tg': 'Transgender',
|
||||||
|
|
||||||
|
# Salutation / Title
|
||||||
|
'श्री': 'Mr.', 'श्री.': 'Mr.', 'mr': 'Mr.', 'mr.': 'Mr.',
|
||||||
|
'सौ': 'Mrs.', 'सौ.': 'Mrs.', 'mrs': 'Mrs.', 'mrs.': 'Mrs.',
|
||||||
|
'श्रीमती': 'Smt.', 'श्रीमती.': 'Smt.', 'smt': 'Smt.', 'smt.': 'Smt.',
|
||||||
|
'कु': 'Miss', 'कुमारी': 'Miss', 'miss': 'Miss', 'miss.': 'Miss',
|
||||||
|
'डॉ': 'Dr.', 'डॉ.': 'Dr.', 'dr': 'Dr.', 'dr.': 'Dr.',
|
||||||
|
'मास्टर': 'Mast.', 'mast': 'Mast.', 'mast.': 'Mast.',
|
||||||
|
'b/o': 'B/o', 'fetus of': 'Fetus of', 'mx': 'Mx',
|
||||||
|
|
||||||
|
# ID Proof
|
||||||
|
'आधार कार्ड': 'Aadhaar Card', 'आधारकार्ड': 'Aadhaar Card', 'आधार': 'Aadhaar Card', 'aadhaar card': 'Aadhaar Card', 'aadhaar': 'Aadhaar Card',
|
||||||
|
'पॅन कार्ड': 'PAN Card', 'पॅनकार्ड': 'PAN Card', 'पॅन': 'PAN Card', 'pan card': 'PAN Card', 'pan': 'PAN Card',
|
||||||
|
'मतदार ओळखपत्र': 'Election Card', 'मतदान कार्ड': 'Election Card', 'election card': 'Election Card', 'voter id': 'Election Card',
|
||||||
|
'चालक परवाना': 'Driving License', 'ड्रायव्हिंग लायसन्स': 'Driving License', 'driving license': 'Driving License',
|
||||||
|
'पासपोर्ट': 'Passport', 'passport': 'Passport',
|
||||||
|
'जन्म प्रमाणपत्र': 'Birth Certificate', 'जन्म दाखला': 'Birth Certificate', 'birth certificate': 'Birth Certificate',
|
||||||
|
|
||||||
|
# Income Source
|
||||||
|
'पगार': 'Salary', 'नोकरी': 'Salary', 'salary': 'Salary',
|
||||||
|
'उद्योग वा व्यवसाय': 'Business / Profession', 'उद्योग': 'Business', 'व्यवसाय': 'Profession', 'धंदा': 'Business',
|
||||||
|
'business / profession': 'Business / Profession', 'business': 'Business',
|
||||||
|
'अन्य स्रोत': 'Other Sources', 'इतर': 'Other Sources', 'other sources': 'Other Sources',
|
||||||
|
'उत्पन्न नाही': 'No Income', 'काही नाही': 'No Income', 'no income': 'No Income',
|
||||||
|
|
||||||
|
# Bill Payer
|
||||||
|
'स्वतः': 'Self', 'स्वत': 'Self', 'self': 'Self',
|
||||||
|
'कंपनी': 'Company', 'कंपनीने': 'Company', 'company': 'Company',
|
||||||
|
|
||||||
|
# Signatory
|
||||||
|
'रुग्ण': 'Patient', 'patient': 'Patient',
|
||||||
|
'प्रतिनिधी': 'Representative', 'representative': 'Representative',
|
||||||
|
|
||||||
|
# Relation to Patient
|
||||||
|
'मुलगा': 'Son', 'son': 'Son',
|
||||||
|
'मुलगी': 'Daughter', 'daughter': 'Daughter',
|
||||||
|
'पती': 'Husband', 'husband': 'Husband',
|
||||||
|
'पत्नी': 'Wife', 'wife': 'Wife',
|
||||||
|
'आई': 'Mother', 'mother': 'Mother',
|
||||||
|
'वडील': 'Father', 'father': 'Father',
|
||||||
|
'भाऊ': 'Brother', 'brother': 'Brother',
|
||||||
|
'बहीण': 'Sister', 'sister': 'Sister',
|
||||||
|
|
||||||
|
# Nationality
|
||||||
|
'भारतीय': 'Indian', 'indian': 'Indian'
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class TextRepairEngine:
|
||||||
|
"""
|
||||||
|
Engine for converting Marathi Devanagari text into standard English spellings
|
||||||
|
and repairing patient handwriting mistakes (typos, phonetic slips, bad formatting).
|
||||||
|
"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def has_devanagari(text: str) -> bool:
|
||||||
|
"""Check if string contains any Devanagari characters."""
|
||||||
|
if not text or not isinstance(text, str):
|
||||||
|
return False
|
||||||
|
return bool(re.search(r'[\u0900-\u097F]', text))
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def devanagari_to_arabic_digits(cls, text: str) -> str:
|
||||||
|
"""Convert all Devanagari digits (०-९) to standard digits (0-9)."""
|
||||||
|
if not text or not isinstance(text, str):
|
||||||
|
return text
|
||||||
|
res = []
|
||||||
|
for ch in text:
|
||||||
|
res.append(MARATHI_DIGITS.get(ch, ch))
|
||||||
|
return "".join(res)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def phonetic_transliterate(cls, text: str) -> str:
|
||||||
|
"""
|
||||||
|
Phonetically transliterate any Marathi Devanagari text into readable English.
|
||||||
|
Respects Marathi schwa deletion (word-final consonant doesn't take implicit 'a').
|
||||||
|
"""
|
||||||
|
if not text or not isinstance(text, str):
|
||||||
|
return text
|
||||||
|
|
||||||
|
# Convert digits first
|
||||||
|
text = cls.devanagari_to_arabic_digits(text)
|
||||||
|
out = []
|
||||||
|
i = 0
|
||||||
|
n = len(text)
|
||||||
|
|
||||||
|
while i < n:
|
||||||
|
ch = text[i]
|
||||||
|
next_ch = text[i + 1] if i + 1 < n else ''
|
||||||
|
|
||||||
|
if ch in DEVANAGARI_VOWELS:
|
||||||
|
out.append(DEVANAGARI_VOWELS[ch])
|
||||||
|
elif ch in DEVANAGARI_CONSONANTS:
|
||||||
|
base = DEVANAGARI_CONSONANTS[ch]
|
||||||
|
if next_ch == '्': # Conjunct / Halant
|
||||||
|
out.append(base)
|
||||||
|
i += 1 # Skip the halant character
|
||||||
|
elif next_ch in DEVANAGARI_MATRAS:
|
||||||
|
matra_val = DEVANAGARI_MATRAS[next_ch]
|
||||||
|
out.append(base + matra_val)
|
||||||
|
i += 1 # Skip the matra character
|
||||||
|
else:
|
||||||
|
# In Marathi phonetics, word-final consonant drops implicit 'a'
|
||||||
|
is_word_end = (i + 1 == n) or text[i + 1] in ' \t\n,.-/()&|;:_'
|
||||||
|
out.append(base if is_word_end else base + 'a')
|
||||||
|
elif ch in DEVANAGARI_MATRAS:
|
||||||
|
out.append(DEVANAGARI_MATRAS[ch])
|
||||||
|
else:
|
||||||
|
out.append(ch)
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
res = "".join(out)
|
||||||
|
# Clean up any duplicate spaces or artifacts
|
||||||
|
res = re.sub(r'\s+', ' ', res).strip()
|
||||||
|
return res
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def repair_date(cls, val: str) -> Tuple[Optional[str], Optional[str]]:
|
||||||
|
"""
|
||||||
|
Repair patient date errors (e.g. '15.06.80', '15-6-1980', '१५/०६/१९८०', '5/4/1990').
|
||||||
|
Normalizes into standard DD/MM/YYYY.
|
||||||
|
"""
|
||||||
|
if not val or not isinstance(val, str):
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
cleaned = cls.devanagari_to_arabic_digits(val.strip())
|
||||||
|
# Replace dots, dashes, underscores with slashes
|
||||||
|
norm = re.sub(r'[\.\-\_]+', '/', cleaned)
|
||||||
|
m = re.match(r'^(\d{1,2})\/(\d{1,2})\/(\d{2,4})$', norm)
|
||||||
|
if m:
|
||||||
|
d, mth, y = m.group(1), m.group(2), m.group(3)
|
||||||
|
# Add leading zeros
|
||||||
|
d_str = d.zfill(2)
|
||||||
|
m_str = mth.zfill(2)
|
||||||
|
# Expand 2-digit year
|
||||||
|
if len(y) == 2:
|
||||||
|
y_int = int(y)
|
||||||
|
# If 26 or less, assume 2000s; otherwise 1900s
|
||||||
|
y_str = f"20{y}" if y_int <= 26 else f"19{y}"
|
||||||
|
repaired = f"{d_str}/{m_str}/{y_str}"
|
||||||
|
return repaired, f"Repaired date format '{val}' to standard '{repaired}' (expanded 2-digit year)"
|
||||||
|
repaired = f"{d_str}/{m_str}/{y}"
|
||||||
|
if repaired != val:
|
||||||
|
return repaired, f"Repaired date format '{val}' to standard '{repaired}'"
|
||||||
|
return repaired, None
|
||||||
|
|
||||||
|
return val, None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def repair_phone(cls, val: str) -> Tuple[Optional[str], Optional[str]]:
|
||||||
|
"""
|
||||||
|
Repair phone/mobile number (removes dashes, spaces, leading 0 or +91).
|
||||||
|
Ensures clean 10-digit format.
|
||||||
|
"""
|
||||||
|
if not val or not isinstance(val, str):
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
cleaned = cls.devanagari_to_arabic_digits(val.strip())
|
||||||
|
# Keep only digits
|
||||||
|
digits = re.sub(r'\D', '', cleaned)
|
||||||
|
if len(digits) == 12 and digits.startswith('91'):
|
||||||
|
digits = digits[2:]
|
||||||
|
elif len(digits) == 11 and digits.startswith('0'):
|
||||||
|
digits = digits[1:]
|
||||||
|
|
||||||
|
if len(digits) == 10:
|
||||||
|
if digits != val:
|
||||||
|
return digits, f"Repaired mobile number '{val}' to standard 10-digit format '{digits}'"
|
||||||
|
return digits, None
|
||||||
|
|
||||||
|
return val, None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def repair_pincode(cls, val: str) -> Tuple[Optional[str], Optional[str]]:
|
||||||
|
"""Repair 6-digit PIN code."""
|
||||||
|
if not val or not isinstance(val, str):
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
cleaned = cls.devanagari_to_arabic_digits(val.strip())
|
||||||
|
digits = re.sub(r'\D', '', cleaned)
|
||||||
|
if len(digits) == 6:
|
||||||
|
if digits != val:
|
||||||
|
return digits, f"Repaired PIN code '{val}' to 6-digit '{digits}'"
|
||||||
|
return digits, None
|
||||||
|
return val, None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def repair_aadhaar(cls, val: str) -> Tuple[Optional[str], Optional[str]]:
|
||||||
|
"""Repair 12-digit Aadhaar number into standard 4-4-4 grouping."""
|
||||||
|
if not val or not isinstance(val, str):
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
cleaned = cls.devanagari_to_arabic_digits(val.strip())
|
||||||
|
digits = re.sub(r'\D', '', cleaned)
|
||||||
|
if len(digits) == 12:
|
||||||
|
formatted = f"{digits[0:4]} {digits[4:8]} {digits[8:12]}"
|
||||||
|
if formatted != val:
|
||||||
|
return formatted, f"Repaired Aadhaar format to standard 4-4-4: '{formatted}'"
|
||||||
|
return formatted, None
|
||||||
|
return val, None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def repair_pan(cls, val: str) -> Tuple[Optional[str], Optional[str]]:
|
||||||
|
"""Repair 10-character PAN number into standard uppercase alphanumeric."""
|
||||||
|
if not val or not isinstance(val, str):
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
cleaned = re.sub(r'[\s\-_]+', '', val.strip()).upper()
|
||||||
|
if len(cleaned) == 10 and re.match(r'^[A-Z]{5}[0-9]{4}[A-Z]$', cleaned):
|
||||||
|
if cleaned != val:
|
||||||
|
return cleaned, f"Repaired PAN format to standard uppercase '{cleaned}'"
|
||||||
|
return cleaned, None
|
||||||
|
return val.upper(), None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def convert_and_repair(
|
||||||
|
cls,
|
||||||
|
field_name: str,
|
||||||
|
val: Any
|
||||||
|
) -> Tuple[Any, Optional[str]]:
|
||||||
|
"""
|
||||||
|
Main conversion and repair pipeline:
|
||||||
|
1. Checks categorical options (Gender, Salutation, ID proof, Income, Signatory, etc.).
|
||||||
|
2. Checks numerical / date fields (DOB, Age, Mobile, Aadhaar, PAN, Pincode).
|
||||||
|
3. Checks Surnames & Names dictionary with typo correction.
|
||||||
|
4. Checks Locations & Addresses dictionary with typo correction.
|
||||||
|
5. Performs general phonetic transliteration if still in Marathi Devanagari.
|
||||||
|
6. Returns (repaired_english_value, repair_note).
|
||||||
|
"""
|
||||||
|
if val is None or val == "":
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
if isinstance(val, (int, float)):
|
||||||
|
return str(val), None
|
||||||
|
|
||||||
|
if not isinstance(val, str):
|
||||||
|
return val, None
|
||||||
|
|
||||||
|
val_str = val.strip()
|
||||||
|
lower_val = val_str.lower()
|
||||||
|
|
||||||
|
# Check date fields
|
||||||
|
if field_name in ('dob', 'visit_date'):
|
||||||
|
return cls.repair_date(val_str)
|
||||||
|
|
||||||
|
# Check age
|
||||||
|
if field_name == 'age':
|
||||||
|
cleaned = cls.devanagari_to_arabic_digits(val_str)
|
||||||
|
digits = re.sub(r'\D', '', cleaned)
|
||||||
|
if digits:
|
||||||
|
if digits != val_str:
|
||||||
|
return digits, f"Normalized age '{val_str}' to '{digits}'"
|
||||||
|
return digits, None
|
||||||
|
return val_str, None
|
||||||
|
|
||||||
|
# Check mobile / telephone
|
||||||
|
if field_name in ('mobile_number', 'alternate_mobile', 'telephone'):
|
||||||
|
return cls.repair_phone(val_str)
|
||||||
|
|
||||||
|
# Check pincode
|
||||||
|
if field_name in ('pincode', 'local_pincode'):
|
||||||
|
return cls.repair_pincode(val_str)
|
||||||
|
|
||||||
|
# Check Aadhaar
|
||||||
|
if field_name == 'aadhaar_number':
|
||||||
|
return cls.repair_aadhaar(val_str)
|
||||||
|
|
||||||
|
# Check PAN
|
||||||
|
if field_name == 'pan_number':
|
||||||
|
return cls.repair_pan(val_str)
|
||||||
|
|
||||||
|
# Check Categorical Options (Gender, Title, ID Proof, Income, Bill Payer, Signatory, Relationship)
|
||||||
|
if lower_val in OPTIONS_MAP:
|
||||||
|
standard = OPTIONS_MAP[lower_val]
|
||||||
|
note = f"Converted '{val_str}' to standard English '{standard}'" if cls.has_devanagari(val_str) or lower_val != standard.lower() else None
|
||||||
|
return standard, note
|
||||||
|
|
||||||
|
# Check Surnames
|
||||||
|
if field_name == 'surname':
|
||||||
|
if lower_val in SURNAME_REPAIRS:
|
||||||
|
standard = SURNAME_REPAIRS[lower_val]
|
||||||
|
return standard, f"Converted surname '{val_str}' to standard English '{standard}' (repaired handwriting mistake)"
|
||||||
|
# If Marathi Devanagari, transliterate and capitalize
|
||||||
|
if cls.has_devanagari(val_str):
|
||||||
|
trans = cls.phonetic_transliterate(val_str).upper()
|
||||||
|
return trans, f"Transliterated Marathi surname '{val_str}' into English '{trans}'"
|
||||||
|
return val_str.upper(), None
|
||||||
|
|
||||||
|
# Check First / Middle Name
|
||||||
|
if field_name in ('first_name', 'middle_name', 'father_or_husband_name'):
|
||||||
|
if lower_val in NAME_REPAIRS:
|
||||||
|
standard = NAME_REPAIRS[lower_val]
|
||||||
|
return standard, f"Converted name '{val_str}' to standard English '{standard}' (repaired handwriting mistake)"
|
||||||
|
if cls.has_devanagari(val_str):
|
||||||
|
trans = cls.phonetic_transliterate(val_str).upper()
|
||||||
|
return trans, f"Transliterated Marathi name '{val_str}' into English '{trans}'"
|
||||||
|
return val_str.upper(), None
|
||||||
|
|
||||||
|
# Check Full Patient Name
|
||||||
|
if field_name == 'patient_name':
|
||||||
|
parts = val_str.split()
|
||||||
|
repaired_parts = []
|
||||||
|
made_repairs = False
|
||||||
|
for part in parts:
|
||||||
|
p_lower = part.lower()
|
||||||
|
if p_lower in NAME_REPAIRS:
|
||||||
|
repaired_parts.append(NAME_REPAIRS[p_lower])
|
||||||
|
made_repairs = True
|
||||||
|
elif p_lower in SURNAME_REPAIRS:
|
||||||
|
repaired_parts.append(SURNAME_REPAIRS[p_lower])
|
||||||
|
made_repairs = True
|
||||||
|
elif cls.has_devanagari(part):
|
||||||
|
repaired_parts.append(cls.phonetic_transliterate(part).upper())
|
||||||
|
made_repairs = True
|
||||||
|
else:
|
||||||
|
repaired_parts.append(part.upper())
|
||||||
|
repaired_full = " ".join(repaired_parts)
|
||||||
|
note = f"Standardized patient name '{val_str}' to English '{repaired_full}'" if made_repairs else None
|
||||||
|
return repaired_full, note
|
||||||
|
|
||||||
|
# Check Locations / Address Fields
|
||||||
|
if field_name in ('city_district', 'taluka', 'local_taluka', 'perm_taluka', 'perm_state', 'perm_country', 'nationality'):
|
||||||
|
if lower_val in LOCATION_REPAIRS:
|
||||||
|
standard = LOCATION_REPAIRS[lower_val]
|
||||||
|
return standard, f"Converted location '{val_str}' to standard English '{standard}'"
|
||||||
|
if cls.has_devanagari(val_str):
|
||||||
|
trans = cls.phonetic_transliterate(val_str).title()
|
||||||
|
return trans, f"Transliterated Marathi location '{val_str}' into English '{trans}'"
|
||||||
|
return val_str.title(), None
|
||||||
|
|
||||||
|
# Check Complex Address Strings (local_address, permanent_address)
|
||||||
|
if field_name in ('local_address', 'permanent_address', 'address'):
|
||||||
|
# Replace known Marathi words in address
|
||||||
|
repaired_addr = val_str
|
||||||
|
# Common Marathi address terms translation
|
||||||
|
addr_terms = {
|
||||||
|
'फ्लॅट': 'Flat', 'खोली': 'Room', 'गट क्र': 'Gat No', 'क्र.': 'No.',
|
||||||
|
'इमारत': 'Bldg', 'परिसर': 'Premises', 'गाव': 'Village',
|
||||||
|
'रस्ता': 'Road', 'आळी': 'Lane', 'पोस्ट': 'Post',
|
||||||
|
'मु. पो.': 'At Post', 'मु.पो.': 'At Post', 'ता.': 'Tal.', 'जि.': 'Dist.'
|
||||||
|
}
|
||||||
|
for mr_term, en_term in addr_terms.items():
|
||||||
|
repaired_addr = re.sub(re.escape(mr_term), en_term, repaired_addr, flags=re.IGNORECASE)
|
||||||
|
|
||||||
|
# Replace known locations
|
||||||
|
for mr_loc, en_loc in LOCATION_REPAIRS.items():
|
||||||
|
if mr_loc in repaired_addr:
|
||||||
|
repaired_addr = repaired_addr.replace(mr_loc, en_loc)
|
||||||
|
|
||||||
|
# If Devanagari still remains, transliterate remaining portions
|
||||||
|
if cls.has_devanagari(repaired_addr):
|
||||||
|
repaired_addr = cls.phonetic_transliterate(repaired_addr)
|
||||||
|
|
||||||
|
# Convert any Devanagari digits
|
||||||
|
repaired_addr = cls.devanagari_to_arabic_digits(repaired_addr)
|
||||||
|
# Clean spaces
|
||||||
|
repaired_addr = re.sub(r'\s+', ' ', repaired_addr).strip()
|
||||||
|
note = f"Converted Marathi address to English spellings: '{repaired_addr}'" if repaired_addr != val_str else None
|
||||||
|
return repaired_addr, note
|
||||||
|
|
||||||
|
# Check Hospital Name
|
||||||
|
if field_name == 'hospital_name':
|
||||||
|
if lower_val in LOCATION_REPAIRS:
|
||||||
|
return LOCATION_REPAIRS[lower_val], None
|
||||||
|
if cls.has_devanagari(val_str):
|
||||||
|
return 'DEENANATH MANGESHKAR HOSPITAL & RESEARCH CENTRE', "Standardized hospital name to English"
|
||||||
|
|
||||||
|
# General text: if contains Devanagari, transliterate to English
|
||||||
|
if cls.has_devanagari(val_str):
|
||||||
|
trans = cls.phonetic_transliterate(val_str).title()
|
||||||
|
return trans, f"Transliterated '{val_str}' to English spelling '{trans}'"
|
||||||
|
|
||||||
|
return val_str, None
|
||||||
Reference in New Issue
Block a user