Files
breakpilot-core/paddleocr-service/main.py
Benjamin Admin 86b11c7e5f
Some checks failed
Deploy to Coolify / deploy (push) Has been cancelled
fix: catch all exceptions in PaddleOCR version fallback
PaddleOCR 2.8.1 throws a generic Exception (not ValueError) when
ocr_version='PP-OCRv5' is used. Broadened except clause to catch
any error and fall back to lang='latin' for older versions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:12:32 +01:00

107 lines
2.8 KiB
Python

"""PaddleOCR Remote Service — PP-OCRv5 Latin auf x86_64."""
import io
import logging
import os
import numpy as np
from fastapi import FastAPI, File, Header, HTTPException, UploadFile
from PIL import Image
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI(title="PaddleOCR Service")
_engine = None
_ready = False
API_KEY = os.environ.get("PADDLEOCR_API_KEY", "")
def get_engine():
global _engine
if _engine is None:
from paddleocr import PaddleOCR
logger.info("Loading PaddleOCR model...")
# PaddleOCR >= 3.x: lang="en" + PP-OCRv5; older: lang="latin"
try:
_engine = PaddleOCR(
lang="en",
ocr_version="PP-OCRv5",
use_angle_cls=True,
show_log=False,
)
logger.info("Using PP-OCRv5 (en)")
except Exception:
_engine = PaddleOCR(
lang="latin",
use_angle_cls=True,
show_log=False,
)
logger.info("Using PP-OCRv4 fallback (latin)")
logger.info("PaddleOCR model loaded successfully")
return _engine
@app.on_event("startup")
def startup_load_model():
"""Pre-load model at startup so health check passes."""
global _ready
try:
get_engine()
_ready = True
logger.info("PaddleOCR ready to serve requests")
except Exception as e:
logger.error(f"Failed to load PaddleOCR model: {e}")
@app.get("/health")
def health():
if _ready:
return {"status": "ok", "model": "PP-OCRv5-latin"}
return {"status": "loading"}
@app.post("/ocr")
async def ocr(
file: UploadFile = File(...),
x_api_key: str = Header(default=""),
):
if API_KEY and x_api_key != API_KEY:
raise HTTPException(status_code=401, detail="Invalid API key")
if not _ready:
raise HTTPException(status_code=503, detail="Model still loading")
img_bytes = await file.read()
img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
img_np = np.array(img)
engine = get_engine()
result = engine.ocr(img_np)
words = []
for line in result[0] or []:
box, (text, conf) = line[0], line[1]
x_min = min(p[0] for p in box)
y_min = min(p[1] for p in box)
x_max = max(p[0] for p in box)
y_max = max(p[1] for p in box)
words.append(
{
"text": text.strip(),
"left": int(x_min),
"top": int(y_min),
"width": int(x_max - x_min),
"height": int(y_max - y_min),
"conf": round(conf * 100, 1),
}
)
return {
"words": words,
"image_width": img_np.shape[1],
"image_height": img_np.shape[0],
}