Files
2026-10-19 10:59:31 +05:30

274 lines
12 KiB
Python

"""
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