File size: 14,537 Bytes
dd90200
 
 
593188b
 
dd90200
 
 
 
 
 
 
 
593188b
dd90200
 
 
676a6ec
 
 
 
dd90200
8f2e63b
 
 
dd90200
 
 
593188b
dd90200
 
593188b
 
 
 
 
 
 
dd90200
 
 
 
 
 
 
 
 
 
 
 
593188b
 
 
 
 
 
 
 
 
 
 
dd90200
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593188b
dd90200
 
 
 
 
 
 
 
593188b
dd90200
 
 
 
8f2e63b
 
 
 
dd90200
 
 
 
8f2e63b
dd90200
 
 
8f2e63b
dd90200
 
 
 
8f2e63b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd90200
 
 
 
8f2e63b
 
 
dd90200
ad37019
dd90200
8f2e63b
 
dd90200
 
49c7468
337f91b
 
49c7468
337f91b
 
 
 
 
49c7468
 
 
337f91b
 
49c7468
 
 
 
 
 
 
 
337f91b
dd90200
 
 
 
 
 
 
ad37019
dd90200
 
 
8f2e63b
dd90200
 
 
 
8f2e63b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd90200
 
8f2e63b
dd90200
 
 
8f2e63b
 
 
 
 
 
 
 
 
 
337f91b
8f2e63b
337f91b
 
 
 
dd90200
 
 
 
 
8f2e63b
 
 
 
 
 
 
 
 
 
dd90200
 
 
593188b
dd90200
 
 
 
8f2e63b
676a6ec
dd90200
 
676a6ec
 
dd90200
 
 
 
 
 
 
 
676a6ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd90200
 
 
676a6ec
 
 
dd90200
 
 
 
676a6ec
dd90200
676a6ec
 
dd90200
8f2e63b
 
 
 
 
 
676a6ec
8f2e63b
 
676a6ec
8f2e63b
 
 
 
 
 
 
 
 
 
dd90200
 
 
676a6ec
 
dd90200
 
 
 
 
 
593188b
dd90200
8f2e63b
 
 
 
 
 
dd90200
 
 
 
 
 
8f2e63b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd90200
 
 
 
 
 
 
 
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
"""
DocuMint AI - FastAPI REST endpoints.

Mounted into Gradio's internal FastAPI app via APIRouter so that
ZeroGPU compatibility is preserved (demo.launch handles @spaces.GPU).
"""

import os
import json
import time
import tempfile
import logging

from fastapi import APIRouter, UploadFile, File, Form, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from PIL import Image

from extraction import (
    extract_invoice, extract_from_pdf, ExtractionResult,
    validate_with_vlm, run_dynamic_math_checks, image_to_base64,
)

# Persistence layer (gracefully no-ops when Supabase is not configured)
from db.supabase import save_document, create_run, complete_run, save_stage_result

logger = logging.getLogger(__name__)

# ---------------------------------------------------------------------------
# Router (mounted by app.py into Gradio's FastAPI app)
# ---------------------------------------------------------------------------

api_router = APIRouter()

HF_TOKEN = os.environ.get("HF_TOKEN", "")

# ---------------------------------------------------------------------------
# CORS helper β€” called by app.py after include_router
# ---------------------------------------------------------------------------

ALLOWED_ORIGINS = [
    "http://localhost:5173",           # Vite dev server
    "http://localhost:3000",
    "https://*.vercel.app",            # Vercel preview deploys
]

FRONTEND_URL = os.environ.get("FRONTEND_URL", "")
if FRONTEND_URL:
    ALLOWED_ORIGINS.append(FRONTEND_URL)


def add_cors_middleware(app):
    """Add CORS middleware to the given FastAPI/Starlette app."""
    app.add_middleware(
        CORSMiddleware,
        allow_origins=ALLOWED_ORIGINS,
        allow_origin_regex=r"https://.*\.vercel\.app",
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )


# ---------------------------------------------------------------------------
# Available models
# ---------------------------------------------------------------------------

EXTRACTION_MODELS = [
    {"id": "Qwen/Qwen2.5-VL-72B-Instruct", "name": "Qwen2.5-VL 72B", "tier": "high"},
    {"id": "Qwen/Qwen2.5-VL-7B-Instruct",  "name": "Qwen2.5-VL 7B",  "tier": "mid"},
    {"id": "Qwen/Qwen2.5-VL-3B-Instruct",   "name": "Qwen2.5-VL 3B",  "tier": "fast"},
    {"id": "ocr-only",                        "name": "OCR + Patterns", "tier": "fast"},
]

VALIDATION_MODELS = [
    {"id": "Qwen/Qwen2.5-VL-72B-Instruct", "name": "Qwen2.5-VL 72B", "tier": "high"},
    {"id": "Qwen/Qwen2.5-VL-7B-Instruct",  "name": "Qwen2.5-VL 7B",  "tier": "mid"},
]


# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------

@api_router.get("/api/v1/models")
async def list_models():
    """List available extraction and validation models."""
    return {
        "extraction": EXTRACTION_MODELS,
        "validation": VALIDATION_MODELS,
    }


@api_router.post("/api/v1/extract")
async def extract(
    file: UploadFile = File(...),
    model: str = Form("Qwen/Qwen2.5-VL-72B-Instruct"),
    force_ocr: str = Form("false"),
    persist: str = Form("true"),
    use_case: str = Form("invoice"),
    org_id: str = Form(""),
    user_id: str = Form(""),
):
    """
    Extract structured data from an uploaded invoice image or PDF.
    Returns all fields, line items, and bounding box coordinates.
    When persist=true and Supabase is configured, records the run.
    """
    start = time.time()
    use_ocr_only = force_ocr.lower() in ("true", "1", "yes") or model == "ocr-only"
    should_persist = persist.lower() in ("true", "1", "yes")

    # Determine the HF token to use β€” skip VLM when OCR-only
    token = "" if use_ocr_only else HF_TOKEN

    # ── Persistence: register document & open run ──
    doc_id = None
    run_id = None
    if should_persist:
        file_size = 0
        if hasattr(file, "size") and file.size:
            file_size = file.size
        ext = os.path.splitext(file.filename or "")[1].lower()
        file_type = "pdf" if ext == ".pdf" else "image"

        doc_id = save_document(
            filename=file.filename or "unknown",
            file_type=file_type,
            file_size=file_size,
            org_id=org_id or None,
            user_id=user_id or None,
        )
        run_id = create_run(
            document_id=doc_id,
            use_case=use_case,
            org_id=org_id or None,
            user_id=user_id or None,
        )

    # ── Stage 1: Upload (already complete at this point) ──
    upload_ms = int((time.time() - start) * 1000)
    if run_id:
        save_stage_result(
            run_id=run_id,
            stage_type="upload",
            stage_name="Document Upload",
            status="passed",
            sort_order=0,
            duration_ms=upload_ms,
        )

    try:
        contents = await file.read()
        ext = os.path.splitext(file.filename or "")[1].lower()

        # ── Stage 2: Extraction ──
        extraction_start = time.time()

        if ext == ".pdf":
            results = extract_from_pdf(contents, hf_token=token, force_ocr=use_ocr_only, use_case=use_case)
            if not results:
                if run_id:
                    _record_extraction_failure(run_id, extraction_start, "Could not extract data from PDF")
                raise HTTPException(status_code=422, detail="Could not extract data from PDF")
            result = results[0]
            # Tag page-0 bboxes
            for bb in result.bounding_boxes:
                bb.page = 0

            # Collect all page images for multi-page preview
            page_images = []
            for r in results:
                if r.page_image:
                    page_images.append(r.page_image)

            # Merge line items and their bboxes from subsequent pages.
            base_li_count = len(result.line_items)
            for page_idx, r in enumerate(results[1:], start=1):
                for bb in r.bounding_boxes:
                    if bb.field.startswith("line_item_"):
                        li_idx = int(bb.field.split("_")[-1])
                        bb.field = f"line_item_{base_li_count + li_idx}"
                        bb.page = page_idx
                        result.bounding_boxes.append(bb)
                result.line_items.extend(r.line_items)
                base_li_count += len(r.line_items)

            result._page_images = page_images
        else:
            # Save to temp file and open as image
            with tempfile.NamedTemporaryFile(suffix=ext or ".jpg", delete=False) as tmp:
                tmp.write(contents)
                tmp_path = tmp.name
            try:
                image = Image.open(tmp_path)
                result = extract_invoice(image, hf_token=token, force_ocr=use_ocr_only, use_case=use_case)
            finally:
                os.unlink(tmp_path)

        extraction_ms = int((time.time() - extraction_start) * 1000)
        total_ms = int((time.time() - start) * 1000)
        result.processing_time_ms = total_ms

        # Check for failure modes
        is_failure = result.extraction_method.startswith("failed")

        if run_id:
            extraction_status = "failed" if is_failure else "passed"
            save_stage_result(
                run_id=run_id,
                stage_type="extraction",
                stage_name="Data Extraction",
                status=extraction_status,
                sort_order=1,
                output=result.to_dict() if not is_failure else None,
                error_message=_describe_failure(result.extraction_method) if is_failure else None,
                duration_ms=extraction_ms,
            )

        if is_failure:
            if run_id:
                complete_run(
                    run_id=run_id,
                    status="completed",
                    overall_result="failed",
                    extraction_data=result.to_dict(),
                    processing_time_ms=total_ms,
                    error_message=_describe_failure(result.extraction_method),
                )
            return {
                **result.to_dict(),
                "run_id": run_id,
                "error": _describe_failure(result.extraction_method),
            }

        # ── Success β€” mark run as passed (validation is a separate call) ──
        if run_id:
            complete_run(
                run_id=run_id,
                status="completed",
                overall_result="passed",
                extraction_data=result.to_dict(),
                processing_time_ms=total_ms,
            )

        resp = result.to_dict()
        resp["run_id"] = run_id
        # Include all page images for multi-page PDF preview
        if hasattr(result, '_page_images') and result._page_images:
            resp["page_images"] = result._page_images
        return resp

    except HTTPException:
        raise
    except Exception as e:
        logger.exception("Extraction failed")
        if run_id:
            total_ms = int((time.time() - start) * 1000)
            complete_run(
                run_id=run_id,
                status="completed",
                overall_result="failed",
                extraction_data={},
                processing_time_ms=total_ms,
                error_message=str(e),
            )
        raise HTTPException(status_code=500, detail=str(e))


@api_router.post("/api/v1/validate")
async def validate(
    file: UploadFile = File(...),
    extraction: str = Form(...),
    model: str = Form("Qwen/Qwen2.5-VL-72B-Instruct"),
    run_id: str = Form(""),
    use_case: str = Form("_default"),
):
    """
    Validate extraction results using dynamic math checks and VLM semantic
    verification. Checks are generated based on the document's use_case.
    """
    start = time.time()

    try:
        data = json.loads(extraction)
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="Invalid extraction JSON")

    # ── Dynamic math/consistency checks (use_case-aware) ──
    math_checks = run_dynamic_math_checks(data)

    # ── VLM semantic validation (cross-check against source image) ──
    semantic_checks = []
    try:
        contents = await file.read()
        ext = os.path.splitext(file.filename or "")[1].lower()

        if ext == ".pdf":
            try:
                import fitz
                doc = fitz.open(stream=contents, filetype="pdf")
                page = doc[0]
                pix = page.get_pixmap(dpi=200)
                image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
                doc.close()
            except Exception:
                image = None
        else:
            with tempfile.NamedTemporaryFile(suffix=ext or ".jpg", delete=False) as tmp:
                tmp.write(contents)
                tmp_path = tmp.name
            try:
                image = Image.open(tmp_path)
            finally:
                os.unlink(tmp_path)

        if image and HF_TOKEN:
            semantic_checks = validate_with_vlm(
                image=image,
                extraction_data=data,
                hf_token=HF_TOKEN,
                model_id=model,
                use_case=use_case,
            )
    except Exception as e:
        logger.warning(f"Semantic validation failed: {e}")
        semantic_checks = [{
            "name": "VLM validation",
            "status": "skipped",
            "message": f"Could not run semantic validation: {str(e)[:100]}",
        }]

    total_ms = int((time.time() - start) * 1000)

    # Determine overall status from all check results
    all_checks = math_checks + semantic_checks
    statuses = [c["status"] for c in all_checks if c["status"] != "skipped"]
    if "fail" in statuses:
        overall = "invalid"
    elif "warn" in statuses:
        overall = "needs_review"
    elif statuses:
        overall = "valid"
    else:
        overall = "needs_review"

    # ── Persist validation stage ──
    if run_id:
        result_map = {"valid": "passed", "invalid": "failed", "needs_review": "needs_review"}
        save_stage_result(
            run_id=run_id,
            stage_type="validation",
            stage_name="Validation",
            status=result_map.get(overall, overall),
            sort_order=2,
            output={"math_checks": math_checks, "semantic_checks": semantic_checks, "overall": overall},
            duration_ms=total_ms,
        )
        complete_run(
            run_id=run_id,
            status="completed",
            overall_result=result_map.get(overall, overall),
            extraction_data=data,
            processing_time_ms=total_ms,
        )

    return {
        "overall_status": overall,
        "math_checks": math_checks,
        "semantic_checks": semantic_checks,
        "domain_checks": [],
        "cross_model_confidence": 0.0,
        "validation_model": model,
        "processing_time_ms": total_ms,
    }


@api_router.get("/api/v1/health")
async def health():
    from db.supabase import is_enabled
    return {
        "status": "ok",
        "hf_token_set": bool(HF_TOKEN),
        "persistence_enabled": is_enabled(),
    }


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _record_extraction_failure(run_id: str, extraction_start: float, message: str):
    """Record a failed extraction stage and close the run."""
    import time as _time
    extraction_ms = int((_time.time() - extraction_start) * 1000)
    save_stage_result(
        run_id=run_id,
        stage_type="extraction",
        stage_name="Data Extraction",
        status="failed",
        sort_order=1,
        error_message=message,
        duration_ms=extraction_ms,
    )
    complete_run(
        run_id=run_id,
        status="completed",
        overall_result="failed",
        extraction_data={},
        processing_time_ms=extraction_ms,
        error_message=message,
    )


def _describe_failure(method: str) -> str:
    if "no_token" in method:
        return "HF_TOKEN not set β€” AI Vision unavailable. Set the Space Secret to enable Qwen2.5-VL."
    if "vlm" in method:
        return "AI Vision models failed. Inference API may be loading or rate-limited. Try again shortly."
    return "Could not extract readable text. Image may be blurry or handwritten."