Run this model with HF Jobs

Run OpenTensorLab/OCRia-1-W4A16-AutoRound 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/OpenTensorLab/OCRia-1-W4A16-AutoRound. 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/OpenTensorLab/OCRia-1-W4A16-AutoRound 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/OpenTensorLab/OCRia-1-W4A16-AutoRound. 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.
File size: 6,211 Bytes
90d9faa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# 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.
"""Exercise public dispatch, serialization, CLI, and HTTP with CPU attention fixtures."""

import base64
import http.client
import importlib.util
import io
import json
from pathlib import Path
import runpy
import sys
import threading

import numpy as np
from PIL import Image
import pytest

import ocria_grounding
from ocria_grounding import ground_layout, load_fast_layout, to_layout_items_page
from parse_rl_utils.ocria_attention_grounding.api import FastLayout

ROOT = Path(__file__).resolve().parents[1]
ANSWER = "# Heading\n\nOne two three four five six seven eight."


class Capture:
    def unit_maps(
        self, image: Image.Image, answer: str, units: list[tuple[int, int]]
    ) -> tuple[np.ndarray, tuple[int, int], np.ndarray]:
        maps = np.zeros((len(units), 12, 16), dtype=np.float32)
        for i in range(len(units)):
            maps[i, 3 + i // 5, 2 + i % 5] = 1
        return maps, (12, 16), np.ones(len(units), dtype=bool)


@pytest.fixture(scope="module")
def backend() -> FastLayout:
    return load_fast_layout()


def test_fast_dispatch_rejects_detector_and_unknown_method(backend: FastLayout) -> None:
    image = Image.new("RGB", (320, 240), "white")
    with pytest.raises(ValueError, match="attention only"):
        ground_layout(
            Capture(),
            image,
            ANSWER,
            method="fast-layout",
            fast_backend=backend,
            detector=object(),
        )
    with pytest.raises(ValueError, match="Unknown layout method"):
        ground_layout(None, image, ANSWER, method="typo")


def test_serializer_preserves_split_segments_and_text_offsets() -> None:
    segments = [
        {
            "x": 10.0,
            "y": 20.0,
            "w": 30.0,
            "h": 40.0,
            "label": "text",
            "start_index": 0,
            "end_index": 4,
        },
        {
            "x": 60.0,
            "y": 5.0,
            "w": 20.0,
            "h": 15.0,
            "label": "text",
            "start_index": 5,
            "end_index": 9,
        },
    ]
    page = {
        "width": 100,
        "height": 100,
        "items": [
            {
                "type": "Text",
                "label": "text",
                "md": "alpha beta",
                "box": [10.0, 5.0, 80.0, 60.0],
                "layout_segments": segments,
            }
        ],
    }
    result = to_layout_items_page(page, scale=0.5)["items"][0]
    assert result["layout_segments"] == [
        {**s, **{k: s[k] * 0.5 for k in ("x", "y", "w", "h")}} for s in segments
    ]
    assert page["items"][0]["layout_segments"] == segments


def test_cli_fast_mode_skips_detector_and_writes_boxes(tmp_path, monkeypatch, backend):
    source = tmp_path / "page.png"
    Image.new("RGB", (320, 240), "white").save(source)
    monkeypatch.setattr(ocria_grounding, "load", lambda *args: Capture())
    monkeypatch.setattr(ocria_grounding, "transcribe", lambda *args: ANSWER)
    monkeypatch.setattr(ocria_grounding, "load_fast_layout", lambda: backend)

    def fail_detector() -> None:
        raise AssertionError("CLI loaded detector in fast mode")

    monkeypatch.setattr(ocria_grounding, "load_detector", fail_detector)
    monkeypatch.setattr(
        sys, "argv", ["boxes.py", str(source), "--layout", "fast-layout"]
    )
    runpy.run_path(str(ROOT / "examples/boxes.py"), run_name="__main__")
    result = json.loads(source.with_suffix(".boxes.json").read_text())
    assert result["items"] and result["attention_source"] == "teacher-forced"
    assert Image.open(source.with_suffix(".boxes.png")).size == (320, 240)


def test_http_fast_mode_serializes_real_backend_result_and_rejects_bad_input(
    backend: FastLayout,
) -> None:
    spec = importlib.util.spec_from_file_location(
        "serve_boxes", ROOT / "examples/serve_boxes.py"
    )
    server_module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(server_module)
    server_module.STATE.update(
        g=Capture(), det=None, method="fast-layout", fast=backend
    )
    server = server_module.ThreadingHTTPServer(("127.0.0.1", 0), server_module.Handler)
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    image = io.BytesIO()
    Image.new("RGB", (320, 240), "white").save(image, format="PNG")
    request = {
        "image_png_b64": base64.b64encode(image.getvalue()).decode(),
        "answer": ANSWER,
    }
    try:
        connection = http.client.HTTPConnection(
            "127.0.0.1", server.server_port, timeout=10
        )
        connection.request(
            "POST", "/ground", json.dumps(request), {"Content-Type": "application/json"}
        )
        response = connection.getresponse()
        body = json.loads(response.read())
        assert response.status == 200 and body["items"]
        assert body["attention_source"] == "teacher-forced"
        connection.request(
            "POST", "/ground", "{}", {"Content-Type": "application/json"}
        )
        response = connection.getresponse()
        response.read()
        assert response.status == 400
        connection.close()
    finally:
        server.shutdown()
        server.server_close()
        thread.join(timeout=5)


def test_live_fast_dispatch_never_constructs_pixel_geometry(
    backend: FastLayout, monkeypatch: pytest.MonkeyPatch
) -> None:
    import ocria_grounding.ground as original_ground
    import ocria_grounding.layout as original_layout

    def reject_pixels(*args: object, **kwargs: object) -> None:
        raise AssertionError("Fast dispatch constructed raster geometry")

    monkeypatch.setattr(original_ground, "Page", reject_pixels)
    monkeypatch.setattr(original_layout, "Page", reject_pixels)
    result = ground_layout(
        Capture(),
        Image.new("RGB", (320, 240)),
        ANSWER,
        method="fast-layout",
        fast_backend=backend,
    )
    assert result["items"] and result["attention_source"] == "teacher-forced"