feat(ocr): add Unlimited-OCR Space client and keep registry.db out of git
Browse files- src/pino/ocr_client.py +111 -0
src/pino/ocr_client.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Client for the Unlimited-OCR Hugging Face Space.
|
| 5 |
+
|
| 6 |
+
Uploads an image or PDF file and polls for extracted text.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import logging
|
| 11 |
+
import time
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
import requests
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger("pino.ocr_client")
|
| 18 |
+
|
| 19 |
+
SPACE_API = "https://akhaliq-unlimited-ocr.hf.space/gradio_api"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def upload_file(file_path: str | Path, token: str | None = None) -> dict[str, Any]:
|
| 23 |
+
"""Upload a file to the Space and return the Gradio FileData payload."""
|
| 24 |
+
path = Path(file_path)
|
| 25 |
+
url = f"{SPACE_API}/upload"
|
| 26 |
+
headers = {}
|
| 27 |
+
if token:
|
| 28 |
+
headers["Authorization"] = f"Bearer {token}"
|
| 29 |
+
with path.open("rb") as f:
|
| 30 |
+
response = requests.post(url, files={"files": f}, headers=headers, timeout=60)
|
| 31 |
+
response.raise_for_status()
|
| 32 |
+
data = response.json()
|
| 33 |
+
# The upload endpoint returns a list of FileData objects.
|
| 34 |
+
if isinstance(data, list):
|
| 35 |
+
return data[0]
|
| 36 |
+
return data
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def call_ocr(file_data: dict[str, Any], endpoint: str = "v2", token: str | None = None) -> str:
|
| 40 |
+
"""Call the OCR endpoint and return the event_id to poll."""
|
| 41 |
+
url = f"{SPACE_API}/call/{endpoint}"
|
| 42 |
+
headers = {"Content-Type": "application/json"}
|
| 43 |
+
if token:
|
| 44 |
+
headers["Authorization"] = f"Bearer {token}"
|
| 45 |
+
payload = {"data": [file_data]}
|
| 46 |
+
response = requests.post(url, json=payload, headers=headers, timeout=60)
|
| 47 |
+
response.raise_for_status()
|
| 48 |
+
data = response.json()
|
| 49 |
+
logger.debug("OCR call response: %s", data)
|
| 50 |
+
return str(data["event_id"])
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def poll_result(event_id: str, token: str | None = None, timeout: float = 120.0) -> dict[str, Any]:
|
| 54 |
+
"""Poll the result endpoint until completion or timeout."""
|
| 55 |
+
url = f"{SPACE_API}/call/{event_id}"
|
| 56 |
+
headers = {}
|
| 57 |
+
if token:
|
| 58 |
+
headers["Authorization"] = f"Bearer {token}"
|
| 59 |
+
deadline = time.time() + timeout
|
| 60 |
+
while time.time() < deadline:
|
| 61 |
+
response = requests.get(url, headers=headers, timeout=30)
|
| 62 |
+
response.raise_for_status()
|
| 63 |
+
# The endpoint returns Server-Sent Events or JSON depending on state.
|
| 64 |
+
for line in response.text.splitlines():
|
| 65 |
+
line = line.strip()
|
| 66 |
+
if not line:
|
| 67 |
+
continue
|
| 68 |
+
if line.startswith("data:"):
|
| 69 |
+
try:
|
| 70 |
+
payload = json.loads(line[5:].strip())
|
| 71 |
+
except json.JSONDecodeError:
|
| 72 |
+
continue
|
| 73 |
+
if isinstance(payload, dict):
|
| 74 |
+
return payload
|
| 75 |
+
if isinstance(payload, list) and len(payload) > 0:
|
| 76 |
+
return {"result": payload}
|
| 77 |
+
time.sleep(2.0)
|
| 78 |
+
raise TimeoutError(f"OCR polling timed out for event_id {event_id}")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def extract_text(file_path: str | Path, token: str | None = None) -> str:
|
| 82 |
+
"""End-to-end: upload a file, run OCR, and return the extracted text."""
|
| 83 |
+
file_data = upload_file(file_path, token=token)
|
| 84 |
+
event_id = call_ocr(file_data, token=token)
|
| 85 |
+
result = poll_result(event_id, token=token)
|
| 86 |
+
# The OCR result is typically a list of strings or a single string.
|
| 87 |
+
if isinstance(result, dict) and "result" in result:
|
| 88 |
+
data = result["result"]
|
| 89 |
+
else:
|
| 90 |
+
data = result
|
| 91 |
+
if isinstance(data, list):
|
| 92 |
+
return "\n".join(str(item) for item in data)
|
| 93 |
+
return str(data)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
if __name__ == "__main__":
|
| 97 |
+
import argparse
|
| 98 |
+
|
| 99 |
+
parser = argparse.ArgumentParser(description="Extract text from an image/PDF using Unlimited-OCR")
|
| 100 |
+
parser.add_argument("file", help="Path to image or PDF file")
|
| 101 |
+
parser.add_argument("--token", default=None, help="Hugging Face token")
|
| 102 |
+
parser.add_argument("--output", default=None, help="Optional output text file")
|
| 103 |
+
args = parser.parse_args()
|
| 104 |
+
|
| 105 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 106 |
+
|
| 107 |
+
text = extract_text(args.file, token=args.token)
|
| 108 |
+
if args.output:
|
| 109 |
+
Path(args.output).write_text(text, encoding="utf-8")
|
| 110 |
+
else:
|
| 111 |
+
print(text)
|