Run this model with HF Jobs

Run OpenTensorLab/OCRia-1-W4A16-LLM-Compressor 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-LLM-Compressor. 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-LLM-Compressor 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-LLM-Compressor. 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: 11,204 Bytes
d8db4d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# 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.
"""Layout elements of a raw ocria answer: the character spans that each get one box, with a type.

The answer is ocria's no-layout transcription (markdown, HTML tables, `<page_header>`/`<page_footer>`/`<page_number>`
furniture tags, `![label: description]` image references, ```mermaid diagrams). Each element becomes one
`<!-- bbox: TYPE x0 y0 x1 y1 -->` marker, so the types are the box-mode vocabulary the layout scorer already reads
(`layout_score._BOX_TYPE_TO_REGION_LABEL`): text, heading, list, table, image, code, header, footer.

Granularity (one element per ...): paragraph (blank-line separated), heading line, list item (with its indented
continuation lines), whole table, image reference, fenced block, display-math block, furniture band. A standalone
`<page_number>` gets type "page_number" and is resolved to header/footer from its box (`resolve_page_numbers`).
Offsets index the raw answer, fence included, so they line up with the teacher-forced tokens.
"""

from __future__ import annotations

import re
from collections.abc import Callable
from dataclasses import dataclass

from .tune import FLAGS

_OPEN_FENCE = re.compile(r"\A\s*```(?:markdown|md)?[ \t]*\n")
_FURN_OPEN = re.compile(r"<(page_header|page_footer|watermark)>")
_PAGE_NUMBER = re.compile(r"^\s*<page_number>.*?</page_number>\s*$")
_HEADING = re.compile(r"^\s{0,3}#{1,6}\s")
_IMAGE = re.compile(r"^\s*!\[")
_FENCE = re.compile(r"^\s*```")
_MATH = re.compile(r"^\s*\$\$")
_PIPE_ROW = re.compile(r"^\s*\|")
_TABLE_OPEN = re.compile(r"<(table|rcl)\b", re.I)  # HTML table, or ocria-1.5's RCL grid
_LIST_ITEM = re.compile(
    r"^(\s*)(?:[*\-+•▪◦»]\s|\d{1,3}[.)]\s|\(?[a-zA-Z][.)]\s|\[[ xX_]*\]\s)"
)
_QUOTE_PREFIX = re.compile(r"^(?: {0,3}>[ \t]?)+")
_BOLD_LINE = re.compile(r"^\s*\*\*[^*]+\*\*:?\s*$")
_TYPES_FOR_FURN = {
    "page_header": "header",
    "page_footer": "footer",
    "watermark": "text",
}


@dataclass
class Block:
    type: str
    start: int
    end: int


def _lines(text: str, lo: int, hi: int) -> list[tuple[int, int, str]]:
    """(start, end, line) for each line of text[lo:hi]; end excludes the newline."""
    out, pos = [], lo
    while pos < hi:
        nl = text.find("\n", pos, hi)
        end = hi if nl < 0 else nl
        out.append((pos, end, text[pos:end]))
        pos = end + 1
    return out


def body_span(text: str) -> tuple[int, int]:
    """The transcription inside the ```markdown fence (the whole answer when there is none)."""
    lo, hi = 0, len(text)
    m = _OPEN_FENCE.match(text)
    if m:
        lo = m.end()
        close = text.rfind("```")
        if close >= lo:
            hi = close
    return lo, hi


def _starts_construct(line: str) -> bool:
    return bool(
        _HEADING.match(line)
        or _IMAGE.match(line)
        or _FENCE.match(line)
        or _MATH.match(line)
        or _PIPE_ROW.match(line)
        or _TABLE_OPEN.search(line)
        or _FURN_OPEN.search(line)
        or _PAGE_NUMBER.match(line)
        or _LIST_ITEM.match(line)
    )


def split_blocks(text: str) -> list[Block]:
    """Layout elements of one page's raw answer, in reading order."""
    lo, hi = body_span(text)
    lines = _lines(text, lo, hi)
    blocks: list[Block] = []
    i = 0

    def until(j: int, pred: Callable[[str], bool]) -> int:
        """Index of the first line from j on for which pred holds (the last line when none does)."""
        while j < len(lines) and not pred(lines[j][2]):
            j += 1
        return min(j, len(lines) - 1)

    while i < len(lines):
        s, e, line = lines[i]
        if not line.strip():
            i += 1
            continue
        m = _FURN_OPEN.search(line)
        if m:
            tag = m.group(1)
            close = f"</{tag}>"
            j = i if close in line else until(i + 1, lambda x: close in x)
            blocks.append(Block(_TYPES_FOR_FURN[tag], s, lines[j][1]))
            i = j + 1
            continue
        if _PAGE_NUMBER.match(line):
            blocks.append(Block("page_number", s, e))
            i += 1
            continue
        tm = _TABLE_OPEN.search(line)
        if tm:
            close = "</table>" if tm.group(1).lower() == "table" else "</rcl>"
            j = (
                i
                if close in line.lower()
                else until(i + 1, lambda x: close in x.lower())
            )
            if "split_layout_tables" in FLAGS and _is_layout_table(
                text[s : lines[j][1]]
            ):
                blocks.extend(_layout_table_blocks(text, s, lines[j][1]))
            else:
                blocks.append(Block("table", s, lines[j][1]))
            i = j + 1
            continue
        if _FENCE.match(line):
            j = until(i + 1, lambda x: _FENCE.match(x) is not None)
            kind = "image" if "mermaid" in line.lower() else "code"
            blocks.append(Block(kind, s, lines[j][1]))
            i = j + 1
            continue
        if _MATH.match(line):
            rest = line.strip()[2:]
            j = i if "$$" in rest else until(i + 1, lambda x: "$$" in x)
            blocks.append(Block("text", s, lines[j][1]))
            i = j + 1
            continue
        if _HEADING.match(line):
            blocks.append(Block("heading", s, e))
            i += 1
            continue
        if _IMAGE.match(line):
            blocks.append(Block("image", s, e))
            i += 1
            continue
        if _PIPE_ROW.match(line):
            j = i
            while j + 1 < len(lines) and _PIPE_ROW.match(lines[j + 1][2]):
                j += 1
            blocks.append(Block("table", s, lines[j][1]))
            i = j + 1
            continue
        lm = _LIST_ITEM.match(line)
        if lm:
            indent = len(lm.group(1))
            j = i
            while j + 1 < len(lines):
                nxt = lines[j + 1][2]
                if not nxt.strip() or _starts_construct(nxt):
                    break
                if (
                    len(nxt) - len(nxt.lstrip()) <= indent
                ):  # a continuation line is indented under the marker
                    break
                j += 1
            blocks.append(Block("list", s, lines[j][1]))
            i = j + 1
            continue
        if (
            "split_lines" in FLAGS
        ):  # each line its own element; a bold-only line is a heading
            blocks.append(Block("heading" if _BOLD_LINE.match(line) else "text", s, e))
            i += 1
            continue
        j = i  # paragraph: until a blank line or a line that opens another element
        while (
            j + 1 < len(lines)
            and lines[j + 1][2].strip()
            and not _starts_construct(lines[j + 1][2])
        ):
            j += 1
        blocks.append(Block("text", s, lines[j][1]))
        i = j + 1
    blocks = [piece for block in blocks for piece in _split_quoted_list(text, block)]
    if "inline_images" in FLAGS:
        blocks = [p for b in blocks for p in _split_inline_images(text, b)]
    return blocks


def _split_quoted_list(text: str, block: Block) -> list[Block]:
    """Expose quoted list items while retaining raw offsets and continuation lines.

    Quote prefixes are ignored only for recognizing markers. Keeping the raw
    spans preserves the word sequence used by cached sparse attention maps.
    """
    if block.type != "text" or ">" not in text[block.start : block.end]:
        return [block]
    result: list[Block] = []
    start, kind = block.start, block.type
    for line_start, _, line in _lines(text, block.start, block.end):
        prefix = _QUOTE_PREFIX.match(line)
        if prefix is None or not _LIST_ITEM.match(line[prefix.end() :]):
            continue
        if line_start > start and text[start:line_start].strip(" >\t\r\n"):
            result.append(Block(kind, start, line_start))
        start, kind = line_start, "list"
    result.append(Block(kind, start, block.end))
    return result


_INLINE_IMAGE = re.compile(r"!\[[^\]\n]*\](?:\([^)\s]*\))?")


def _split_inline_images(text: str, b: Block) -> list[Block]:
    """An image reference inside a text-like element (an icon after a heading, a logo next to a footer's page number)
    is a picture of its own on the page: the element is cut into the text before it, the image, and the text after."""
    if b.type in ("image", "table", "code") or "![" not in text[b.start : b.end]:
        return [b]
    out, pos = [], b.start
    for m in _INLINE_IMAGE.finditer(text, b.start, b.end):
        if _TAGS.sub("", text[pos : m.start()]).strip(" \t\n|*#-"):
            out.append(Block(b.type, pos, m.start()))
        out.append(Block("image", m.start(), m.end()))
        pos = m.end()
    if _TAGS.sub("", text[pos : b.end]).strip(" \t\n|*#-"):
        out.append(Block(b.type, pos, b.end))
    return out or [b]


def resolve_page_numbers(blocks: list[Block], boxes: list, page_height: float) -> None:
    """A standalone page number is furniture: header when its box sits in the top half, else footer."""
    for b, box in zip(blocks, boxes):
        if b.type == "page_number":
            b.type = (
                "header"
                if box is not None and (box[1] + box[3]) / 2 < page_height / 2
                else "footer"
            )


_CELL = re.compile(r"<t[dh][^>]*>(.*?)</t[dh]>", re.S | re.I)
_TAGS = re.compile(r"<[^>]+>")


def _is_layout_table(html: str) -> bool:
    """A table used to lay out a page (people grids, card layouts), not data: it holds image references, or its
    cells hold prose (mean >= 8 words)."""
    if "![" in html:
        return True
    words = [len(_TAGS.sub(" ", c).split()) for c in _CELL.findall(html) if c.strip()]
    return bool(words) and sum(words) / len(words) >= 8


def _layout_table_blocks(text: str, lo: int, hi: int) -> list[Block]:
    """One element per segment of each cell: segments split at blank lines (two or more <br>, or any <br> with
    split_br), an image reference is its own element."""
    sep = re.compile(
        r"(?:<br\s*/?>\s*)+" if "split_br" in FLAGS else r"(?:<br\s*/?>\s*){2,}", re.I
    )
    out: list[Block] = []
    for m in _CELL.finditer(text, lo, hi):
        a, b = m.start(1), m.end(1)
        pos = a
        for cut in [*sep.finditer(text, a, b), None]:
            end = cut.start() if cut else b
            seg = text[pos:end]
            if _TAGS.sub("", seg).strip():
                k = pos + (len(seg) - len(seg.lstrip()))
                origin = k
                for im in re.finditer(r"!\[[^\]]*\]", text[origin:end]):
                    start, stop = origin + im.start(), origin + im.end()
                    if text[k:start].strip():
                        out.append(Block("text", k, start))
                    out.append(Block("image", start, stop))
                    k = stop
                if _TAGS.sub("", text[k:end]).strip():
                    out.append(Block("text", k, end))
            pos = cut.end() if cut else b
    return out