Files
handwritten_extraction/app.py
T
2026-10-19 10:59:31 +05:30

744 lines
28 KiB
Python

"""
Flask application — Handwritten Marathi Hospital Form Extraction
using Sarvam AI Vision Document Intelligence API.
"""
import os
import json
import time
import uuid
import logging
import base64
from datetime import datetime
from flask import (
Flask, render_template, request, jsonify,
send_from_directory, redirect, url_for, send_file, Response
)
from werkzeug.utils import secure_filename
from config import Config
from sarvam_client import SarvamClient, SarvamAPIError
from gemini_client import GeminiClient, GeminiAPIError
from image_preprocessor import ImagePreprocessor
from extraction_schema import EMPTY_RESPONSE_TEMPLATE
from history_manager import HistoryManager
import concurrent.futures
# ──────────────────────────────────────────────────────────────────────
# Logging
# ──────────────────────────────────────────────────────────────────────
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s"
)
logger = logging.getLogger(__name__)
# ──────────────────────────────────────────────────────────────────────
# Flask App
# ──────────────────────────────────────────────────────────────────────
app = Flask(__name__)
app.secret_key = Config.SECRET_KEY
app.config["MAX_CONTENT_LENGTH"] = Config.MAX_CONTENT_LENGTH
# Ensure upload directory exists
os.makedirs(Config.UPLOAD_FOLDER, exist_ok=True)
# Persistent test history is handled by HistoryManager (stored in data/test_history.json)
def allowed_file(filename: str) -> bool:
"""Check if the file extension is allowed."""
return (
"." in filename
and filename.rsplit(".", 1)[1].lower() in Config.ALLOWED_EXTENSIONS
)
def get_mime_type(filename: str) -> str:
"""Get MIME type from filename extension."""
ext = filename.rsplit(".", 1)[1].lower() if "." in filename else ""
mime_map = {
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
"bmp": "image/bmp",
"tiff": "image/tiff",
"tif": "image/tiff",
"pdf": "application/pdf",
}
return mime_map.get(ext, "application/octet-stream")
# ──────────────────────────────────────────────────────────────────────
# Model Runners
# ──────────────────────────────────────────────────────────────────────
def _run_sarvam(extraction_bytes, filename, mime_type, api_lang, method="auto"):
"""Execute document extraction using Sarvam Vision API."""
client = SarvamClient()
if method == "extract":
return client.extract(extraction_bytes, filename, mime_type, language=api_lang)
elif method == "digitise":
return client.digitise(extraction_bytes, filename, mime_type, language=api_lang)
else:
return client.extract_with_fallback(extraction_bytes, filename, mime_type, language=api_lang)
def _run_gemini(extraction_bytes, filename, mime_type, api_lang, model_name=None):
"""Execute document extraction using Google Gemini Vision API."""
client = GeminiClient(model=model_name)
return client.extract(extraction_bytes, filename, mime_type, language=api_lang)
# ──────────────────────────────────────────────────────────────────────
# Routes
# ──────────────────────────────────────────────────────────────────────
@app.route("/")
def index():
"""Render the main dashboard."""
config_errors = Config.validate()
models_status = Config.get_configured_models()
return render_template(
"index.html",
config_errors=config_errors,
models_status=models_status,
gemini_model=Config.get_gemini_model()
)
@app.route("/api/models", methods=["GET"])
def api_models():
"""Return available and configured AI Vision models."""
configured = Config.get_configured_models()
return jsonify({
"configured": configured,
"default_gemini_model": Config.get_gemini_model(),
"available_gemini_models": [
"gemini-3.8-flash",
"gemini-flash-latest",
"gemini-3.6-flash",
"gemini-3.5-flash",
"gemini-2.5-flash"
]
})
@app.route("/api/extract", methods=["POST"])
def api_extract():
"""
Handle document upload and extraction.
Accepts multipart form data with:
- file: The document image/PDF
- preprocess: "true" or "false"
- method: "extract", "digitise", or "auto" (default: "auto")
"""
start_time = time.time()
# ── Validate file ──
if "file" not in request.files:
return jsonify({"error": "No file uploaded."}), 400
file = request.files["file"]
if file.filename == "" or not file.filename:
return jsonify({"error": "No file selected."}), 400
if not allowed_file(file.filename):
return jsonify({
"error": f"File type not allowed. Supported: {', '.join(Config.ALLOWED_EXTENSIONS)}"
}), 400
filename = secure_filename(file.filename)
file_bytes = file.read()
mime_type = get_mime_type(filename)
# ── Options ──
do_preprocess = request.form.get("preprocess", "false").lower() == "true"
method = request.form.get("method", "auto").lower()
selected_language = request.form.get("language", "auto")
model_choice = request.form.get("model", "auto").lower()
gemini_model_custom = request.form.get("gemini_model", "").strip() or Config.get_gemini_model()
api_lang = None
if selected_language in ("mr-IN", "mr", "marathi"):
api_lang = "mr-IN"
elif selected_language in ("en-IN", "en", "english"):
api_lang = "en-IN"
# ── Preprocessing ──
preprocessing_info = None
original_b64 = None
processed_b64 = None
if mime_type.startswith("image/"):
# Always provide original preview
original_b64 = base64.b64encode(file_bytes).decode("utf-8")
if do_preprocess:
try:
processed_bytes, preprocessing_info = ImagePreprocessor.preprocess(file_bytes)
processed_b64 = base64.b64encode(processed_bytes).decode("utf-8")
# Use processed image for extraction
extraction_bytes = processed_bytes
except Exception as e:
logger.warning(f"Preprocessing failed, using original: {e}")
preprocessing_info = {"error": str(e), "steps_applied": []}
extraction_bytes = file_bytes
else:
extraction_bytes = file_bytes
else:
# PDF or other — skip preprocessing
extraction_bytes = file_bytes
ext = filename.rsplit(".", 1)[1].lower() if "." in filename else "jpg"
# ── MODE 1: Dual-Model Comparison Benchmark (Run Both Parallel) ──
if model_choice == "compare":
logger.info(f"Initiating dual-model comparison benchmark: Gemini ({gemini_model_custom}) vs Sarvam DocVision AI")
gemini_res = None
sarvam_res = None
gemini_err = None
sarvam_err = None
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
fut_gemini = executor.submit(_run_gemini, extraction_bytes, filename, mime_type, api_lang, gemini_model_custom)
fut_sarvam = executor.submit(_run_sarvam, extraction_bytes, filename, mime_type, api_lang, method)
try:
gemini_res = fut_gemini.result()
except Exception as e:
gemini_err = str(e)
logger.warning(f"Gemini comparison branch error: {e}")
try:
sarvam_res = fut_sarvam.result()
except Exception as e:
sarvam_err = str(e)
logger.warning(f"Sarvam comparison branch error: {e}")
# If both failed
if not gemini_res and not sarvam_res:
return jsonify({
"error": f"Both vision models failed to extract. Gemini: {gemini_err} | Sarvam: {sarvam_err}"
}), 500
total_time = round(time.time() - start_time, 2)
gemini_hist_id = None
sarvam_hist_id = None
# Store Gemini run in history if successful
if gemini_res:
gem_entry = {
"id": str(uuid.uuid4())[:8],
"filename": filename,
"timestamp": datetime.now().isoformat(),
"model": gemini_res.get("_meta", {}).get("model", f"Gemini ({gemini_model_custom})"),
"method": "gemini_vision",
"status": "success",
"api_response_time": gemini_res.get("_meta", {}).get("api_response_time_seconds"),
"total_time": total_time,
"fields_extracted": _count_extracted_fields(gemini_res),
"fields_missing": len(gemini_res.get("unreadable_fields", [])),
"raw_transcription": gemini_res.get("raw_transcription", ""),
"result": gemini_res,
"preprocessing": preprocessing_info
}
saved_gem = HistoryManager.add_entry(
gem_entry,
original_bytes=file_bytes if mime_type.startswith("image/") else None,
file_ext=ext
)
gemini_hist_id = saved_gem["id"]
# Store Sarvam run in history if successful
if sarvam_res:
sar_entry = {
"id": str(uuid.uuid4())[:8],
"filename": filename,
"timestamp": datetime.now().isoformat(),
"model": sarvam_res.get("_meta", {}).get("model", "DocVision AI"),
"method": sarvam_res.get("_meta", {}).get("method", method),
"status": "success",
"api_response_time": sarvam_res.get("_meta", {}).get("api_response_time_seconds"),
"total_time": total_time,
"fields_extracted": _count_extracted_fields(sarvam_res),
"fields_missing": len(sarvam_res.get("unreadable_fields", [])),
"raw_transcription": sarvam_res.get("raw_transcription", ""),
"result": sarvam_res,
"preprocessing": preprocessing_info
}
saved_sar = HistoryManager.add_entry(
sar_entry,
original_bytes=file_bytes if mime_type.startswith("image/") else None,
file_ext=ext
)
sarvam_hist_id = saved_sar["id"]
# Perform side-by-side comparison breakdown if both succeeded
comparison_data = None
if gemini_res and sarvam_res:
comparison_data = _compare_models(
gemini_res,
sarvam_res,
label_a=f"Gemini ({gemini_model_custom})",
label_b="DocVision AI (Sarvam)"
)
primary_result = gemini_res if gemini_res else sarvam_res
return jsonify({
"success": True,
"is_comparison": True,
"filename": filename,
"extraction": primary_result,
"gemini_result": gemini_res,
"sarvam_result": sarvam_res,
"gemini_error": gemini_err,
"sarvam_error": sarvam_err,
"comparison": comparison_data,
"gemini_history_id": gemini_hist_id,
"sarvam_history_id": sarvam_hist_id,
"history_id": gemini_hist_id or sarvam_hist_id,
"preprocessing": preprocessing_info,
"original_image_b64": original_b64,
"processed_image_b64": processed_b64,
"total_time_seconds": total_time,
"timestamp": datetime.now().isoformat()
})
# ── MODE 2: Single-Model Extraction ──
target_model = model_choice
configured = Config.get_configured_models()
if target_model == "auto":
if configured["gemini"] and not configured["sarvam"]:
target_model = "gemini"
elif configured["sarvam"] and not configured["gemini"]:
target_model = "sarvam"
elif configured["gemini"] and configured["sarvam"]:
target_model = "gemini"
else:
return jsonify({
"error": "No Vision API key configured. Please set SARVAM_API_KEY or GEMINI_API_KEY in your .env file."
}), 400
try:
if target_model == "gemini":
result = _run_gemini(extraction_bytes, filename, mime_type, api_lang, gemini_model_custom)
else:
result = _run_sarvam(extraction_bytes, filename, mime_type, api_lang, method)
except (GeminiAPIError, SarvamAPIError) as e:
logger.error(f"Vision API error ({target_model}): {e}")
model_name_tag = f"Gemini ({gemini_model_custom})" if target_model == "gemini" else "DocVision AI"
fail_entry = {
"id": str(uuid.uuid4())[:8],
"filename": filename,
"timestamp": datetime.now().isoformat(),
"model": model_name_tag,
"method": method,
"status": "failed",
"error": str(e),
"api_response_time": None,
"total_time": round(time.time() - start_time, 2),
"fields_extracted": 0,
"fields_missing": 0,
"raw_transcription": "",
"result": None
}
HistoryManager.add_entry(fail_entry)
return jsonify({
"error": str(e),
"status_code": getattr(e, "status_code", 500),
"model": model_name_tag
}), getattr(e, "status_code", 500) or 500
except Exception as e:
logger.exception(f"Unexpected error during extraction: {e}")
fail_entry = {
"id": str(uuid.uuid4())[:8],
"filename": filename,
"timestamp": datetime.now().isoformat(),
"model": "DocVision AI" if target_model != "gemini" else f"Gemini ({gemini_model_custom})",
"method": method,
"status": "failed",
"error": str(e),
"api_response_time": None,
"total_time": round(time.time() - start_time, 2),
"fields_extracted": 0,
"fields_missing": 0,
"raw_transcription": "",
"result": None
}
HistoryManager.add_entry(fail_entry)
return jsonify({"error": f"Internal error: {str(e)}"}), 500
total_time = round(time.time() - start_time, 2)
# ── Build response ──
response = {
"success": True,
"is_comparison": False,
"filename": filename,
"extraction": result,
"preprocessing": preprocessing_info,
"original_image_b64": original_b64,
"processed_image_b64": processed_b64,
"total_time_seconds": total_time,
"timestamp": datetime.now().isoformat()
}
# ── Store test result in persistent history ──
test_entry = {
"id": str(uuid.uuid4())[:8],
"filename": filename,
"timestamp": response["timestamp"],
"model": result.get("_meta", {}).get("model", "DocVision AI"),
"method": result.get("_meta", {}).get("method", method),
"status": "success",
"api_response_time": result.get("_meta", {}).get("api_response_time_seconds"),
"total_time": total_time,
"fields_extracted": _count_extracted_fields(result),
"fields_missing": len(result.get("unreadable_fields", [])),
"raw_transcription": result.get("raw_transcription", ""),
"result": result,
"preprocessing": preprocessing_info
}
saved_entry = HistoryManager.add_entry(
test_entry,
original_bytes=file_bytes if mime_type.startswith("image/") else None,
processed_bytes=processed_bytes if (do_preprocess and 'processed_bytes' in locals()) else None,
file_ext=ext
)
response["history_id"] = saved_entry["id"]
return jsonify(response)
@app.route("/api/test-results", methods=["GET"])
def api_test_results():
"""Return all persistent test results."""
return jsonify({"results": HistoryManager.get_all()})
@app.route("/api/test-results/<result_id>", methods=["GET"])
def api_get_test_result(result_id):
"""Return full details for a specific test result."""
result = HistoryManager.get_by_id(result_id)
if not result:
return jsonify({"error": "Test result not found"}), 404
return jsonify(result)
@app.route("/api/test-results/<result_id>/image/<image_type>", methods=["GET"])
def api_get_test_image(result_id, image_type):
"""Serve the saved image (original or processed) for a history test."""
if image_type not in ("original", "processed"):
return jsonify({"error": "Invalid image type"}), 400
path = HistoryManager.get_image_path(result_id, image_type)
if not path or not os.path.exists(path):
return jsonify({"error": "Image not found"}), 404
return send_file(path)
@app.route("/api/test-results/<result_id>", methods=["DELETE"])
def api_delete_test_result(result_id):
"""Delete a specific test result from persistent history."""
success = HistoryManager.delete_entry(result_id)
return jsonify({"success": success})
@app.route("/api/test-results/clear", methods=["POST", "DELETE"])
def api_clear_test_results():
"""Clear all test results from persistent history."""
HistoryManager.clear_all()
return jsonify({"success": True, "message": "All history cleared."})
@app.route("/api/test-results/export/csv", methods=["GET"])
def api_export_history_csv():
"""Export all test history summary as a downloadable CSV."""
csv_data = HistoryManager.export_csv()
return Response(
csv_data,
mimetype="text/csv",
headers={"Content-Disposition": f"attachment;filename=marathi_ocr_history_{int(time.time())}.csv"}
)
@app.route("/api/test-results/export/json", methods=["GET"])
def api_export_history_json():
"""Export all test history and full extractions as downloadable JSON."""
records = HistoryManager.get_all()
return Response(
json.dumps(records, ensure_ascii=False, indent=2),
mimetype="application/json",
headers={"Content-Disposition": f"attachment;filename=marathi_ocr_history_{int(time.time())}.json"}
)
@app.route("/api/compare", methods=["POST"])
def api_compare():
"""
Compare extraction result against a manually provided reference JSON.
Calculates field-level match statistics.
"""
data = request.get_json()
if not data:
return jsonify({"error": "No JSON body provided."}), 400
extracted = data.get("extracted", {})
reference = data.get("reference", {})
comparison = _compare_results(extracted, reference)
return jsonify(comparison)
@app.route("/api/compare-models", methods=["POST"])
def api_compare_models():
"""
Compare two specific extraction runs (e.g., Gemini vs Sarvam) side-by-side.
Accepts JSON body with:
- id_a: History ID of first run (e.g. Gemini)
- id_b: History ID of second run (e.g. Sarvam)
or
- result_a: Direct result dict
- result_b: Direct result dict
"""
data = request.get_json() or {}
result_a = data.get("result_a")
result_b = data.get("result_b")
label_a = data.get("label_a", "Model A")
label_b = data.get("label_b", "Model B")
if not result_a and data.get("id_a"):
entry_a = HistoryManager.get_by_id(data["id_a"])
if entry_a:
result_a = entry_a.get("result")
label_a = entry_a.get("model", "Model A")
if not result_b and data.get("id_b"):
entry_b = HistoryManager.get_by_id(data["id_b"])
if entry_b:
result_b = entry_b.get("result")
label_b = entry_b.get("model", "Model B")
if not result_a or not result_b:
return jsonify({"error": "Could not locate both results to compare."}), 400
comparison = _compare_models(result_a, result_b, label_a=label_a, label_b=label_b)
return jsonify(comparison)
@app.route("/api/health", methods=["GET"])
def api_health():
"""Health check endpoint."""
config_errors = Config.validate()
configured_models = Config.get_configured_models()
return jsonify({
"status": "ok" if not config_errors else "warning",
"config_errors": config_errors,
"configured_models": configured_models,
"language": Config.DOCUMENT_LANGUAGE,
"content_type": Config.CONTENT_TYPE
})
# ──────────────────────────────────────────────────────────────────────
# Helper Functions
# ──────────────────────────────────────────────────────────────────────
def _count_extracted_fields(result: dict) -> int:
"""Count non-null fields in the extraction result."""
count = 0
sections = (
"patient_details", "hospital_details", "address_details",
"billing_details", "representative_details", "medical_details"
)
for section in sections:
section_data = result.get(section, {})
if isinstance(section_data, dict):
for key, val in section_data.items():
if val is not None and val != "" and val != []:
count += 1
if result.get("document_type"):
count += 1
if result.get("raw_transcription"):
count += 1
return count
def _compare_models(result_a: dict, result_b: dict, label_a: str = "Gemini", label_b: str = "Sarvam") -> dict:
"""
Compare two model extraction outputs field-by-field.
Classifies each field into MATCH, DIFFERENT, ONLY_IN_A, ONLY_IN_B, or BOTH_EMPTY.
"""
sections = [
("hospital_details", "Hospital & Registration"),
("patient_details", "Patient Identification"),
("address_details", "Address Information"),
("billing_details", "Billing & Financial"),
("representative_details", "Representative Details"),
("medical_details", "Clinical & Medical")
]
repaired_a = {r["field"]: r for r in result_a.get("repaired_fields", [])}
repaired_b = {r["field"]: r for r in result_b.get("repaired_fields", [])}
matches = 0
mismatches = 0
only_a = 0
only_b = 0
both_empty = 0
field_rows = []
for sec_key, sec_title in sections:
sec_a = result_a.get(sec_key, {}) or {}
sec_b = result_b.get(sec_key, {}) or {}
all_keys = sorted(set(list(sec_a.keys()) + list(sec_b.keys())))
for field in all_keys:
val_a = sec_a.get(field)
val_b = sec_b.get(field)
is_empty_a = val_a is None or val_a == "" or val_a == []
is_empty_b = val_b is None or val_b == "" or val_b == []
if is_empty_a and is_empty_b:
both_empty += 1
status = "BOTH_EMPTY"
elif is_empty_a and not is_empty_b:
only_b += 1
status = "ONLY_IN_B"
elif not is_empty_a and is_empty_b:
only_a += 1
status = "ONLY_IN_A"
else:
norm_a = str(val_a).strip().lower()
norm_b = str(val_b).strip().lower()
if norm_a == norm_b:
matches += 1
status = "MATCH"
else:
mismatches += 1
status = "DIFFERENT"
field_rows.append({
"section": sec_key,
"section_title": sec_title,
"field": field,
"value_a": val_a,
"value_b": val_b,
"status": status,
"repaired_a": field in repaired_a,
"repaired_b": field in repaired_b,
"note_a": repaired_a.get(field, {}).get("note"),
"note_b": repaired_b.get(field, {}).get("note")
})
active_fields = matches + mismatches + only_a + only_b
agreement_pct = round((matches / (matches + mismatches) * 100), 1) if (matches + mismatches) > 0 else 0
overall_match_pct = round((matches / active_fields * 100), 1) if active_fields > 0 else 0
return {
"model_a": label_a,
"model_b": label_b,
"time_a_seconds": result_a.get("_meta", {}).get("api_response_time_seconds"),
"time_b_seconds": result_b.get("_meta", {}).get("api_response_time_seconds"),
"fields_a_count": _count_extracted_fields(result_a),
"fields_b_count": _count_extracted_fields(result_b),
"repairs_a_count": len(result_a.get("repaired_fields", [])),
"repairs_b_count": len(result_b.get("repaired_fields", [])),
"matches": matches,
"mismatches": mismatches,
"only_a": only_a,
"only_b": only_b,
"both_empty": both_empty,
"active_fields": active_fields,
"agreement_percent": agreement_pct,
"overall_match_percent": overall_match_pct,
"field_rows": field_rows
}
def _compare_results(extracted: dict, reference: dict) -> dict:
"""
Compare extracted fields against reference JSON.
Dynamically compares all fields present across all sections.
Returns per-field match results and overall statistics.
"""
sections = [
"hospital_details", "patient_details", "address_details",
"billing_details", "representative_details", "medical_details"
]
matches = 0
mismatches = 0
field_results = []
for section in sections:
ext_sec = extracted.get(section, {}) or {}
ref_sec = reference.get(section, {}) or {}
all_keys = sorted(set(list(ext_sec.keys()) + list(ref_sec.keys())))
for field in all_keys:
ext_val = ext_sec.get(field)
ref_val = ref_sec.get(field)
# Skip if both are null or empty
if (ext_val is None or ext_val == "") and (ref_val is None or ref_val == ""):
continue
# Normalize strings for comparison (whitespace & casing)
ext_norm = (ext_val or "").strip().lower() if isinstance(ext_val, str) else ext_val
ref_norm = (ref_val or "").strip().lower() if isinstance(ref_val, str) else ref_val
is_match = ext_norm == ref_norm
if is_match:
matches += 1
else:
mismatches += 1
field_results.append({
"section": section,
"field": field,
"extracted": ext_val,
"reference": ref_val,
"match": is_match
})
total = matches + mismatches
accuracy = round((matches / total * 100), 1) if total > 0 else 0
return {
"total_fields": total,
"matches": matches,
"mismatches": mismatches,
"accuracy_percent": accuracy,
"field_results": field_results,
"note": "Accuracy is calculated from field-level value matching against reference values."
}
# ──────────────────────────────────────────────────────────────────────
# Main
# ──────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
logger.info("=" * 60)
logger.info("Handwritten Marathi Hospital Form Extraction")
logger.info("Powered by DocVision AI")
logger.info("=" * 60)
errors = Config.validate()
if errors:
for err in errors:
logger.warning(f"⚠ {err}")
app.run(
host="0.0.0.0",
port=Config.PORT,
debug=Config.DEBUG
)