File size: 1,953 Bytes
257992b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import base64
import json

import cv2
import numpy as np
from fastapi import FastAPI, File, HTTPException, UploadFile
from fastapi.responses import JSONResponse

from app import run_ocr

api = FastAPI(title="Arabic Prescription OCR API")


@api.get("/health")
def health():
    return {
        "status": "ok",
        "service": "arabic-prescription-ocr",
    }


@api.post("/ocr")
async def ocr(file: UploadFile = File(...)):
    if not file.content_type or not file.content_type.startswith("image/"):
        raise HTTPException(
            status_code=415,
            detail="Upload an image.",
        )

    raw = await file.read()

    image = cv2.imdecode(
        np.frombuffer(raw, dtype=np.uint8),
        cv2.IMREAD_COLOR,
    )

    if image is None:
        raise HTTPException(
            status_code=400,
            detail="Invalid image.",
        )

    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    try:
        # New PaddleOCR-VL interface
        output_image, summary, result_json, markdown_text = run_ocr(
            image_rgb
        )

    except Exception as exc:
        raise HTTPException(
            status_code=500,
            detail=f"OCR failed: {type(exc).__name__}: {exc}",
        ) from exc

    # Encode the returned preview as PNG Base64
    output_bgr = cv2.cvtColor(
        output_image,
        cv2.COLOR_RGB2BGR,
    )

    success, encoded = cv2.imencode(".png", output_bgr)

    if not success:
        raise HTTPException(
            status_code=500,
            detail="Failed to encode output image.",
        )

    try:
        results = json.loads(result_json)
    except (json.JSONDecodeError, TypeError):
        results = result_json

    return JSONResponse({
        "summary": summary,
        "results": results,
        "recognized_text": markdown_text,
        "annotated_image_png_base64": base64.b64encode(
            encoded.tobytes()
        ).decode("ascii"),
    })