| import os |
| import requests |
|
|
|
|
| HF_MODEL = os.getenv("HF_OCR_MODEL", "microsoft/trocr-base-printed") |
|
|
|
|
| def run_hf_ocr(image_bytes: bytes) -> str: |
| token = os.getenv("HUGGINGFACE_API_TOKEN") |
| if not token: |
| raise RuntimeError("Missing HUGGINGFACE_API_TOKEN") |
|
|
| |
| url = f"https://api-inference.huggingface.co/models/{HF_MODEL}" |
| headers = {"Authorization": f"Bearer {token}"} |
| response = requests.post(url, headers=headers, data=image_bytes, timeout=60) |
| if response.status_code >= 400: |
| raise RuntimeError(f"HF API error: {response.status_code} {response.text}") |
|
|
| try: |
| data = response.json() |
| except Exception as exc: |
| raise RuntimeError(f"Invalid HF response: {exc}") |
|
|
| |
| if isinstance(data, list) and data and isinstance(data[0], dict): |
| text = data[0].get("generated_text") |
| if isinstance(text, str): |
| return text |
|
|
| |
| return str(data) |
|
|
|
|
|
|