Spaces:
Runtime error
Runtime error
Download api_server.py from mohamedahraf273/text-ocr-server: direct link, hf CLI and curl.
- Browser
- Download file 1.95 kB
-
https://huggingface.co/spaces/mohamedahraf273/text-ocr-server/resolve/main/api_server.py
- Command line
-
hf download hf://spaces/mohamedahraf273/text-ocr-server/api_server.py
-
curl -L -o api_server.py https://huggingface.co/spaces/mohamedahraf273/text-ocr-server/resolve/main/api_server.py
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") | |
| def health(): | |
| return { | |
| "status": "ok", | |
| "service": "arabic-prescription-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"), | |
| }) | |