Run this model with HF Jobs

Run suryatmodulus/OCRia-1 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs and TRL to fine-tune https://huggingface.co/suryatmodulus/OCRia-1. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/suryatmodulus/OCRia-1 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/suryatmodulus/OCRia-1. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.

Quantize for lower memory use

Use HF Jobs to create a 4-bit version of https://huggingface.co/suryatmodulus/OCRia-1. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
File size: 3,908 Bytes
400c03b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# 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()