From ecbc829a3825a33b612673308870c60ec1e816c8 Mon Sep 17 00:00:00 2001 From: "shivani.aiindia@gmail.com" Date: Mon, 19 Oct 2026 10:59:31 +0530 Subject: [PATCH] handwritten ocr --- .gitignore | 37 ++ README.md | 205 ++++++ app.py | 743 +++++++++++++++++++++ config.py | 86 +++ extraction_schema.py | 864 +++++++++++++++++++++++++ gemini_client.py | 273 ++++++++ history_manager.py | 249 ++++++++ image_preprocessor.py | 235 +++++++ requirements.txt | 7 + sample_output.json | 143 +++++ sample_output_en.json | 87 +++ sarvam_client.py | 367 +++++++++++ static/css/style.css | 1417 +++++++++++++++++++++++++++++++++++++++++ static/js/app.js | 1229 +++++++++++++++++++++++++++++++++++ templates/index.html | 380 +++++++++++ text_repair_engine.py | 551 ++++++++++++++++ 16 files changed, 6873 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 app.py create mode 100644 config.py create mode 100644 extraction_schema.py create mode 100644 gemini_client.py create mode 100644 history_manager.py create mode 100644 image_preprocessor.py create mode 100644 requirements.txt create mode 100644 sample_output.json create mode 100644 sample_output_en.json create mode 100644 sarvam_client.py create mode 100644 static/css/style.css create mode 100644 static/js/app.js create mode 100644 templates/index.html create mode 100644 text_repair_engine.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..04fa91e --- /dev/null +++ b/.gitignore @@ -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/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..0750f53 --- /dev/null +++ b/README.md @@ -0,0 +1,205 @@ +# Handwritten Marathi Hospital Form Extraction + +> Extract handwritten Marathi (मराठी) text from hospital forms using **Sarvam AI Vision** Document Intelligence. + +![Python](https://img.shields.io/badge/Python-3.9+-blue) +![Flask](https://img.shields.io/badge/Flask-3.1-green) +![Sarvam AI](https://img.shields.io/badge/Sarvam_AI-Vision-orange) + +--- + +## 🎯 Purpose + +This application evaluates how accurately **Sarvam Vision** reads handwritten Marathi text written in Devanagari script on hospital documents. It supports: + +- Handwritten Marathi hospital registration forms +- Patient information forms +- Handwritten medical notes and prescriptions +- Scanned documents and mobile photographs +- JPG, JPEG, PNG, PDF, BMP, and TIFF files + +## 🏗️ Architecture + +``` +┌─────────────────┐ ┌──────────────┐ ┌─────────────────────┐ +│ Flask Frontend │────▶│ Flask API │────▶│ Sarvam AI Doc-AI │ +│ (HTML/CSS/JS) │◀────│ (Python) │◀────│ Vision API │ +└─────────────────┘ └──────┬───────┘ └─────────────────────┘ + │ + ┌──────┴───────┐ + │ OpenCV │ + │ Preprocessor│ + └──────────────┘ +``` + +**API Endpoints Used:** +| Endpoint | Purpose | +|----------|---------| +| `POST /doc-ai/v1/job/extract` | Schema-based key-value extraction | +| `POST /doc-ai/v1/job/digitise` | Full OCR / raw transcription | +| `GET /doc-ai/v1/job/{id}/status` | Poll job completion | +| `GET /doc-ai/v1/job/{id}/results` | Fetch extraction results | + +## 📁 Project Structure + +``` +handwritten_extraction/ +├── app.py # Flask application & routes +├── config.py # Configuration from .env +├── sarvam_client.py # Sarvam AI API client +├── extraction_schema.py # JSON schema & response builder +├── image_preprocessor.py # OpenCV preprocessing pipeline +├── requirements.txt # Python dependencies +├── sample_output.json # Sample extraction output (fictional) +├── .env.example # Environment template +├── .gitignore +├── README.md +├── templates/ +│ └── index.html # Dashboard UI template +└── static/ + ├── css/ + │ └── style.css # Dark theme stylesheet + └── js/ + └── app.js # Frontend logic +``` + +## 🚀 Setup & Run + +### 1. Prerequisites + +- Python 3.9 or higher +- A Sarvam AI API key ([Sign up here](https://dashboard.sarvam.ai/)) + +### 2. Clone & Install + +```bash +cd handwritten_extraction + +# Create virtual environment +python -m venv venv + +# Activate it +# Windows: +venv\Scripts\activate +# macOS/Linux: +source venv/bin/activate + +# Install dependencies +pip install -r requirements.txt +``` + +### 3. Configure API Key + +```bash +# Copy the example env file +copy .env.example .env # Windows +# cp .env.example .env # macOS/Linux + +# Edit .env and set your API key: +# SARVAM_API_KEY=your_actual_api_key_here +``` + +### 4. Run the Application + +```bash +python app.py +``` + +Open your browser at: **http://localhost:5000** + +## 🖥️ Dashboard Features + +| Feature | Description | +|---------|-------------| +| **Document Upload** | Drag & drop or browse. Supports JPG, PNG, PDF, TIFF, BMP | +| **Image Preprocessing** | Toggle OpenCV enhancement (deskew, contrast, denoise, sharpen) | +| **Extraction Method** | Choose Auto, Schema-based Extract, or Raw OCR Digitise | +| **Extracted Fields** | Visual grid showing all parsed fields with Marathi text | +| **JSON Output** | Syntax-highlighted JSON viewer with download | +| **Raw Transcription** | Full Marathi text in Devanagari script | +| **Accuracy Comparison** | Compare against reference JSON for field-level matching | +| **Test History** | Track all extractions in the current session | +| **Download** | Export JSON or plain text transcription | + +## 📝 Extracted Fields + +The application extracts these fields when present: + +| Category | Fields | +|----------|--------| +| **Patient** | Name, Age, Gender, Address, Mobile Number | +| **Hospital** | Hospital Name, Department, Doctor Name, Visit Date | +| **Medical** | Symptoms, Medical History, Diagnosis, Medicines & Dosage, Notes | +| **Meta** | Document Type, Raw Transcription, Unreadable Fields, Warnings | + +## 🔧 Image Preprocessing + +Optional OpenCV pipeline (toggle on/off to compare quality): + +1. **Resize** — Scale down oversized images (>4096px) +2. **Auto-Rotate** — Correct skew using Hough line detection +3. **Noise Reduction** — Non-local means denoising (gentle) +4. **Contrast Enhancement** — CLAHE on luminance channel +5. **Sharpening** — Unsharp mask for clearer strokes + +> ⚠️ Preprocessing uses conservative parameters to preserve handwriting strokes. + +## 🔒 Security + +- API key stored in `.env` (never exposed to frontend) +- `.env` excluded via `.gitignore` +- Uploaded files processed in-memory (not saved to disk by default) +- No real patient data included — sample uses fictional data +- API errors handled without leaking keys + +## 📊 Sample Output + +See [`sample_output.json`](sample_output.json) for a complete example using fictional Marathi hospital data. + +Key structure: +```json +{ + "document_type": "hospital_registration_form", + "language": "mr", + "patient_details": { "patient_name": "राम विठ्ठल शिंदे", ... }, + "hospital_details": { "hospital_name": "जिल्हा रुग्णालय", ... }, + "medical_details": { "symptoms": "ताप, डोकेदुखी", ... }, + "raw_transcription": "...", + "unreadable_fields": [], + "validation_warnings": [] +} +``` + +## ⚙️ Configuration + +All settings are in `.env`: + +| Variable | Default | Description | +|----------|---------|-------------| +| `SARVAM_API_KEY` | — | Your Sarvam AI API key (required) | +| `FLASK_PORT` | `5000` | Server port | +| `FLASK_DEBUG` | `True` | Debug mode | +| `MAX_CONTENT_LENGTH_MB` | `16` | Max upload size in MB | +| `SARVAM_JOB_POLL_INTERVAL` | `3` | Seconds between status polls | +| `SARVAM_JOB_MAX_WAIT` | `120` | Max seconds to wait for job | + +## 🧪 Testing + + +1. Upload a handwritten Marathi document +2. Optionally enable preprocessing +3. Click **Extract Marathi Text** +4. Review the extracted fields, JSON, and raw transcription +5. Paste a reference JSON in the **Compare** tab for accuracy measurement +6. Check **Test History** for all session results + +> Accuracy percentages are calculated only from actual test comparisons — never fabricated. + +## 📜 License + +This project is for evaluation and testing purposes. +Do not use real patient data without appropriate authorization and data protection measures. + +--- + +**Built with ❤️ for Marathi (मराठी) language technology** diff --git a/app.py b/app.py new file mode 100644 index 0000000..0959a27 --- /dev/null +++ b/app.py @@ -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/", 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//image/", 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/", 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 + ) diff --git a/config.py b/config.py new file mode 100644 index 0000000..63226fd --- /dev/null +++ b/config.py @@ -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 diff --git a/extraction_schema.py b/extraction_schema.py new file mode 100644 index 0000000..2d78da9 --- /dev/null +++ b/extraction_schema.py @@ -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. +""" diff --git a/gemini_client.py b/gemini_client.py new file mode 100644 index 0000000..d6760a0 --- /dev/null +++ b/gemini_client.py @@ -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 diff --git a/history_manager.py b/history_manager.py new file mode 100644 index 0000000..20b7504 --- /dev/null +++ b/history_manager.py @@ -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() diff --git a/image_preprocessor.py b/image_preprocessor.py new file mode 100644 index 0000000..31bfd7f --- /dev/null +++ b/image_preprocessor.py @@ -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 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..10927d6 --- /dev/null +++ b/requirements.txt @@ -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 diff --git a/sample_output.json b/sample_output.json new file mode 100644 index 0000000..db1fa2e --- /dev/null +++ b/sample_output.json @@ -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 + } +} diff --git a/sample_output_en.json b/sample_output_en.json new file mode 100644 index 0000000..df6af95 --- /dev/null +++ b/sample_output_en.json @@ -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 + } +} diff --git a/sarvam_client.py b/sarvam_client.py new file mode 100644 index 0000000..ae45b30 --- /dev/null +++ b/sarvam_client.py @@ -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}" + ) diff --git a/static/css/style.css b/static/css/style.css new file mode 100644 index 0000000..901c7e5 --- /dev/null +++ b/static/css/style.css @@ -0,0 +1,1417 @@ +/* ═══════════════════════════════════════════════════════════ + Marathi Handwritten Extraction — Enterprise UI System + Clean, Professional, Simple & High-Legibility Design + ═══════════════════════════════════════════════════════════ */ + +@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Noto+Sans+Devanagari:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap'); + +/* ── Design Tokens ─────────────────────────────────────── */ +:root { + /* Palette: Clean Enterprise Slate & Medical Navy */ + --bg-page: #f8fafc; + --bg-card: #ffffff; + --bg-subtle: #f1f5f9; + --bg-input: #ffffff; + + --border-color: #e2e8f0; + --border-subtle: #edf2f7; + --border-hover: #cbd5e1; + --border-focus: #2563eb; + + --text-primary: #0f172a; + --text-secondary: #334155; + --text-muted: #64748b; + --text-white: #ffffff; + + --primary: #1e40af; + --primary-hover: #1d4ed8; + --primary-light: #eff6ff; + --primary-border: #bfdbfe; + + --success: #059669; + --success-bg: #ecfdf5; + --success-border: #a7f3d0; + + --warning: #b45309; + --warning-bg: #fffbeb; + --warning-border: #fde68a; + + --danger: #dc2626; + --danger-bg: #fef2f2; + --danger-border: #fecaca; + + /* Typography */ + --font-sans: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; + --font-devanagari: 'Noto Sans Devanagari', 'Inter', sans-serif; + --font-mono: 'JetBrains Mono', 'Cascadia Code', monospace; + + /* Metrics */ + --radius-sm: 6px; + --radius-md: 8px; + --radius-lg: 12px; + + --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05); + --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.06), 0 2px 4px -1px rgba(0, 0, 0, 0.04); + --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.08), 0 4px 6px -2px rgba(0, 0, 0, 0.03); + + --transition: all 0.15s ease-in-out; +} + +/* ── Global Resets ─────────────────────────────────────── */ +*, *::before, *::after { + box-sizing: border-box; + margin: 0; + padding: 0; +} + +body { + font-family: var(--font-sans); + background-color: var(--bg-page); + color: var(--text-primary); + line-height: 1.5; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + min-height: 100vh; +} + +/* ── Container ─────────────────────────────────────────── */ +.app-container { + max-width: 1240px; + margin: 0 auto; + padding: 24px 20px 48px; +} + +/* ── Professional Header ───────────────────────────────── */ +.app-header { + background: var(--bg-card); + border: 1px solid var(--border-color); + border-radius: var(--radius-lg); + padding: 20px 24px; + margin-bottom: 24px; + box-shadow: var(--shadow-sm); + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 16px; +} + +.header-left { + display: flex; + align-items: center; + gap: 16px; +} + +.header-icon-box { + width: 44px; + height: 44px; + border-radius: var(--radius-md); + background: var(--primary-light); + color: var(--primary); + display: flex; + align-items: center; + justify-content: center; + font-size: 22px; + border: 1px solid var(--primary-border); + flex-shrink: 0; +} + +.app-title { + font-size: 19px; + font-weight: 700; + color: var(--text-primary); + letter-spacing: -0.02em; + display: flex; + align-items: center; + gap: 8px; +} + +.app-title .marathi { + font-family: var(--font-devanagari); + color: var(--primary); + font-weight: 700; +} + +.app-subtitle { + font-size: 13px; + color: var(--text-muted); + margin-top: 2px; +} + +.header-badge { + display: inline-flex; + align-items: center; + gap: 6px; + background: var(--bg-subtle); + border: 1px solid var(--border-color); + padding: 6px 12px; + border-radius: 100px; + font-size: 12px; + font-weight: 600; + color: var(--text-secondary); +} + +.header-badge .dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--success); +} + +/* ── Config Alert ──────────────────────────────────────── */ +.config-alert { + background: var(--warning-bg); + border: 1px solid var(--warning-border); + color: var(--warning); + padding: 12px 16px; + border-radius: var(--radius-md); + margin-bottom: 20px; + display: flex; + align-items: center; + gap: 10px; + font-size: 13px; + font-weight: 500; +} + +/* ── Dashboard Grid ────────────────────────────────────── */ +.dashboard { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 20px; +} + +@media (max-width: 960px) { + .dashboard { + grid-template-columns: 1fr; + } +} + +/* ── Cards ─────────────────────────────────────────────── */ +.card { + background: var(--bg-card); + border: 1px solid var(--border-color); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-sm); + overflow: hidden; + transition: var(--transition); +} + +.card:hover { + border-color: var(--border-hover); +} + +.card.full-width { + grid-column: 1 / -1; + margin-top: 4px; +} + +.card-header { + padding: 16px 20px; + border-bottom: 1px solid var(--border-color); + background: #fafbfc; + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.card-title { + font-size: 15px; + font-weight: 600; + color: var(--text-primary); + display: flex; + align-items: center; + gap: 8px; +} + +.card-title .icon { + font-size: 16px; +} + +.card-header-actions { + display: flex; + align-items: center; + gap: 8px; +} + +.card-body { + padding: 20px; +} + +/* ── Upload Zone ───────────────────────────────────────── */ +.upload-zone { + position: relative; + border: 2px dashed var(--border-color); + border-radius: var(--radius-md); + padding: 36px 20px; + text-align: center; + background: #fafbfc; + cursor: pointer; + transition: var(--transition); +} + +.upload-zone:hover, +.upload-zone.drag-over { + border-color: var(--primary); + background: var(--primary-light); +} + +.upload-zone input[type="file"] { + position: absolute; + inset: 0; + opacity: 0; + cursor: pointer; + width: 100%; + height: 100%; +} + +.upload-icon { + font-size: 32px; + display: block; + margin-bottom: 10px; +} + +.upload-title { + font-size: 14px; + font-weight: 600; + color: var(--text-primary); +} + +.upload-hint { + font-size: 12px; + color: var(--text-muted); + margin-top: 4px; +} + +.upload-formats { + display: flex; + justify-content: center; + gap: 6px; + margin-top: 14px; +} + +.format-tag { + font-size: 11px; + font-weight: 600; + font-family: var(--font-mono); + padding: 2px 7px; + border-radius: var(--radius-sm); + background: var(--bg-card); + border: 1px solid var(--border-color); + color: var(--text-muted); +} + +/* ── File Preview Box ──────────────────────────────────── */ +.file-preview { + display: none; + align-items: center; + gap: 12px; + padding: 12px 14px; + background: var(--bg-subtle); + border: 1px solid var(--border-color); + border-radius: var(--radius-md); + margin-top: 14px; +} + +.file-preview.visible { + display: flex; +} + +.file-info { + flex: 1; + min-width: 0; +} + +.file-name { + font-size: 13px; + font-weight: 600; + color: var(--text-primary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.file-size { + font-size: 11px; + color: var(--text-muted); +} + +.remove-file { + background: none; + border: none; + color: var(--text-muted); + font-size: 16px; + cursor: pointer; + padding: 4px 8px; + border-radius: var(--radius-sm); + transition: var(--transition); +} + +.remove-file:hover { + color: var(--danger); + background: var(--danger-bg); +} + +/* ── Options Panel ─────────────────────────────────────── */ +.options-panel { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); + gap: 14px; + margin-top: 16px; + padding: 14px; + background: #fafbfc; + border: 1px solid var(--border-color); + border-radius: var(--radius-md); +} + +@media (max-width: 600px) { + .options-panel { + grid-template-columns: 1fr; + } +} + +.option-group { + display: flex; + flex-direction: column; + gap: 6px; +} + +.option-label { + font-size: 11px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.5px; + color: var(--text-muted); +} + +.toggle-wrapper { + display: flex; + align-items: center; + gap: 8px; + height: 36px; +} + +.toggle { + position: relative; + display: inline-block; + width: 38px; + height: 22px; + flex-shrink: 0; +} + +.toggle input { + opacity: 0; + width: 0; + height: 0; +} + +.toggle-track { + position: absolute; + inset: 0; + background: #cbd5e1; + border-radius: 20px; + cursor: pointer; + transition: var(--transition); +} + +.toggle input:checked + .toggle-track { + background: var(--primary); +} + +.toggle-track::after { + content: ''; + position: absolute; + top: 3px; + left: 3px; + width: 16px; + height: 16px; + border-radius: 50%; + background: #ffffff; + transition: var(--transition); + box-shadow: 0 1px 2px rgba(0,0,0,0.2); +} + +.toggle input:checked + .toggle-track::after { + transform: translateX(16px); +} + +.toggle-text { + font-size: 12px; + color: var(--text-secondary); + font-weight: 500; +} + +.select-styled { + height: 36px; + background: var(--bg-card); + border: 1px solid var(--border-color); + border-radius: var(--radius-sm); + padding: 0 30px 0 10px; + font-size: 13px; + color: var(--text-primary); + cursor: pointer; + outline: none; + appearance: none; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='%2364748b' viewBox='0 0 16 16'%3E%3Cpath d='M8 11L3 6h10l-5 5z'/%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-position: right 10px center; +} + +.select-styled:focus { + border-color: var(--primary); + box-shadow: 0 0 0 2px var(--primary-light); +} + +/* ── Anti-Hallucination Shield Banner ─────────────────── */ +.anti-hallucination-banner { + margin-top: 14px; + padding: 12px 14px; + background: #f0f7ff; + border: 1px solid #bfdbfe; + border-radius: var(--radius-md); + box-shadow: 0 1px 2px rgba(30, 64, 175, 0.04); +} + +.banner-top { + display: flex; + justify-content: space-between; + align-items: center; + gap: 8px; +} + +.banner-title { + font-size: 13px; + font-weight: 600; + color: var(--primary); + display: flex; + align-items: center; + gap: 6px; +} + +.banner-tag { + font-size: 10px; + font-weight: 700; + letter-spacing: 0.5px; + background: #ecfdf5; + color: #059669; + border: 1px solid #a7f3d0; + padding: 2px 7px; + border-radius: 12px; +} + +.banner-details { + margin-top: 8px; + font-size: 11px; + color: #334155; + line-height: 1.6; + border-top: 1px dashed #bfdbfe; + padding-top: 8px; +} + +.banner-rule { + margin-top: 4px; + color: #1e40af; + font-weight: 500; +} + +/* ── Buttons ───────────────────────────────────────────── */ +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + padding: 9px 18px; + font-size: 13px; + font-weight: 600; + border-radius: var(--radius-sm); + border: 1px solid transparent; + cursor: pointer; + transition: var(--transition); + white-space: nowrap; + text-decoration: none; +} + +.btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.btn-primary { + background: var(--primary); + color: var(--text-white); + border-color: var(--primary); +} + +.btn-primary:hover:not(:disabled) { + background: var(--primary-hover); + border-color: var(--primary-hover); +} + +.btn-secondary { + background: var(--bg-card); + color: var(--text-secondary); + border-color: var(--border-color); +} + +.btn-secondary:hover:not(:disabled) { + background: var(--bg-subtle); + color: var(--text-primary); + border-color: var(--border-hover); +} + +.btn-danger { + background: var(--bg-card); + color: var(--danger); + border-color: var(--danger-border); +} + +.btn-danger:hover:not(:disabled) { + background: var(--danger-bg); +} + +.btn-sm { + padding: 6px 12px; + font-size: 12px; +} + +.btn-block { + width: 100%; +} + +.flex-1 { + flex: 1; +} + +.btn-group { + display: flex; + align-items: center; + gap: 8px; +} + +/* Spinner */ +.spinner { + display: none; + width: 14px; + height: 14px; + border: 2px solid rgba(255,255,255,0.3); + border-top-color: #ffffff; + border-radius: 50%; + animation: spin 0.6s linear infinite; +} + +.btn.loading .spinner { + display: block; +} + +.btn.loading .btn-text { + opacity: 0.8; +} + +@keyframes spin { + to { transform: rotate(360deg); } +} + +/* ── Error Display ─────────────────────────────────────── */ +.error-display { + display: none; + margin-top: 16px; + padding: 12px 16px; + background: var(--danger-bg); + border: 1px solid var(--danger-border); + border-radius: var(--radius-md); + color: var(--danger); + font-size: 13px; +} + +.error-display.visible { + display: block; +} + +.error-title { + font-weight: 600; + margin-bottom: 4px; +} + +.error-message { + font-weight: 500; +} + +.error-details { + font-size: 11px; + margin-top: 4px; + color: #991b1b; + word-break: break-all; +} + +/* ── Preview Panel ─────────────────────────────────────── */ +.image-preview-container { + display: none; + gap: 16px; + max-height: 480px; + overflow-y: auto; +} + +.image-preview-container.visible { + display: grid; + grid-template-columns: 1fr 1fr; +} + +.image-preview-container.single { + grid-template-columns: 1fr; +} + +.preview-panel { + display: flex; + flex-direction: column; + border: 1px solid var(--border-color); + border-radius: var(--radius-md); + overflow: hidden; + background: #fafbfc; +} + +.preview-label { + padding: 8px 12px; + font-size: 11px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.5px; + color: var(--text-muted); + background: #f1f5f9; + border-bottom: 1px solid var(--border-color); +} + +.preview-panel img { + width: 100%; + height: auto; + max-height: 400px; + object-fit: contain; + background: #ffffff; + display: block; +} + +.preprocess-info { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 12px; +} + +.preprocess-step { + font-size: 11px; + font-weight: 500; + color: var(--success); + background: var(--success-bg); + border: 1px solid var(--success-border); + padding: 3px 8px; + border-radius: 100px; +} + +/* ── Stats Bar ─────────────────────────────────────────── */ +.stats-bar { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 12px; + margin-bottom: 20px; +} + +.stat-chip { + background: #fafbfc; + border: 1px solid var(--border-color); + border-radius: var(--radius-md); + padding: 12px 14px; + display: flex; + align-items: center; + gap: 12px; +} + +.stat-icon { + font-size: 20px; +} + +.stat-value { + font-size: 17px; + font-weight: 700; + color: var(--text-primary); + font-family: var(--font-mono); +} + +.stat-label { + font-size: 11px; + font-weight: 500; + color: var(--text-muted); +} + +/* ── Tabs Navigation ───────────────────────────────────── */ +.tabs { + display: flex; + border-bottom: 1px solid var(--border-color); + margin-bottom: 20px; + gap: 4px; +} + +.tab { + background: none; + border: none; + padding: 10px 16px; + font-size: 13px; + font-weight: 600; + color: var(--text-muted); + cursor: pointer; + border-bottom: 2px solid transparent; + transition: var(--transition); +} + +.tab:hover { + color: var(--text-primary); +} + +.tab.active { + color: var(--primary); + border-bottom-color: var(--primary); +} + +.tab-content { + display: none; +} + +.tab-content.active { + display: block; +} + +/* ── Fields Grid ───────────────────────────────────────── */ +.fields-grid { + display: flex; + flex-direction: column; + gap: 20px; +} + +.field-section-title { + font-size: 13px; + font-weight: 700; + color: var(--primary); + padding-bottom: 8px; + border-bottom: 1px solid var(--border-color); + text-transform: uppercase; + letter-spacing: 0.5px; +} + +.field-grid-inner { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); + gap: 12px; +} + +.field-card { + background: #ffffff; + border: 1px solid var(--border-color); + border-radius: var(--radius-md); + padding: 10px 14px; + display: flex; + flex-direction: column; + gap: 4px; + transition: var(--transition); +} + +.field-card:hover { + border-color: var(--border-hover); +} + +.field-card.filled { + border-left: 3px solid var(--success); +} + +.field-card.missing { + border-left: 3px solid #cbd5e1; + background: #fafbfc; +} + +.field-label { + font-size: 11px; + font-weight: 600; + color: var(--text-muted); + line-height: 1.3; +} + +.field-value { + font-size: 14px; + font-weight: 500; + color: var(--text-primary); + font-family: var(--font-devanagari); + word-break: break-word; + line-height: 1.4; +} + +.null-value { + color: #94a3b8; + font-style: italic; + font-size: 12px; +} + +/* ── JSON Viewer & Transcription ───────────────────────── */ +.json-viewer { + background: #0f172a; + color: #f1f5f9; + padding: 16px; + border-radius: var(--radius-md); + font-family: var(--font-mono); + font-size: 12px; + line-height: 1.6; + max-height: 500px; + overflow-y: auto; +} + +.json-key { color: #93c5fd; } +.json-string { color: #86efac; } +.json-number { color: #fde047; } +.json-boolean { color: #f472b6; } +.json-null { color: #94a3b8; font-style: italic; } + +.transcription-box { + background: #ffffff; + border: 1px solid var(--border-color); + padding: 18px; + border-radius: var(--radius-md); + font-family: var(--font-devanagari); + font-size: 14px; + line-height: 1.8; + white-space: pre-wrap; + max-height: 500px; + overflow-y: auto; + color: var(--text-primary); +} + +/* ── Compare Tab ───────────────────────────────────────── */ +.compare-textarea { + width: 100%; + height: 140px; + padding: 12px; + background: #ffffff; + border: 1px solid var(--border-color); + border-radius: var(--radius-md); + font-family: var(--font-mono); + font-size: 12px; + color: var(--text-primary); + resize: vertical; + outline: none; + margin-bottom: 12px; +} + +.compare-textarea:focus { + border-color: var(--primary); + box-shadow: 0 0 0 2px var(--primary-light); +} + +.compare-results { + margin-top: 16px; +} + +/* ── History Table ─────────────────────────────────────── */ +.badge-count { + display: inline-flex; + align-items: center; + background: var(--primary-light); + border: 1px solid var(--primary-border); + color: var(--primary); + padding: 2px 8px; + border-radius: 100px; + font-size: 11px; + font-weight: 600; + margin-left: 6px; +} + +.history-table-wrapper { + overflow-x: auto; +} + +.history-table { + width: 100%; + border-collapse: collapse; + font-size: 13px; + text-align: left; +} + +.history-table th { + background: #f8fafc; + color: var(--text-muted); + font-weight: 600; + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.5px; + padding: 10px 14px; + border-bottom: 1px solid var(--border-color); + white-space: nowrap; +} + +.history-table td { + padding: 12px 14px; + border-bottom: 1px solid var(--border-color); + color: var(--text-secondary); + vertical-align: middle; +} + +.history-table tr:hover td { + background: #f8fafc; +} + +.history-time { + font-size: 11px; + color: var(--text-muted); + display: block; + margin-top: 2px; +} + +.status-badge { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 2px 8px; + border-radius: 100px; + font-size: 11px; + font-weight: 600; +} + +.status-badge.success { + background: var(--success-bg); + color: var(--success); +} + +.status-badge.error, +.status-badge.failed { + background: var(--danger-bg); + color: var(--danger); +} + +.btn-action-group { + display: inline-flex; + align-items: center; + gap: 6px; +} + +/* ── Loading Overlay ───────────────────────────────────── */ +.loading-overlay { + display: none; + position: fixed; + inset: 0; + background: rgba(15, 23, 42, 0.6); + backdrop-filter: blur(4px); + z-index: 9999; + align-items: center; + justify-content: center; +} + +.loading-overlay.visible { + display: flex; +} + +.loading-content { + background: #ffffff; + border-radius: var(--radius-lg); + padding: 32px 40px; + text-align: center; + box-shadow: var(--shadow-lg); + max-width: 380px; + border: 1px solid var(--border-color); +} + +.loading-spinner-large { + width: 44px; + height: 44px; + border: 3px solid #e2e8f0; + border-top-color: var(--primary); + border-radius: 50%; + animation: spin 0.7s linear infinite; + margin: 0 auto 16px; +} + +.loading-text { + font-size: 16px; + font-weight: 700; + color: var(--text-primary); +} + +.loading-subtext { + font-size: 13px; + color: var(--text-muted); + margin-top: 4px; +} + +.loading-step { + font-size: 12px; + font-weight: 600; + color: var(--primary); + margin-top: 14px; + padding: 4px 10px; + background: var(--primary-light); + border-radius: 100px; + display: inline-block; +} + +/* ── Footer ────────────────────────────────────────────── */ +.app-footer { + text-align: center; + padding: 24px 0 12px; + color: var(--text-muted); + font-size: 12px; +} + +.app-footer strong { + color: var(--text-secondary); +} + +/* ── Utility ───────────────────────────────────────────── */ +.text-center { text-align: center; } +.text-muted { color: var(--text-muted); } +.text-success { color: var(--success); font-weight: 600; } +.text-warning { color: var(--warning); font-weight: 600; } +.text-sm { font-size: 12px; } + +/* ── Auto-Repairs Tab & Cards ──────────────────────────── */ +.repairs-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); + gap: 16px; +} + +.repair-card { + background: #ffffff; + border: 1px solid #bfdbfe; + border-radius: var(--radius-md); + padding: 14px 16px; + box-shadow: 0 1px 3px rgba(30, 64, 175, 0.05); + transition: var(--transition); +} + +.repair-card:hover { + border-color: #93c5fd; + box-shadow: 0 4px 6px -1px rgba(30, 64, 175, 0.08); +} + +.repair-card-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-bottom: 10px; +} + +.repair-card-field { + font-size: 13px; + font-weight: 700; + color: var(--primary); +} + +.repair-card-badge { + font-size: 10px; + font-weight: 700; + padding: 2px 6px; + background: #eff6ff; + color: #1e40af; + border: 1px solid #bfdbfe; + border-radius: 10px; + letter-spacing: 0.4px; +} + +.repair-card-diff { + display: flex; + align-items: center; + gap: 10px; + background: #f8fafc; + border: 1px solid var(--border-color); + border-radius: var(--radius-sm); + padding: 10px 12px; +} + +.repair-diff-item { + flex: 1; + min-width: 0; +} + +.diff-label { + display: block; + font-size: 10px; + font-weight: 600; + text-transform: uppercase; + color: var(--text-muted); + letter-spacing: 0.4px; + margin-bottom: 2px; +} + +.diff-value { + font-size: 13px; + font-weight: 600; + word-break: break-word; +} + +.repair-diff-item.original .diff-value { + color: #dc2626; + text-decoration: line-through; +} + +.repair-diff-item.corrected .diff-value { + color: #059669; +} + +.repair-diff-arrow { + font-size: 16px; + color: var(--primary); + font-weight: 700; + flex-shrink: 0; +} + +.repair-card-note { + font-size: 11px; + color: #475569; + margin-top: 8px; + line-height: 1.4; +} + +.repair-pill-inline { + display: inline-block; + font-size: 10px; + font-weight: 700; + color: #1e40af; + background: #eff6ff; + border: 1px solid #bfdbfe; + border-radius: 10px; + padding: 1px 6px; + margin-left: 6px; + vertical-align: middle; +} + +.repair-subnote { + font-size: 11px; + color: var(--text-muted); + margin-top: 3px; +} + +.repair-subnote s { + color: #b91c1c; +} + +/* ── Model Comparison Benchmark ────────────────────────── */ +.model-compare-container { + padding: 10px 0; +} + +.model-benchmark-hero { + background: linear-gradient(135deg, #f8fafc 0%, #eff6ff 100%); + border: 1px solid var(--border-color); + border-radius: var(--radius-md); + padding: 18px 20px; + margin-bottom: 20px; +} + +.benchmark-hero-top { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 12px; + margin-bottom: 16px; +} + +.benchmark-title { + font-size: 15px; + font-weight: 700; + color: var(--text-primary); + display: flex; + align-items: center; + gap: 8px; +} + +.model-tags-group { + display: flex; + align-items: center; + gap: 8px; +} + +.model-tag { + font-size: 11px; + font-weight: 700; + padding: 3px 10px; + border-radius: 12px; + display: inline-flex; + align-items: center; + gap: 4px; +} + +.model-tag.gemini { + background: #e0f2fe; + color: #0369a1; + border: 1px solid #7dd3fc; +} + +.model-tag.sarvam { + background: #ffedd5; + color: #c2410c; + border: 1px solid #fed7aa; +} + +.model-metrics-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); + gap: 12px; +} + +.model-metric-card { + background: #ffffff; + border: 1px solid var(--border-color); + border-radius: var(--radius-sm); + padding: 12px 14px; +} + +.metric-label { + font-size: 11px; + color: var(--text-muted); + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.3px; + margin-bottom: 4px; +} + +.metric-values { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; +} + +.metric-subval { + font-size: 13px; + font-weight: 700; +} + +.metric-subval.gemini { + color: #0284c7; +} + +.metric-subval.sarvam { + color: #ea580c; +} + +.metric-badge-speed { + font-size: 10px; + padding: 1px 6px; + border-radius: 10px; + background: #dcfce7; + color: #15803d; + font-weight: 700; +} + +.model-switcher-bar { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 12px; + margin-bottom: 14px; + padding-bottom: 12px; + border-bottom: 1px solid var(--border-color); +} + +.view-mode-buttons { + display: inline-flex; + background: #f1f5f9; + padding: 3px; + border-radius: var(--radius-sm); + gap: 2px; +} + +.view-btn { + border: none; + background: transparent; + padding: 5px 12px; + font-size: 12px; + font-weight: 600; + color: var(--text-secondary); + border-radius: 4px; + cursor: pointer; + transition: all 0.15s ease; +} + +.view-btn.active { + background: #ffffff; + color: var(--primary); + box-shadow: 0 1px 3px rgba(0,0,0,0.08); +} + +.model-compare-table-wrapper { + overflow-x: auto; + border: 1px solid var(--border-color); + border-radius: var(--radius-sm); + background: #ffffff; +} + +.model-compare-table { + width: 100%; + border-collapse: collapse; + font-size: 13px; +} + +.model-compare-table th { + background: #f8fafc; + color: var(--text-secondary); + font-size: 11px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.5px; + padding: 10px 14px; + text-align: left; + border-bottom: 2px solid var(--border-color); +} + +.model-compare-table td { + padding: 10px 14px; + border-bottom: 1px solid var(--border-color); + vertical-align: top; +} + +.model-compare-table tr:last-child td { + border-bottom: none; +} + +.model-compare-table tr:hover { + background: #fbfcfe; +} + +.status-badge { + display: inline-flex; + align-items: center; + gap: 4px; + font-size: 10px; + font-weight: 700; + padding: 2px 8px; + border-radius: 12px; + letter-spacing: 0.3px; +} + +.status-badge.match { + background: #ecfdf5; + color: #059669; + border: 1px solid #a7f3d0; +} + +.status-badge.different { + background: #fffbeb; + color: #b45309; + border: 1px solid #fde68a; +} + +.status-badge.only_in_a { + background: #f0f9ff; + color: #0284c7; + border: 1px solid #bae6fd; +} + +.status-badge.only_in_b { + background: #fff7ed; + color: #ea580c; + border: 1px solid #fed7aa; +} + +.status-badge.both_empty { + background: #f1f5f9; + color: #64748b; + border: 1px solid #e2e8f0; +} + diff --git a/static/js/app.js b/static/js/app.js new file mode 100644 index 0000000..4dabf3c --- /dev/null +++ b/static/js/app.js @@ -0,0 +1,1229 @@ +/** + * Handwritten Marathi Hospital Form Extraction + * Frontend Application Logic + */ + +// ════════════════════════════════════════════════════════════ +// State +// ════════════════════════════════════════════════════════════ +const AppState = { + selectedFile: null, + lastResult: null, + isProcessing: false, + testResults: [] +}; + +// ════════════════════════════════════════════════════════════ +// DOM References +// ════════════════════════════════════════════════════════════ +const DOM = {}; + +function cacheDom() { + DOM.uploadZone = document.getElementById('upload-zone'); + DOM.fileInput = document.getElementById('file-input'); + DOM.filePreview = document.getElementById('file-preview'); + DOM.fileName = document.getElementById('file-name'); + DOM.fileSize = document.getElementById('file-size'); + DOM.removeFileBtn = document.getElementById('remove-file'); + DOM.languageSelect = document.getElementById('language-select'); + DOM.preprocessToggle = document.getElementById('preprocess-toggle'); + DOM.methodSelect = document.getElementById('method-select'); + DOM.extractBtn = document.getElementById('extract-btn'); + DOM.resetBtn = document.getElementById('reset-btn'); + DOM.imagePreviewContainer = document.getElementById('image-preview-container'); + DOM.originalImage = document.getElementById('original-image'); + DOM.processedImage = document.getElementById('processed-image'); + DOM.processedPanel = document.getElementById('processed-panel'); + DOM.resultsContainer = document.getElementById('results-container'); + DOM.errorDisplay = document.getElementById('error-display'); + DOM.errorMessage = document.getElementById('error-message'); + DOM.errorDetails = document.getElementById('error-details'); + DOM.loadingOverlay = document.getElementById('loading-overlay'); + DOM.loadingStep = document.getElementById('loading-step'); + DOM.statTime = document.getElementById('stat-time'); + DOM.statLang = document.getElementById('stat-lang'); + DOM.statFields = document.getElementById('stat-fields'); + DOM.statRepairs = document.getElementById('stat-repairs'); + DOM.statMissing = document.getElementById('stat-missing'); + DOM.statMethod = document.getElementById('stat-method'); + DOM.tabRepairsCount = document.getElementById('tab-repairs-count'); + DOM.repairsContainer = document.getElementById('repairs-container'); + DOM.jsonViewer = document.getElementById('json-viewer'); + DOM.transcriptionBox = document.getElementById('transcription-box'); + DOM.fieldsGrid = document.getElementById('fields-grid'); + DOM.downloadJsonBtn = document.getElementById('download-json'); + DOM.downloadTextBtn = document.getElementById('download-text'); + DOM.compareTextarea = document.getElementById('compare-textarea'); + DOM.compareBtn = document.getElementById('compare-btn'); + DOM.compareResults = document.getElementById('compare-results'); + DOM.historyBody = document.getElementById('history-body'); + DOM.preprocessInfo = document.getElementById('preprocess-info'); + DOM.modelSelect = document.getElementById('model-select'); + DOM.geminiModelGroup = document.getElementById('gemini-model-group'); + DOM.geminiModelSelect = document.getElementById('gemini-model-select'); + DOM.geminiCustomInput = document.getElementById('gemini-custom-input'); + DOM.statModel = document.getElementById('stat-model'); + DOM.tabBtnModelCompare = document.getElementById('tab-btn-model-compare'); + DOM.modelMatchPct = document.getElementById('model-match-pct'); + DOM.modelCompareContainer = document.getElementById('model-compare-container'); +} + +// ════════════════════════════════════════════════════════════ +// Init +// ════════════════════════════════════════════════════════════ +document.addEventListener('DOMContentLoaded', () => { + cacheDom(); + bindEvents(); + loadTestHistory(); + checkModelAvailability(); +}); + +function bindEvents() { + // Upload + DOM.fileInput.addEventListener('change', handleFileSelect); + DOM.removeFileBtn.addEventListener('click', clearFile); + + // Model controls + if (DOM.modelSelect) { + DOM.modelSelect.addEventListener('change', updateModelControls); + updateModelControls(); + } + if (DOM.geminiModelSelect) { + DOM.geminiModelSelect.addEventListener('change', () => { + if (DOM.geminiCustomInput) { + DOM.geminiCustomInput.style.display = DOM.geminiModelSelect.value === 'custom' ? 'block' : 'none'; + } + }); + } + + // Drag & drop + DOM.uploadZone.addEventListener('dragover', (e) => { + e.preventDefault(); + DOM.uploadZone.classList.add('drag-over'); + }); + DOM.uploadZone.addEventListener('dragleave', () => { + DOM.uploadZone.classList.remove('drag-over'); + }); + DOM.uploadZone.addEventListener('drop', (e) => { + e.preventDefault(); + DOM.uploadZone.classList.remove('drag-over'); + if (e.dataTransfer.files.length > 0) { + DOM.fileInput.files = e.dataTransfer.files; + handleFileSelect({ target: DOM.fileInput }); + } + }); + + // Actions + DOM.extractBtn.addEventListener('click', handleExtract); + DOM.resetBtn.addEventListener('click', handleReset); + DOM.downloadJsonBtn.addEventListener('click', downloadJson); + DOM.downloadTextBtn.addEventListener('click', downloadText); + DOM.compareBtn.addEventListener('click', handleCompare); + + // Tabs + document.querySelectorAll('.tab').forEach(tab => { + tab.addEventListener('click', () => switchTab(tab.dataset.tab)); + }); +} + +async function checkModelAvailability() { + try { + const resp = await fetch('/api/models'); + if (!resp.ok) return; + const data = await resp.json(); + const configured = data.configured || {}; + + const geminiOpt = DOM.modelSelect?.querySelector('option[value="gemini"]'); + const sarvamOpt = DOM.modelSelect?.querySelector('option[value="sarvam"]'); + const compareOpt = DOM.modelSelect?.querySelector('option[value="compare"]'); + + if (geminiOpt) { + if (!configured.gemini) { + geminiOpt.textContent = '🔷 Google Gemini (Requires GEMINI_API_KEY in .env)'; + } else { + geminiOpt.textContent = '🔷 Google Gemini Flash (Vision) • Ready'; + } + } + if (sarvamOpt) { + if (!configured.sarvam) { + sarvamOpt.textContent = '🔶 DocVision AI (Requires SARVAM_API_KEY in .env)'; + } else { + sarvamOpt.textContent = '🔶 DocVision AI (Sarvam Vision) • Ready'; + } + } + if (compareOpt) { + if (configured.gemini && configured.sarvam) { + compareOpt.textContent = '⚖️ Run Both Models & Compare (Benchmark Ready)'; + } else { + compareOpt.textContent = '⚖️ Run Both Models & Compare (Benchmark)'; + } + } + } catch (e) { + console.warn('Could not check model status:', e); + } +} + +function updateModelControls() { + if (!DOM.modelSelect || !DOM.geminiModelGroup) return; + const val = DOM.modelSelect.value; + DOM.geminiModelGroup.style.display = (val === 'gemini' || val === 'compare') ? 'flex' : 'none'; +} + +// ════════════════════════════════════════════════════════════ +// File Handling +// ════════════════════════════════════════════════════════════ +function handleFileSelect(e) { + const file = e.target.files[0]; + if (!file) return; + + const allowed = ['jpg', 'jpeg', 'png', 'pdf', 'bmp', 'tiff', 'tif']; + const ext = file.name.split('.').pop().toLowerCase(); + if (!allowed.includes(ext)) { + showError('Unsupported file type', `Allowed formats: ${allowed.join(', ').toUpperCase()}`); + return; + } + + AppState.selectedFile = file; + DOM.fileName.textContent = file.name; + DOM.fileSize.textContent = formatFileSize(file.size); + DOM.filePreview.classList.add('visible'); + DOM.extractBtn.disabled = false; + + // Show image preview for image files + if (file.type.startsWith('image/')) { + const reader = new FileReader(); + reader.onload = (ev) => { + DOM.originalImage.src = ev.target.result; + DOM.imagePreviewContainer.classList.add('visible', 'single'); + DOM.processedPanel.style.display = 'none'; + }; + reader.readAsDataURL(file); + } else { + DOM.imagePreviewContainer.classList.remove('visible'); + } + + hideError(); +} + +function clearFile() { + AppState.selectedFile = null; + DOM.fileInput.value = ''; + DOM.filePreview.classList.remove('visible'); + DOM.extractBtn.disabled = true; + DOM.imagePreviewContainer.classList.remove('visible'); +} + +// ════════════════════════════════════════════════════════════ +// Extraction +// ════════════════════════════════════════════════════════════ +async function handleExtract() { + if (!AppState.selectedFile || AppState.isProcessing) return; + + AppState.isProcessing = true; + DOM.extractBtn.classList.add('loading'); + DOM.extractBtn.disabled = true; + showLoading(); + hideError(); + DOM.resultsContainer.classList.remove('visible'); + + const formData = new FormData(); + formData.append('file', AppState.selectedFile); + formData.append('preprocess', DOM.preprocessToggle.checked ? 'true' : 'false'); + formData.append('method', DOM.methodSelect.value); + formData.append('language', DOM.languageSelect ? DOM.languageSelect.value : 'auto'); + + // Multi-model selection + const selectedModel = DOM.modelSelect ? DOM.modelSelect.value : 'auto'; + formData.append('model', selectedModel); + + let geminiModelName = 'gemini-2.0-flash'; + if (DOM.geminiModelSelect) { + geminiModelName = DOM.geminiModelSelect.value === 'custom' && DOM.geminiCustomInput + ? DOM.geminiCustomInput.value.trim() + : DOM.geminiModelSelect.value; + } + if (geminiModelName) { + formData.append('gemini_model', geminiModelName); + } + + updateLoadingStep('Uploading document...'); + + try { + const startTime = Date.now(); + if (selectedModel === 'compare') { + updateLoadingStep('Benchmarking: Running both Gemini Flash & Sarvam Vision concurrently...'); + } else if (selectedModel === 'gemini') { + updateLoadingStep(`Analyzing with Google Gemini Flash (${geminiModelName})...`); + } else { + updateLoadingStep('Analyzing with DocVision AI...'); + } + + const response = await fetch('/api/extract', { + method: 'POST', + body: formData + }); + + updateLoadingStep('Processing response & applying auto-repairs...'); + const data = await response.json(); + + if (!response.ok || data.error) { + throw { + message: data.error || `Server returned ${response.status}`, + details: data.api_response || data.status_code || '' + }; + } + + AppState.lastResult = data; + renderResults(data); + + } catch (err) { + showError( + err.message || 'Extraction failed', + err.details || 'Please check your API key configuration in .env and try again.' + ); + } finally { + AppState.isProcessing = false; + DOM.extractBtn.classList.remove('loading'); + DOM.extractBtn.disabled = false; + hideLoading(); + } +} + +// ════════════════════════════════════════════════════════════ +// Render Results +// ════════════════════════════════════════════════════════════ +function renderResults(data) { + AppState.lastResult = data; + const extraction = data.extraction || {}; + const meta = extraction._meta || {}; + + // Stats + DOM.statTime.textContent = `${data.total_time_seconds || meta.api_response_time_seconds || '—'}s`; + if (DOM.statLang) { + const lang = (extraction.form_language || extraction.language || '').toLowerCase(); + if (lang === 'en' || lang === 'en-in') { + DOM.statLang.innerHTML = '🇬🇧 English Form'; + } else if (lang === 'mr' || lang === 'mr-in') { + DOM.statLang.innerHTML = '🇮🇳 Marathi Form'; + } else { + DOM.statLang.textContent = lang || '—'; + } + } + DOM.statFields.textContent = countFields(extraction); + const repairs = extraction.repaired_fields || []; + if (DOM.statRepairs) DOM.statRepairs.textContent = repairs.length; + if (DOM.tabRepairsCount) DOM.tabRepairsCount.textContent = repairs.length; + DOM.statMissing.textContent = (extraction.unreadable_fields || []).length; + DOM.statMethod.textContent = meta.method || 'auto'; + + if (DOM.statModel) { + if (data.is_comparison) { + DOM.statModel.innerHTML = 'Gemini vs Sarvam'; + } else { + const rawModel = meta.model || 'DocVision AI'; + const cleanModel = rawModel.replace('Gemini (', '').replace(')', ''); + DOM.statModel.textContent = cleanModel; + } + } + + // JSON Viewer + const displayJson = { ...extraction }; + delete displayJson._meta; + DOM.jsonViewer.innerHTML = syntaxHighlightJson(JSON.stringify(displayJson, null, 2)); + + // Raw Transcription + DOM.transcriptionBox.textContent = extraction.raw_transcription || ''; + + // Fields Grid & Repairs + renderFieldsGrid(extraction); + renderRepairsTab(repairs); + + // Model Comparison tab + if (data.is_comparison && data.comparison) { + if (DOM.tabBtnModelCompare) { + DOM.tabBtnModelCompare.style.display = 'inline-flex'; + } + if (DOM.modelMatchPct) { + DOM.modelMatchPct.textContent = `${data.comparison.overall_match_percent}%`; + } + renderModelComparisonTab(data.comparison, data.gemini_result, data.sarvam_result); + switchTab('model-compare'); + } else { + if (DOM.tabBtnModelCompare) { + DOM.tabBtnModelCompare.style.display = 'none'; + } + switchTab('fields'); + } + + // Image previews + if (data.original_image_b64) { + DOM.originalImage.src = `data:image/jpeg;base64,${data.original_image_b64}`; + DOM.imagePreviewContainer.classList.add('visible'); + } else if (data.original_image_url) { + DOM.originalImage.src = data.original_image_url; + DOM.imagePreviewContainer.classList.add('visible'); + } else { + DOM.imagePreviewContainer.classList.remove('visible'); + } + + if (data.processed_image_b64) { + DOM.processedImage.src = `data:image/jpeg;base64,${data.processed_image_b64}`; + DOM.processedPanel.style.display = 'block'; + DOM.imagePreviewContainer.classList.remove('single'); + } else if (data.processed_image_url) { + DOM.processedImage.src = data.processed_image_url; + DOM.processedPanel.style.display = 'block'; + DOM.imagePreviewContainer.classList.remove('single'); + } else { + DOM.processedPanel.style.display = 'none'; + DOM.imagePreviewContainer.classList.add('single'); + } + + // Preprocessing info + if (data.preprocessing && data.preprocessing.steps_applied) { + const steps = data.preprocessing.steps_applied; + DOM.preprocessInfo.innerHTML = steps.map(s => + `✓ ${formatStepName(s)}` + ).join(''); + DOM.preprocessInfo.style.display = steps.length > 0 ? 'flex' : 'none'; + } else { + DOM.preprocessInfo.style.display = 'none'; + } + + // Show results + DOM.resultsContainer.classList.add('visible'); + + // Update history + loadTestHistory(); + + // Scroll to results + DOM.resultsContainer.scrollIntoView({ behavior: 'smooth', block: 'start' }); +} + +function renderFieldsGrid(extraction) { + const sections = [ + { + title: '🏥 Hospital & Registration — रुग्णालय व नोंदणी माहिती', + icon: '🏥', + data: extraction.hospital_details || {} + }, + { + title: '👤 Patient Identification — रुग्ण ओळख व नाव', + icon: '👤', + data: extraction.patient_details || {} + }, + { + title: '📍 Local Address (Pune) — स्थानिक पत्ता (पुण्यातील)', + icon: '📍', + data: { + local_address: (extraction.address_details || {}).local_address, + local_flat_room: (extraction.address_details || {}).local_flat_room, + local_premises: (extraction.address_details || {}).local_premises, + local_landmark: (extraction.address_details || {}).local_landmark, + local_road: (extraction.address_details || {}).local_road, + local_taluka: (extraction.address_details || {}).local_taluka, + local_pincode: (extraction.address_details || {}).local_pincode + } + }, + { + title: '🏡 Permanent Address — कायमचा पत्ता', + icon: '🏡', + data: { + permanent_address: (extraction.address_details || {}).permanent_address, + perm_flat_room: (extraction.address_details || {}).perm_flat_room, + perm_premises: (extraction.address_details || {}).perm_premises, + perm_landmark: (extraction.address_details || {}).perm_landmark, + perm_road: (extraction.address_details || {}).perm_road, + perm_taluka: (extraction.address_details || {}).perm_taluka, + city_district: (extraction.address_details || {}).city_district, + perm_state: (extraction.address_details || {}).perm_state, + pincode: (extraction.address_details || {}).pincode, + perm_country: (extraction.address_details || {}).perm_country, + nationality: (extraction.address_details || {}).nationality + } + }, + { + title: '💳 Socio-Economic & Billing — उत्पन्न व शुल्क', + icon: '💳', + data: extraction.billing_details || {} + }, + { + title: '✍️ Representative / Signatory — प्रतिनिधी माहिती', + icon: '✍️', + data: extraction.representative_details || {} + }, + { + title: '🩺 Medical Notes — वैद्यकीय नोंदी', + icon: '🩺', + data: extraction.medical_details || {} + } + ].filter(s => s.data && Object.keys(s.data).length > 0); + + const fieldLabels = { + // Hospital & Registration + hospital_name: 'Hospital Name / रुग्णालयाचे नाव', + mrd_number: 'MRD No. / एमआरडी क्र.', + barcode_number: 'Registration Barcode / बारकोड नोंदणी क्र.', + visit_date: 'Date / दिनांक', + examiner_name: 'Audited by / तपासणीसाचे नाव', + registrar_name: 'Entered by / नोंद घेणाऱ्याचे नाव', + department: 'Department / विभाग', + doctor_name: 'Consultant / डॉक्टरांचे नाव', + remarks: 'Remark / शेरा', + + // Patient Details + patient_name: 'Full Name / पूर्ण नाव', + first_name: 'First Name / पहिले नाव', + middle_name: 'Middle Name / मधले किंवा वडिलांचे नाव', + surname: 'Last Name / Surname / आडनाव', + father_or_husband_name: 'Father/Husband / वडील किंवा पतीचे नाव', + salutation: 'Title / Salutation / संबोधन', + gender: 'Gender / लिंग', + dob: 'Date of Birth / जन्मतारीख', + age: 'Approximate Age / वय', + id_proof_type: 'ID Proof / ओळखपत्र प्रकार', + mobile_number: 'Mobile / मोबाईल क्रमांक', + alternate_mobile: 'Alt Mobile / पर्यायी मोबाईल', + telephone: 'Telephone / दूरध्वनी क्रमांक', + email: 'Email / ईमेल', + aadhaar_number: 'AADHAAR / आधार क्रमांक', + pan_number: 'PAN / पॅन क्रमांक', + address: 'Combined Address / पत्ता', + + // Local Address + local_address: 'Full Local Address / स्थानिक पूर्ण पत्ता', + local_flat_room: 'Flat / Room No. / फ्लॅट क्र.', + local_premises: 'Premises / Building / गाव इमारत', + local_landmark: 'Landmark / घराजवळची खूण', + local_road: 'Road / Lane / रस्ता आळी', + local_taluka: 'Area / Taluka / विभाग तालुका', + local_pincode: 'PIN / Zip Code / पिनकोड', + + // Permanent Address + permanent_address: 'Full Permanent Address / कायमचा पूर्ण पत्ता', + perm_flat_room: 'Flat / Room No. / फ्लॅट क्र.', + perm_premises: 'Premises / Building / गाव इमारत', + perm_landmark: 'Landmark / घराजवळची खूण', + perm_road: 'Road / Lane / रस्ता आळी', + perm_taluka: 'Area / Taluka / विभाग तालुका', + city_district: 'City / District / शहर जिल्हा', + perm_state: 'State / Union Territory / राज्य', + pincode: 'PIN / Zip Code / पिनकोड', + perm_country: 'Country / देश', + nationality: 'Nationality / राष्ट्रीयत्व', + + // Billing + income_source: 'Source of Income / उत्पन्नाचा स्रोत', + monthly_income: 'Monthly Income / मासिक उत्पन्न', + bill_payer: 'Bill Payer / शुल्क कोण भरणार?', + company_name: 'Company / कंपनीचे नाव', + + // Representative + signatory: 'Signature / स्वाक्षरी', + representative_name: 'Representative / प्रतिनिधीचे नाव', + relationship: 'Relationship / नाते', + + // Clinical + symptoms: 'Symptoms / लक्षणे', + medical_history: 'Medical History / इतिहास', + diagnosis: 'Diagnosis / निदान', + medicines: 'Medicines / औषधे', + additional_notes: 'Additional Notes / नोंदी' + }; + + let html = ''; + + // Language & Form Header Badge + const formLang = (extraction.form_language || extraction.language || '').toLowerCase(); + const isEnglish = formLang === 'en' || formLang === 'en-in'; + const formTitle = isEnglish + ? '🇬🇧 English Form: DEENANATH MANGESHKAR HOSPITAL & RESEARCH CENTRE (PATIENT REGISTRATION FORM)' + : '🇮🇳 मराठी अर्ज: दीनानाथ मंगेशकर रुग्णालय आणि संशोधन केंद्र (रुग्ण नावनोंदणी अर्ज)'; + + html += ` +
+
${formTitle}
+
+ 🛡️ ZERO-HALLUCINATION SHIELD APPLIED +
+
+ `; + + // Map of repaired fields + const repairMap = {}; + (extraction.repaired_fields || []).forEach(r => { + repairMap[r.field] = r; + }); + + sections.forEach(section => { + html += `
${section.title}
`; + html += `
`; + Object.entries(section.data).forEach(([key, value]) => { + // Skip redundant father_or_husband_name if middle_name is already shown + if (key === 'father_or_husband_name' && section.data.middle_name) { + return; + } + if (key === 'mrp_number') { + return; + } + + const label = fieldLabels[key] || key; + const isMissing = value === null || value === '' || (Array.isArray(value) && value.length === 0); + const cssClass = isMissing ? 'missing' : 'filled'; + + let displayValue; + if (Array.isArray(value)) { + if (value.length === 0) { + displayValue = '— empty —'; + } else { + displayValue = value.map(item => { + if (typeof item === 'object') { + return `${item.name || '—'} : ${item.dosage || '—'}`; + } + return item; + }).join('
'); + } + } else if (value === null || value === undefined) { + displayValue = '— null (unwritten) —'; + } else { + displayValue = escapeHtml(String(value)); + } + + const repairInfo = repairMap[key]; + const repairBadge = repairInfo + ? `✨ Auto-Repaired` + : ''; + const repairSubnote = repairInfo + ? `
Patient wrote: ${escapeHtml(repairInfo.original)}
` + : ''; + + html += ` +
+
${label} ${repairBadge}
+
${displayValue}
+ ${repairSubnote} +
+ `; + }); + html += `
`; + }); + + // Warnings + const warnings = extraction.validation_warnings || []; + if (warnings.length > 0) { + html += `
⚠️ Warnings & Auto-Repair Audit
`; + warnings.forEach(w => { + const isHallucinationGuard = w.includes('Hallucination') || w.includes('विसंगत') || w.includes('Anti-Hallucination') || w.includes('दुरुस्त') || w.includes('Auto-Repaired'); + const icon = isHallucinationGuard ? '🛡️' : '⚠️'; + const cardStyle = isHallucinationGuard + ? 'background: #eff6ff; border: 1px solid #bfdbfe; border-left: 4px solid #1e40af;' + : ''; + const textStyle = isHallucinationGuard + ? 'color: #1e40af; font-weight: 500;' + : 'color: var(--warning);'; + html += ` +
+
${icon} ${escapeHtml(w)}
+
+ `; + }); + } + + DOM.fieldsGrid.innerHTML = html; +} + +function renderRepairsTab(repairs) { + if (!DOM.repairsContainer) return; + if (!repairs || repairs.length === 0) { + DOM.repairsContainer.innerHTML = ` +
+ ✨ + Clean Handwriting Extraction +

No patient spelling typos or phonetic mistakes were detected. All fields were extracted cleanly.

+
+ `; + return; + } + + let html = ` +
+ ✨ Auto-Repair Engine Applied: ${repairs.length} patient handwriting mistake(s) / phonetic slips were repaired and converted into standard, properly spelled English. +
+
+ `; + + repairs.forEach(r => { + html += ` +
+
+ ${escapeHtml(r.field)} + REPAIRED & CONVERTED +
+
+
+ Patient Handwrote: + ${escapeHtml(r.original)} +
+
➔
+
+ Standard English: + ${escapeHtml(r.repaired)} +
+
+
💡 ${escapeHtml(r.note)}
+
+ `; + }); + + html += `
`; + DOM.repairsContainer.innerHTML = html; +} + +function renderModelComparisonTab(comparison, geminiRes, sarvamRes) { + if (!DOM.modelCompareContainer) return; + if (!comparison) { + DOM.modelCompareContainer.innerHTML = '
No comparison data available.
'; + return; + } + + const timeA = comparison.time_a_seconds !== undefined && comparison.time_a_seconds !== null ? comparison.time_a_seconds : '—'; + const timeB = comparison.time_b_seconds !== undefined && comparison.time_b_seconds !== null ? comparison.time_b_seconds : '—'; + + let speedBadge = ''; + if (typeof timeA === 'number' && typeof timeB === 'number' && timeA > 0 && timeB > 0) { + const faster = timeA < timeB ? comparison.model_a : comparison.model_b; + const ratio = (Math.max(timeA, timeB) / Math.min(timeA, timeB)).toFixed(1); + const firstName = faster.includes('Gemini') ? 'Gemini' : 'Sarvam'; + speedBadge = `⚡ ${firstName} ${ratio}x Faster`; + } + + let html = ` +
+
+
+ ⚖️ + AI Vision Model Benchmark & Accuracy Comparison +
+
+ 🔷 ${escapeHtml(comparison.model_a)} + vs + 🔶 ${escapeHtml(comparison.model_b)} +
+
+ +
+
+
⏱️ Response Time
+
+ ${timeA}s + vs + ${timeB}s +
+
${speedBadge}
+
+ +
+
📋 Extracted Fields
+
+ ${comparison.fields_a_count} + vs + ${comparison.fields_b_count} +
+
+ Active evaluated: ${comparison.active_fields} +
+
+ +
+
🤝 Agreement Rate
+
+ ${comparison.agreement_percent}% +
+
+ ${comparison.matches} matches · ${comparison.mismatches} differences +
+
+ +
+
✨ Auto-Repairs Applied
+
+ ${comparison.repairs_a_count} + vs + ${comparison.repairs_b_count} +
+
+ Handwriting mistakes repaired +
+
+
+
+ +
+
+ Field-by-Field Matrix (${comparison.field_rows.length} fields) +
+
+ + + + +
+
+ +
+ + + + + + + + + + + `; + + comparison.field_rows.forEach(r => { + let badgeClass = 'both_empty'; + let badgeText = 'BOTH EMPTY'; + + if (r.status === 'MATCH') { + badgeClass = 'match'; + badgeText = '✓ MATCH'; + } else if (r.status === 'DIFFERENT') { + badgeClass = 'different'; + badgeText = '≠ DIFFERENCE'; + } else if (r.status === 'ONLY_IN_A') { + badgeClass = 'only_in_a'; + badgeText = 'GEMINI ONLY'; + } else if (r.status === 'ONLY_IN_B') { + badgeClass = 'only_in_b'; + badgeText = 'SARVAM ONLY'; + } + + const displayA = r.value_a ? escapeHtml(String(r.value_a)) : '— null —'; + const displayB = r.value_b ? escapeHtml(String(r.value_b)) : '— null —'; + + const repairBadgeA = r.repaired_a ? `✨ Repaired` : ''; + const repairBadgeB = r.repaired_b ? `✨ Repaired` : ''; + + const filterTag = r.status === 'MATCH' ? 'match' : (r.status === 'DIFFERENT' ? 'diff' : (r.status === 'BOTH_EMPTY' ? 'empty' : 'active')); + + html += ` + + + + + + + `; + }); + + html += ` + +
Field Name🔷 ${escapeHtml(comparison.model_a)}🔶 ${escapeHtml(comparison.model_b)}Comparison Status
+ ${escapeHtml(r.field)} +
${escapeHtml(r.section_title)}
+
+
${displayA} ${repairBadgeA}
+
+
${displayB} ${repairBadgeB}
+
+ ${badgeText} +
+
+ `; + + DOM.modelCompareContainer.innerHTML = html; +} + +window.filterComparisonRows = function(type, btn) { + if (btn) { + document.querySelectorAll('.view-mode-buttons .view-btn').forEach(b => b.classList.remove('active')); + btn.classList.add('active'); + } + const rows = document.querySelectorAll('#compare-table-body tr'); + rows.forEach(r => { + const filter = r.getAttribute('data-filter'); + if (type === 'all') { + r.style.display = ''; + } else if (type === 'match') { + r.style.display = filter === 'match' ? '' : 'none'; + } else if (type === 'diff') { + r.style.display = filter === 'diff' ? '' : 'none'; + } else if (type === 'active') { + r.style.display = filter !== 'empty' ? '' : 'none'; + } + }); +}; + +// ════════════════════════════════════════════════════════════ +// Comparison +// ════════════════════════════════════════════════════════════ +async function handleCompare() { + if (!AppState.lastResult) { + showError('No extraction result', 'Run an extraction first before comparing.'); + return; + } + + const refText = DOM.compareTextarea.value.trim(); + if (!refText) { + showError('Empty reference', 'Paste a reference JSON to compare against.'); + return; + } + + let reference; + try { + reference = JSON.parse(refText); + } catch (e) { + showError('Invalid JSON', `Could not parse reference JSON: ${e.message}`); + return; + } + + try { + const response = await fetch('/api/compare', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + extracted: AppState.lastResult.extraction, + reference: reference + }) + }); + + const result = await response.json(); + renderCompareResults(result); + } catch (err) { + showError('Comparison failed', err.message); + } +} + +function renderCompareResults(result) { + const circumference = 2 * Math.PI * 27; + const offset = circumference - (result.accuracy_percent / 100) * circumference; + + let html = ` +
+
+ + + + +
${result.accuracy_percent}%
+
+
+
+ ${result.matches}/${result.total_fields} fields match +
+
+ ${result.note} +
+
+
+ `; + + result.field_results.forEach(fr => { + const icon = fr.match ? '✅' : '❌'; + const iconClass = fr.match ? 'yes' : 'no'; + html += ` +
+ ${icon} + ${fr.field} + ${escapeHtml(fr.extracted ?? 'null')} + → + ${escapeHtml(fr.reference ?? 'null')} +
+ `; + }); + + DOM.compareResults.innerHTML = html; +} + +// ════════════════════════════════════════════════════════════ +// Test History +// ════════════════════════════════════════════════════════════ +function formatTimestamp(isoStr) { + if (!isoStr) return ''; + try { + const d = new Date(isoStr); + return d.toLocaleDateString('en-IN', { + day: 'numeric', + month: 'short', + hour: '2-digit', + minute: '2-digit' + }); + } catch { + return isoStr; + } +} + +async function loadTestHistory() { + try { + const resp = await fetch('/api/test-results'); + const data = await resp.json(); + AppState.testResults = data.results || []; + renderHistory(); + } catch (e) { + console.error('Failed to load test history:', e); + } +} + +function renderHistory() { + if (!DOM.historyBody) return; + + const countEl = document.getElementById('history-count'); + if (countEl) { + countEl.textContent = `${AppState.testResults.length} test${AppState.testResults.length === 1 ? '' : 's'}`; + } + + if (AppState.testResults.length === 0) { + DOM.historyBody.innerHTML = ` + + + No tests run yet. Upload a document and extract to begin. + + + `; + return; + } + + DOM.historyBody.innerHTML = AppState.testResults.map(r => { + const isSuccess = r.status === 'success'; + const statusBadge = isSuccess + ? `● success` + : `● failed`; + const timeDisplay = formatTimestamp(r.timestamp); + + const isGemini = r.model && r.model.toLowerCase().includes('gemini'); + const modelBadge = isGemini + ? `🔷 ${escapeHtml(r.model)}` + : `🔶 ${escapeHtml(r.model || 'DocVision AI')}`; + + return ` + + +
+ ${escapeHtml(r.filename)} +
+ ${timeDisplay} + + ${modelBadge} + ${escapeHtml(r.method || 'auto')} + ${statusBadge} + ${r.api_response_time ? r.api_response_time + 's' : '—'} + ${r.fields_extracted ?? '—'} + ${r.fields_missing ?? '—'} + +
+ ${isSuccess ? `` : ''} + +
+ + + `; + }).join(''); +} + +async function viewHistoryResult(id) { + try { + const resp = await fetch(`/api/test-results/${id}`); + if (!resp.ok) { + showError('Record not found', 'Could not load details for this test.'); + return; + } + const record = await resp.json(); + if (!record || !record.result) return; + + const origUrl = record.has_original_image ? `/api/test-results/${id}/image/original` : null; + const procUrl = record.has_processed_image ? `/api/test-results/${id}/image/processed` : null; + + renderResults({ + filename: record.filename, + extraction: record.result, + total_time_seconds: record.total_time, + preprocessing: record.preprocessing || null, + original_image_url: origUrl, + processed_image_url: procUrl + }); + + if (DOM.resultsContainer) { + DOM.resultsContainer.scrollIntoView({ behavior: 'smooth', block: 'start' }); + } + } catch (e) { + console.error('Failed to view history result:', e); + } +} + +async function deleteHistoryResult(id, event) { + if (event) event.stopPropagation(); + if (!confirm('Delete this test result from history?')) return; + try { + const resp = await fetch(`/api/test-results/${id}`, { method: 'DELETE' }); + if (resp.ok) { + await loadTestHistory(); + } + } catch (e) { + console.error('Delete failed:', e); + } +} + +async function clearAllHistory() { + if (!confirm('Are you sure you want to permanently clear ALL test history and saved images?')) return; + try { + const resp = await fetch('/api/test-results/clear', { method: 'POST' }); + if (resp.ok) { + await loadTestHistory(); + } + } catch (e) { + console.error('Clear history failed:', e); + } +} + +// Expose globally for inline onclick handlers +window.viewHistoryResult = viewHistoryResult; +window.deleteHistoryResult = deleteHistoryResult; +window.clearAllHistory = clearAllHistory; + +// ════════════════════════════════════════════════════════════ +// Downloads +// ════════════════════════════════════════════════════════════ +function downloadJson() { + if (!AppState.lastResult) return; + const extraction = { ...AppState.lastResult.extraction }; + delete extraction._meta; + const blob = new Blob([JSON.stringify(extraction, null, 2)], { type: 'application/json' }); + downloadBlob(blob, `extraction_${Date.now()}.json`); +} + +function downloadText() { + if (!AppState.lastResult) return; + const text = AppState.lastResult.extraction?.raw_transcription || 'No transcription available.'; + const blob = new Blob([text], { type: 'text/plain;charset=utf-8' }); + downloadBlob(blob, `transcription_${Date.now()}.txt`); +} + +function downloadBlob(blob, filename) { + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); +} + +// ════════════════════════════════════════════════════════════ +// Tabs +// ════════════════════════════════════════════════════════════ +function switchTab(tabId) { + document.querySelectorAll('.tab').forEach(t => t.classList.remove('active')); + document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active')); + + const tab = document.querySelector(`.tab[data-tab="${tabId}"]`); + const content = document.getElementById(`tab-${tabId}`); + if (tab) tab.classList.add('active'); + if (content) content.classList.add('active'); +} + +// ════════════════════════════════════════════════════════════ +// Reset +// ════════════════════════════════════════════════════════════ +function handleReset() { + clearFile(); + AppState.lastResult = null; + DOM.resultsContainer.classList.remove('visible'); + DOM.imagePreviewContainer.classList.remove('visible'); + hideError(); + DOM.preprocessToggle.checked = false; + DOM.methodSelect.value = 'auto'; + DOM.compareTextarea.value = ''; + DOM.compareResults.innerHTML = ''; + DOM.preprocessInfo.style.display = 'none'; + window.scrollTo({ top: 0, behavior: 'smooth' }); +} + +// ════════════════════════════════════════════════════════════ +// UI Helpers +// ════════════════════════════════════════════════════════════ +function showLoading() { + DOM.loadingOverlay.classList.add('visible'); +} + +function hideLoading() { + DOM.loadingOverlay.classList.remove('visible'); +} + +function updateLoadingStep(text) { + DOM.loadingStep.textContent = text; +} + +function showError(title, details) { + DOM.errorMessage.textContent = title; + DOM.errorDetails.textContent = details || ''; + DOM.errorDetails.style.display = details ? 'block' : 'none'; + DOM.errorDisplay.classList.add('visible'); +} + +function hideError() { + DOM.errorDisplay.classList.remove('visible'); +} + +function formatFileSize(bytes) { + if (bytes < 1024) return bytes + ' B'; + if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'; + return (bytes / (1024 * 1024)).toFixed(1) + ' MB'; +} + +function formatStepName(step) { + const names = { + 'resize': 'Resized', + 'auto_rotate': 'Deskewed', + 'noise_reduction': 'Denoised', + 'contrast_enhancement': 'Contrast Enhanced', + 'sharpen': 'Sharpened' + }; + return names[step] || step; +} + +function countFields(extraction) { + let count = 0; + ['patient_details', 'hospital_details', 'medical_details'].forEach(section => { + const data = extraction[section]; + if (data && typeof data === 'object') { + Object.values(data).forEach(v => { + if (v !== null && v !== '' && !(Array.isArray(v) && v.length === 0)) count++; + }); + } + }); + return count; +} + +function escapeHtml(text) { + const div = document.createElement('div'); + div.textContent = text; + return div.innerHTML; +} + +// JSON syntax highlighting +function syntaxHighlightJson(json) { + return json.replace( + /("(\\u[\da-fA-F]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(\.\d+)?([eE][+-]?\d+)?)/g, + (match) => { + let cls = 'json-number'; + if (/^"/.test(match)) { + if (/:$/.test(match)) { + cls = 'json-key'; + } else { + cls = 'json-string'; + } + } else if (/true|false/.test(match)) { + cls = 'json-bool'; + } else if (/null/.test(match)) { + cls = 'json-null'; + } + return `${match}`; + } + ); +} diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..5f16058 --- /dev/null +++ b/templates/index.html @@ -0,0 +1,380 @@ + + + + + + + Marathi Handwritten Hospital Form Extraction + + + + + + + +
+
+
+
Processing Document
+
Reading handwritten Marathi text...
+
Initializing...
+
+
+ +
+ +
+
+
📋
+
+

+ Hospital Form Extraction · मराठी व इंग्रजी नोंदणी अर्ज +

+

+ Automated extraction for Marathi & English hospital forms with strict zero-hallucination grounding +

+
+
+
+ + AI Vision · Bilingual OCR +
+
+ + + {% if config_errors %} + {% for err in config_errors %} +
+ ⚠️ +
+ Configuration Required: {{ err }} +
+
+ {% endfor %} + {% endif %} + + +
+ + +
+
+
+ 📄 + Upload Document +
+
+
+
+ + 📋 +
Drop your document here
+
or click to browse files (English or Marathi Form)
+
+ JPG + PNG + PDF + TIFF + BMP +
+
+ +
+ 📎 +
+
+
+
+ +
+ + +
+
+ AI Vision Engine / Model + +
+
+ Gemini Vision Model + + +
+
+ Form Language + +
+
+ Extraction Method + +
+
+ Preprocessing +
+ + Enhance image quality +
+
+
+ + +
+ + +
+ + +
+ + +
+ + +
+
❌ Error
+
+
+
+
+
+ + +
+
+
+ 🖼️ + Document Preview +
+
+
+
+
+
Original
+ Original document +
+ +
+ +
+ 🖼️ + Upload a document to see a preview +
+
+
+ + +
+
+
+ 📊 + Extraction Results +
+
+ + +
+
+
+ +
+
+ ⏱️ +
+
—
+
Response Time
+
+
+
+ 🌐 +
+
—
+
Form Language
+
+
+
+ ✅ +
+
—
+
Fields Extracted
+
+
+
+ ✨ +
+
0
+
Repaired Slips
+
+
+
+ ⚠️ +
+
—
+
Unfilled Fields
+
+
+
+ 🔧 +
+
—
+
Method Used
+
+
+
+ 🤖 +
+
—
+
AI Engine
+
+
+
+ + +
+ + + + + + +
+ + +
+
+
+ + +
+
+
+ + +
+
+
+ + +
+

+                    
+ + +
+
+
+ + +
+

+ Paste a reference JSON (with the same structure) to compare extraction accuracy: +

+ + +
+
+
+
+ + +
+
+
+ 📜 + Persistent Test History + 0 tests +
+
+ 📥 Export CSV + 📥 Export JSON + +
+
+
+
+ + + + + + + + + + + + + + + + + + +
Document & DateModel EngineMethodStatusAPI TimeExtractedMissingActions
+ No tests run yet. Upload a document and extract to begin. +
+
+
+
+ +
+ + + +
+ Automated Healthcare Document Intelligence · Marathi (मराठी) Vision OCR +
+
+ + + + + \ No newline at end of file diff --git a/text_repair_engine.py b/text_repair_engine.py new file mode 100644 index 0000000..ce20edd --- /dev/null +++ b/text_repair_engine.py @@ -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