# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. # Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). # This is not open-source software: see the license for permitted uses. """HTTP server for OCRia-1 layout boxes: transcribe pages anywhere (vLLM, ...), get the boxes here. pip install "transformers==5.22.2" accelerate torchvision timm scipy pypdfium2 huggingface_hub python examples/serve_boxes.py --port 8100 # loads OCRia-1 (CUDA) and the Heron layout detector POST /ground {"image_png_b64": ..., "answer": ..., "words": [{"text", "box": [x0, y0, x1, y1]}] | null} -> {"width", "height", "items": [{"type", "label", "md", "box": [x0, y0, x1, y1], "start"}]} GET /health -> {"ok": true} `image_png_b64` must be the exact page image the answer was generated from, and `answer` the raw answer. `words` are the page's PDF text-layer words in pixels of that image (`ocria_grounding.pdf.page_words`); pass null for images. Boxes are pixels of the image. One request runs at a time on the GPU; run several servers for throughput. """ import argparse import base64 import io import json import os import sys import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from PIL import Image sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # the repository root holds ocria_grounding/ from ocria_grounding import MODEL, ground_layout, load, load_detector, load_fast_layout # noqa: E402 STATE: dict = {} LOCK = threading.Lock() class Handler(BaseHTTPRequestHandler): def _send(self, code: int, obj: dict) -> None: body = json.dumps(obj).encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def do_GET(self) -> None: # noqa: N802 self._send(200, {"ok": True}) if self.path == "/health" else self._send(404, {"error": "not found"}) def do_POST(self) -> None: # noqa: N802 if self.path != "/ground": return self._send(404, {"error": "not found"}) try: req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0)))) image = Image.open(io.BytesIO(base64.b64decode(req["image_png_b64"]))).convert("RGB") answer = req["answer"] except Exception as e: # malformed request return self._send(400, {"error": f"bad request: {e}"}) try: with LOCK: page = ground_layout(STATE["g"], image, answer, detector=STATE["det"], words=req.get("words"), method=STATE["method"], fast_backend=STATE["fast"]) except Exception as e: return self._send(500, {"error": repr(e)}) self._send(200, page) def log_message(self, fmt, *args) -> None: # quiet access log pass def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--host", default="0.0.0.0") ap.add_argument("--port", type=int, default=8100) ap.add_argument("--no-detector", action="store_true", help="attention-only boxes (less accurate)") ap.add_argument("--layout", choices=["accurate-layout", "fast-layout"], default="accurate-layout") args = ap.parse_args() STATE["g"] = load(os.environ.get("OCRIA_MODEL", MODEL)) STATE["method"] = args.layout STATE["fast"] = load_fast_layout() if args.layout == "fast-layout" else None STATE["det"] = None if args.no_detector or STATE["fast"] is not None else load_detector() print(f"serving OCRia-1 layout boxes on http://{args.host}:{args.port}", flush=True) ThreadingHTTPServer((args.host, args.port), Handler).serve_forever() if __name__ == "__main__": main()