368 lines
13 KiB
Python
368 lines
13 KiB
Python
"""
|
|
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}"
|
|
)
|