File size: 17,762 Bytes
4cb7a47
 
 
 
751d99f
4cb7a47
8dbd19f
9dd5673
 
 
4cb7a47
 
 
 
751d99f
8dbd19f
4cb7a47
 
 
 
 
 
8dbd19f
4cb7a47
8dbd19f
4cb7a47
 
751d99f
4cb7a47
 
 
 
 
751d99f
 
 
 
 
 
 
 
 
9dd5673
 
 
 
751d99f
 
9dd5673
4cb7a47
 
9dd5673
4cb7a47
 
9dd5673
4cb7a47
 
 
 
 
 
 
 
 
 
 
8dbd19f
9dd5673
8dbd19f
9dd5673
 
 
8dbd19f
 
 
9dd5673
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8dbd19f
 
 
9dd5673
 
8dbd19f
 
 
 
 
 
 
9dd5673
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8dbd19f
9dd5673
 
 
 
8dbd19f
 
 
 
 
 
 
 
 
 
 
 
 
 
9dd5673
8dbd19f
9dd5673
8dbd19f
 
 
 
 
 
 
 
 
9dd5673
 
8dbd19f
 
 
 
 
 
9dd5673
8dbd19f
 
 
9dd5673
 
8dbd19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03cb77a
 
 
 
 
8dbd19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cb7a47
 
 
 
 
 
 
 
 
9dd5673
4cb7a47
9dd5673
4cb7a47
 
 
 
 
 
 
 
 
9dd5673
4cb7a47
 
 
 
 
 
 
8dbd19f
9dd5673
 
 
8dbd19f
 
9dd5673
4cb7a47
 
 
9dd5673
 
 
4cb7a47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9dd5673
4cb7a47
 
 
 
9dd5673
 
 
 
4cb7a47
 
 
 
 
 
9dd5673
4cb7a47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
751d99f
4cb7a47
 
 
9dd5673
 
 
 
4cb7a47
9dd5673
4cb7a47
 
 
751d99f
4cb7a47
751d99f
4cb7a47
 
 
9dd5673
8dbd19f
9dd5673
8dbd19f
9dd5673
8dbd19f
 
 
 
9dd5673
751d99f
9dd5673
 
 
 
 
 
 
 
 
 
 
 
 
8dbd19f
9dd5673
 
 
8dbd19f
 
 
751d99f
4cb7a47
9dd5673
4cb7a47
9dd5673
 
8dbd19f
9dd5673
751d99f
9dd5673
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cb7a47
9dd5673
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8dbd19f
 
4cb7a47
 
 
 
8dbd19f
 
 
 
4cb7a47
 
 
8dbd19f
 
 
 
4cb7a47
8dbd19f
 
 
 
4cb7a47
9dd5673
 
 
 
4cb7a47
8dbd19f
4cb7a47
8dbd19f
4cb7a47
 
 
 
8dbd19f
9dd5673
 
8dbd19f
 
 
 
 
4cb7a47
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
"""
Surya OCR - Universal REST API
One endpoint: POST /ocr β€” any file in, extracted text out.
Supports: Images, PDF, Word (.docx/.doc), PowerPoint (.pptx/.ppt), and more.
Secret key authentication via X-API-Key header.
Hugging Face Spaces (Free Tier) compatible.

`document_type` is REQUIRED β€” must be one of the supported types.
`parameters`    is REQUIRED β€” comma-separated field names the caller wants extracted.
Both drive structured JSON extraction via the Sarvam-M LLM.
"""

import io
import gc
import os
import json
import logging
import subprocess
import tempfile
from contextlib import asynccontextmanager
from pathlib import Path

import httpx
import uvicorn
from fastapi import FastAPI, File, Form, UploadFile, HTTPException, Security
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.security import APIKeyHeader
from PIL import Image

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# ── Auth ──────────────────────────────────────────────────────────────────────
API_SECRET_KEY = os.environ.get("API_SECRET_KEY", "")

api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)

def verify_key(api_key: str = Security(api_key_header)):
    if not API_SECRET_KEY:
        raise RuntimeError("API_SECRET_KEY environment variable is not set on the server.")
    if api_key != API_SECRET_KEY:
        raise HTTPException(
            status_code=401,
            detail="Invalid or missing API key. Pass it as X-API-Key header.",
        )
    return api_key


# ── Global model holders ──────────────────────────────────────────────────────
recognition_predictor = None
detection_predictor   = None

MAX_FILE_SIZE_MB = 30
MAX_PAGES        = 10

SUPPORTED_EXTENSIONS = {
    ".jpg", ".jpeg", ".png", ".webp", ".tiff", ".tif", ".bmp",
    ".pdf",
    ".docx", ".doc",
    ".pptx", ".ppt",
    ".odt", ".odp",
    ".rtf",
}


# ── Document Type Registry ────────────────────────────────────────────────────
# Only descriptions live here β€” fields are supplied by the caller via `parameters`.
#
# To add a new document type:
#   1. Add a new entry with a "description" key below.
#   2. No other code changes needed.

DOCUMENT_TYPES: dict[str, dict] = {
    "income_certificate": {
        "description": (
            "A government-issued income certificate that certifies the annual income "
            "of an individual or family for official and welfare purposes."
        ),
    },
    "caste_certificate": {
        "description": (
            "A government-issued caste certificate that officially recognises the caste "
            "category (SC / ST / OBC / etc.) of an individual for reservation and welfare purposes."
        ),
    },
    "domicile_certificate": {
        "description": (
            "A government-issued domicile certificate that proves an individual's permanent "
            "residence in a particular state or union territory."
        ),
    },
}

SUPPORTED_DOCUMENT_TYPES = sorted(DOCUMENT_TYPES.keys())


# ── Sarvam LLM Integration ────────────────────────────────────────────────────
SARVAM_API_KEY = os.environ.get("SARVAM_API_KEY", "")
SARVAM_API_URL = "https://api.sarvam.ai/v1/chat/completions"
SARVAM_MODEL   = "sarvam-m"


def parse_parameters(raw: str) -> list[str]:
    """
    Parse the comma-separated `parameters` string into a clean list of field names.
    e.g.  "name, income , income_in_words"  β†’  ["name", "income", "income_in_words"]
    """
    fields = [f.strip() for f in raw.split(",") if f.strip()]
    if not fields:
        raise HTTPException(
            status_code=400,
            detail=(
                "`parameters` must be a non-empty comma-separated list of field names. "
                "Example: parameters=name,income,income_in_words,validity"
            ),
        )
    return fields


def build_extraction_prompt(doc_type: str, fields: list[str], extracted_text: str) -> str:
    """Build a prompt so the LLM extracts exactly the fields the caller requested."""
    description = DOCUMENT_TYPES[doc_type]["description"]
    fields_list = "\n".join(f"- {f}" for f in fields)
    json_keys   = ", ".join(f'"{f}"' for f in fields)

    return f"""You are a precise document parser. You will be given raw OCR text extracted from a document.

Document Type: {doc_type.replace("_", " ").title()}
Description: {description}

Your task is to extract the following fields from the text:
{fields_list}

Rules:
- Return ONLY a valid JSON object with these exact keys: {json_keys}
- If a field cannot be found in the text, set its value to null.
- If any two related parameters do not match (possibly due to an OCR error), smartly return null.
- Do NOT include any explanation, markdown, or extra text β€” pure JSON only.
- Normalise values where sensible (e.g. trim whitespace, fix obvious OCR typos in names/numbers).

OCR Text:
\"\"\"
{extracted_text}
\"\"\"

JSON Output:"""


async def extract_structured_data(doc_type: str, fields: list[str], extracted_text: str) -> dict:
    """Call Sarvam-M to extract the caller-specified fields from OCR text."""
    if not SARVAM_API_KEY:
        raise HTTPException(
            status_code=503,
            detail="SARVAM_API_KEY environment variable is not set on the server.",
        )

    prompt = build_extraction_prompt(doc_type, fields, extracted_text)

    payload = {
        "model": SARVAM_MODEL,
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.0,  # deterministic for structured extraction
        "max_tokens": 512,
    }
    headers = {
        "Authorization": f"Bearer {SARVAM_API_KEY}",
        "Content-Type": "application/json",
    }

    try:
        async with httpx.AsyncClient(timeout=60) as client:
            response = await client.post(SARVAM_API_URL, json=payload, headers=headers)
            response.raise_for_status()
    except httpx.HTTPStatusError as e:
        raise HTTPException(
            status_code=502,
            detail=f"Sarvam API returned an error: {e.response.status_code} β€” {e.response.text}",
        )
    except httpx.RequestError as e:
        raise HTTPException(status_code=502, detail=f"Failed to reach Sarvam API: {e}")

    resp_json = response.json()

    try:
        raw_content = resp_json["choices"][0]["message"]["content"].strip()
    except (KeyError, IndexError) as e:
        raise HTTPException(
            status_code=502,
            detail=f"Unexpected Sarvam API response structure: {e} β€” {resp_json}",
        )

    # Strip <think>...</think> chain-of-thought block if present (Sarvam-M reasoning output)
    if "<think>" in raw_content:
        import re
        raw_content = re.sub(r"<think>.*?</think>", "", raw_content, flags=re.DOTALL).strip()

    # Strip markdown code fences if the LLM added them despite instructions
    if raw_content.startswith("```"):
        raw_content = raw_content.strip("`").lstrip("json").strip()

    try:
        structured = json.loads(raw_content)
    except json.JSONDecodeError:
        logger.warning(f"LLM returned non-JSON content: {raw_content!r}")
        raise HTTPException(
            status_code=502,
            detail=f"LLM did not return valid JSON. Raw response: {raw_content}",
        )

    return structured


# ── Model loading ─────────────────────────────────────────────────────────────

def load_models():
    global recognition_predictor, detection_predictor
    logger.info("Loading Surya OCR models...")
    from surya.foundation import FoundationPredictor
    from surya.recognition import RecognitionPredictor
    from surya.detection import DetectionPredictor

    foundation            = FoundationPredictor()
    recognition_predictor = RecognitionPredictor(foundation)
    detection_predictor   = DetectionPredictor()
    logger.info("Models loaded.")


@asynccontextmanager
async def lifespan(app: FastAPI):
    load_models()
    yield
    global recognition_predictor, detection_predictor
    recognition_predictor = None
    detection_predictor   = None
    gc.collect()


# ── App ───────────────────────────────────────────────────────────────────────

app = FastAPI(
    title="Surya OCR API",
    description=(
        "Upload any document β€” image, PDF, Word, PowerPoint β€” and receive raw OCR text "
        "plus structured JSON fields you define. "
        "`document_type` and `parameters` are both required. "
        "Requires X-API-Key header."
    ),
    version="4.0.0",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
)


# ── File β†’ PIL Images converters ──────────────────────────────────────────────

def convert_image(data: bytes) -> list:
    return [Image.open(io.BytesIO(data)).convert("RGB")]


def convert_pdf(data: bytes) -> list:
    from pdf2image import convert_from_bytes
    return convert_from_bytes(data, dpi=150, first_page=1, last_page=MAX_PAGES, fmt="RGB")


def convert_office(data: bytes, suffix: str) -> list:
    with tempfile.TemporaryDirectory() as tmpdir:
        input_path = Path(tmpdir) / f"input{suffix}"
        input_path.write_bytes(data)

        result = subprocess.run(
            ["libreoffice", "--headless", "--convert-to", "pdf",
             "--outdir", tmpdir, str(input_path)],
            capture_output=True, timeout=60,
        )
        if result.returncode != 0:
            raise HTTPException(
                status_code=422,
                detail=f"LibreOffice conversion failed: {result.stderr.decode()}",
            )

        pdf_path = Path(tmpdir) / (input_path.stem + ".pdf")
        if not pdf_path.exists():
            raise HTTPException(
                status_code=422,
                detail="Office-to-PDF conversion produced no output.",
            )

        from pdf2image import convert_from_path
        return convert_from_path(str(pdf_path), dpi=150, first_page=1, last_page=MAX_PAGES, fmt="RGB")


def file_to_images(data: bytes, suffix: str) -> list:
    image_exts  = {".jpg", ".jpeg", ".png", ".webp", ".tiff", ".tif", ".bmp"}
    office_exts = {".docx", ".doc", ".pptx", ".ppt", ".odt", ".odp", ".rtf"}

    if suffix in image_exts:
        return convert_image(data)
    elif suffix == ".pdf":
        return convert_pdf(data)
    elif suffix in office_exts:
        return convert_office(data, suffix)
    else:
        raise HTTPException(status_code=415, detail=f"Unsupported file type: '{suffix}'")


# ── OCR runner ────────────────────────────────────────────────────────────────

def run_ocr(images: list) -> str:
    if recognition_predictor is None:
        raise HTTPException(status_code=503, detail="Models not ready. Please retry in a moment.")

    try:
        predictions = recognition_predictor(images, det_predictor=detection_predictor)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"OCR failed: {e}")

    pages_text = []
    for page in predictions:
        page_lines = [line.text for line in page.text_lines]
        pages_text.append("\n".join(page_lines))

    return "\n\n".join(pages_text)


# ── Routes ────────────────────────────────────────────────────────────────────

@app.get("/", summary="Health / Info")
def root():
    """Public endpoint β€” no key required."""
    return {
        "service": "Surya OCR API",
        "status": "ready" if recognition_predictor else "loading",
        "usage": (
            "POST /ocr  |  form fields: file, document_type, parameters  |  header: X-API-Key. "
            "Example: -F 'document_type=income_certificate' -F 'parameters=name,income,validity'"
        ),
        "supported_formats": sorted(SUPPORTED_EXTENSIONS),
        "supported_document_types": SUPPORTED_DOCUMENT_TYPES,
    }


@app.get("/health", summary="Health check")
def health():
    """Public endpoint β€” no key required."""
    return {"status": "ready" if recognition_predictor else "loading"}


@app.get("/types", summary="List supported document types")
def list_types():
    """Public endpoint β€” returns all registered document types and their descriptions."""
    return {
        doc_type: {"description": cfg["description"]}
        for doc_type, cfg in DOCUMENT_TYPES.items()
    }


@app.post("/ocr", summary="Extract text and structured data from any document")
async def ocr(
    file: UploadFile = File(
        ...,
        description="Any image, PDF, Word, or PowerPoint file.",
    ),
    document_type: str = Form(
        ...,
        description=(
            "Type of document being uploaded. "
            f"Must be one of: {', '.join(SUPPORTED_DOCUMENT_TYPES)}."
        ),
    ),
    parameters: str = Form(
        ...,
        description=(
            "Comma-separated list of field names to extract from the document. "
            "You decide what to extract β€” any field name is accepted. "
            "Example: name,income,income_in_words,validity"
        ),
    ),
    _: str = Security(verify_key),
):
    """
    Upload **any** document and receive:

    - **`text`** β€” raw OCR output from the document.
    - **`data`** β€” structured JSON containing exactly the fields you requested, extracted by Sarvam-M LLM.

    **All three form fields are required:**

    | Field | Required | Description |
    |---|---|---|
    | `file` | βœ… | Document file (image / PDF / Word / PowerPoint) |
    | `document_type` | βœ… | One of: `income_certificate`, `caste_certificate`, `domicile_certificate` |
    | `parameters` | βœ… | Comma-separated fields to extract, e.g. `name,income,validity` |

    **Requires** `X-API-Key` header.

    **Example:**
    ```bash
    curl -X POST 'https://your-api/ocr' \\
      -H 'X-API-Key: your-secret-key' \\
      -F 'file=@income_cert.pdf;type=application/pdf' \\
      -F 'document_type=income_certificate' \\
      -F 'parameters=name,income,income_in_words,validity'
    ```
    """

    # ── Validate document_type ────────────────────────────────────────────────
    document_type = document_type.strip().lower()
    if document_type not in DOCUMENT_TYPES:
        raise HTTPException(
            status_code=400,
            detail=(
                f"Invalid `document_type`: '{document_type}'. "
                f"Must be one of: {', '.join(SUPPORTED_DOCUMENT_TYPES)}."
            ),
        )

    # ── Validate & parse parameters ───────────────────────────────────────────
    fields = parse_parameters(parameters)
    logger.info(f"Requested fields: {fields}")

    # ── Read & validate file ──────────────────────────────────────────────────
    data = await file.read()

    size_mb = len(data) / (1024 * 1024)
    if size_mb > MAX_FILE_SIZE_MB:
        raise HTTPException(
            status_code=413,
            detail=f"File too large ({size_mb:.1f} MB). Max: {MAX_FILE_SIZE_MB} MB.",
        )

    suffix = Path(file.filename or "").suffix.lower()
    if not suffix:
        raise HTTPException(
            status_code=400,
            detail="Filename must have an extension so the format can be detected.",
        )
    if suffix not in SUPPORTED_EXTENSIONS:
        raise HTTPException(
            status_code=415,
            detail=f"'{suffix}' is not supported. Supported: {sorted(SUPPORTED_EXTENSIONS)}",
        )

    logger.info(
        f"Processing '{file.filename}' ({size_mb:.1f} MB) | "
        f"document_type={document_type!r} | fields={fields}"
    )

    # ── OCR ───────────────────────────────────────────────────────────────────
    images = file_to_images(data, suffix)
    extracted_text = run_ocr(images)

    del images
    gc.collect()

    # ── LLM structured extraction ─────────────────────────────────────────────
    logger.info(f"Calling Sarvam-M for structured extraction (document_type={document_type!r})")
    structured_data = await extract_structured_data(document_type, fields, extracted_text)

    return JSONResponse(content={
        "text": extracted_text,
        "data": structured_data,
    })


if __name__ == "__main__":
    uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=False)