text-ocr-server / api_server.py
mohamedahraf273's picture
add server
257992b
Raw History Blame Contribute Delete
1.95 kB
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"),
})