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: 35,452 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
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
# 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.
"""Sub-cell word boundaries from attention, composed with conservative block grouping."""

from bisect import bisect_left, bisect_right
from typing import Protocol
import re

from .predict import predict

import numpy as np

from .headers import split_navigation_headers
from .columns import split_column_blocks
from .native import get_native
from .blocks import split_blocks
from .bullet_tables import split_bullet_tables
from .context import extended_features
from .io import SparseWordMaps, dense_maps, element_text, units_for
from .orientation import (
    coherent_rotated_words,
    rotate_attention_clockwise,
    vertical_text_spans,
)
from .rectangles import RectangleConfig, rectangle_boxes
from .pictures import PicturePredictor, refine_pictures
from .rust import get_rust
from .words import norm
from .regions import (
    HeadingGlyphRegionBlend,
    contextual_region_features,
    heading_glyph_features,
    region_features,
)
from .tables import TablePredictor, refine_tables, refine_table_word_boxes
from .repeated import recover_repeated_paragraphs
from .peaks import PeakPredictor, select_word_peaks

_INLINE_IMAGE_REFERENCE = re.compile(r"!\[[^\]\n]+\]")

_NUMERIC_WORD = re.compile(r"[\s*$€£+\d.,%−-]+")

BASE_CONFIG = RectangleConfig(
    keep_tables=True,
    fit_lines=True,
    font_height=2.2,
    anchor_fraction=0.25,
    connected_words=True,
    image_quantile=0.15,
    y_offset=0.125,
    guard_expansion=1.5,
    heading_x_scale=1.05,
    text_x_scale=1.025,
    furniture_y_inset=0.125,
    furniture_x_scale=1.1,
    fit_blend_x=0.75,
    fit_blend_y=0.75,
    image_text_suppression=16,
)
_TEXT_TYPES = {"text", "list", "heading", "header", "footer"}


class Predictor(Protocol):
    def predict(self, features: np.ndarray) -> np.ndarray: ...


def attention_features(
    answer: str,
    units: list[tuple[int, int]],
    sparse: dict,
    grid: tuple[int, int],
    anchors: dict[int, int] | None = None,
) -> tuple[np.ndarray, list[int], np.ndarray]:
    """Return features, retained unit indices, and peak centers in grid-cell units.

    The 5x5 patch is normalized by the strongest cached cell. Optional anchors
    select a sparse-array position without modifying weights. Relative moments are clipped
    to five cells so a weak distant hotspot cannot dominate a word's features.
    Preserve this feature order when fitting or loading boundary regressors.
    """
    rust = get_rust()
    if rust is not None:
        return rust.local_features(answer, units, sparse, grid, anchors)
    gh, gw = grid
    features, valid, peaks = [], [], []
    for u, (start, end) in enumerate(units):
        indices = np.asarray(sparse["idx"][u])
        values = np.asarray(sparse["val"][u])
        if not len(indices) or not sparse["has"][u]:
            continue
        maximum = values.max()
        if not maximum:
            continue
        order = np.argsort(-values)
        if anchors and u in anchors:
            chosen = anchors[u]
            order = np.r_[chosen, order[order != chosen]]
        indices, values = indices[order], values[order]
        yy, xx = indices // gw, indices % gw
        dx, dy = (xx - xx[0]).astype(float), (yy - yy[0]).astype(float)
        patch = np.zeros((5, 5))
        local = (abs(dx) <= 2) & (abs(dy) <= 2)
        patch[(dy[local] + 2).astype(int), (dx[local] + 2).astype(int)] = (
            values[local] / maximum
        )
        total = values.sum()
        mass = values / total
        clipped_x, clipped_y = dx.clip(-5, 5), dy.clip(-5, 5)
        features.append(
            [
                len(norm(answer[start:end])),
                gh,
                gw,
                float(maximum),
                float(total),
                float((mass * clipped_x).sum()),
                float((mass * clipped_y).sum()),
                float((mass * clipped_x**2).sum()),
                float((mass * clipped_y**2).sum()),
                *patch.ravel().tolist(),
            ]
        )
        valid.append(u)
        peaks.append((xx[0] + 0.5, yy[0] + 0.5))
    return (
        np.asarray(features, dtype=float).reshape(-1, 34),
        valid,
        np.asarray(peaks, dtype=float).reshape(-1, 2),
    )


def contextual_features(
    answer: str,
    units: list[tuple[int, int]],
    per_block: list[list[int]],
    features: np.ndarray,
    valid: list[int],
    peaks: np.ndarray,
) -> np.ndarray:
    """Append transcript-neighbor and local line-spacing evidence in grid cells.

    Only words in the same emitted block contribute. Missing attention keeps its
    original unit index, so a missing word cannot shift the neighborhood. A local
    25-word window bounds work independently of document length.
    """
    positions = np.full((len(units), 2), np.nan)
    positions[valid] = peaks
    # Python scalar access avoids repeated NumPy indexing in fixed-size windows.
    coordinates = positions.tolist()
    present = np.isfinite(positions[:, 0]).tolist()
    lengths = [len(norm(answer[start:end])) for start, end in units]
    owners = {u: k for k, indices in enumerate(per_block) for u in indices}
    native = get_native()
    if native is not None:
        return np.column_stack(
            [features, native.neighborhood(positions, lengths, owners, valid)]
        )
    context = []
    for u in valid:
        px, py = coordinates[u]
        row = []
        for offset in (-2, -1, 1, 2):
            neighbor = u + offset
            if (
                0 <= neighbor < len(units)
                and owners.get(neighbor) == owners.get(u)
                and present[neighbor]
            ):
                nx, ny = coordinates[neighbor]
                row.extend(
                    [
                        float(nx - px),
                        float(ny - py),
                        lengths[neighbor],
                        1.0,
                    ]
                )
            else:
                row.extend([0.0, 0.0, 0.0, 0.0])
        nearby = [
            j
            for j in range(max(0, u - 12), min(len(units), u + 13))
            if owners.get(j) == owners.get(u)
            and present[j]
            and abs(coordinates[j][1] - py) <= 1
        ]
        advances = []
        for first, second in zip(nearby, nearby[1:]):
            delta = coordinates[second][0] - coordinates[first][0]
            chars = 0.75 * lengths[first] + 1 + 0.25 * lengths[second]
            if 0.1 <= delta / max(chars, 1) <= 1.5:
                advances.append(delta / chars)
        row.extend(
            [
                len(nearby),
                float(np.median(advances)) if advances else 0.0,
                float(np.median(positions[nearby, 1])) - py if nearby else 0.0,
            ]
        )
        context.append(row)
    context_array = np.asarray(context).reshape(-1, 19)
    # Batch neighbor-offset clipping instead of dispatching eight scalar ufuncs.
    context_array[:, 0:16:4] = np.clip(context_array[:, 0:16:4], -20, 20)
    context_array[:, 1:16:4] = np.clip(context_array[:, 1:16:4], -10, 10)
    return np.column_stack([features, context_array])


def recover_line_tails(
    accepted: set[int], candidates: set[int], peaks: np.ndarray
) -> list[int]:
    """Recover omitted word runs bracketed by a line continuation and a wrap.

    Indices follow transcript order; coordinates are attention-grid cells.
    Candidates already satisfy the paragraph's vertical guard. A misplaced
    word may interrupt the line. A quantized row tie requires earlier downward
    progression and a short horizontal gap relative to local word spacing.
    """
    accepted = set(accepted)
    runs: list[list[int]] = []
    for j in sorted(candidates - accepted):
        if not runs or j != runs[-1][-1] + 1:
            runs.append([j])
        else:
            runs[-1].append(j)
    for run in runs:
        if len(run) < 3:
            continue
        first, last = run[0], run[-1]
        before = next((j for j in (first - 1, first - 2) if j in accepted), None)
        after = last + 1
        if before is None or after not in accepted:
            continue
        positions = peaks[run]
        low, high = positions.min(0), positions.max(0)
        prior, following = peaks[before], peaks[after]
        if high[1] - low[1] > 1 or np.mean(np.diff(positions[:, 0]) >= -1) < 0.8:
            continue
        if (
            prior[0] < low[0]
            and following[0] < low[0]
            and low[1] - 1 <= prior[1] <= high[1] + 1
            and (
                high[1] < following[1] <= high[1] + 3
                or (
                    following[1] == high[1]
                    and prior[1] < high[1]
                    and low[0] - prior[0]
                    <= max(
                        3, 3 * float(np.median(np.maximum(0, np.diff(positions[:, 0]))))
                    )
                )
            )
        ):
            accepted.update(run)
    return sorted(accepted)


def recover_short_line_tails(
    selected: list[int], candidates: set[int], peaks: np.ndarray, boxes: np.ndarray
) -> list[int]:
    """Recover one or two omitted words at a supported line end.

    All coordinates use attention-grid cells. Neighboring word boxes must be
    separated by at most two median word heights, with a left/down wrap after
    the omitted run. This bounds gaps without assuming a page-wide font size.
    """
    accepted = set(selected)
    runs: list[list[int]] = []
    for j in sorted(candidates - accepted):
        if not runs or j != runs[-1][-1] + 1:
            runs.append([j])
        else:
            runs[-1].append(j)
    for run in runs:
        before, after = run[0] - 1, run[-1] + 1
        if len(run) > 2 or before not in accepted or after not in accepted:
            continue
        sequence = [before, *run]
        positions = peaks[sequence]
        height = float(np.median(boxes[sequence, 3] - boxes[sequence, 1]))
        gaps = boxes[sequence[1:], 0] - boxes[sequence[:-1], 2]
        if (
            np.ptp(positions[:, 1]) <= 1
            and np.all(np.diff(positions[:, 0]) > 0)
            and np.all((gaps >= -height) & (gaps <= 2 * height))
            and peaks[after, 0] < peaks[before, 0]
            and 0 < peaks[after, 1] - positions[:, 1].max() <= 3
        ):
            accepted.update(run)
    return sorted(accepted)


def recover_paragraph_opening(
    selected: list[int],
    element_units: list[tuple[int, tuple[int, int]]],
    lookup: dict[int, int],
    peaks: np.ndarray,
    boxes: np.ndarray,
) -> list[int]:
    """Recover one or two opening words continuous with an accepted first line.

    Peaks and word boxes use grid cells. Require increasing horizontal positions
    on one attention row and gaps of at most two local word heights. A substantial
    accepted body anchors the paragraph before relaxing its coarse boundary.
    """
    if len(selected) < 8:
        return selected
    ordered = [lookup[u] for u, _ in element_units if u in lookup]
    if not ordered:
        return selected
    accepted = set(selected)
    prefix = []
    for index in ordered:
        if index in accepted:
            break
        prefix.append(index)
    if not 1 <= len(prefix) <= 2 or len(prefix) == len(ordered):
        return selected
    sequence = prefix + [ordered[len(prefix)]]
    positions = peaks[sequence]
    height = float(np.median(boxes[sequence, 3] - boxes[sequence, 1]))
    gaps = boxes[sequence[1:], 0] - boxes[sequence[:-1], 2]
    if (
        np.ptp(positions[:, 1]) <= 1
        and np.all(np.diff(positions[:, 0]) > 0)
        and np.all((gaps >= -height) & (gaps <= 2 * height))
    ):
        return sorted(accepted | set(prefix))
    return selected


def align_word_boxes_to_neighbor_row(
    selected: list[int],
    element_units: list[tuple[int, tuple[int, int]]],
    lookup: dict[int, int],
    peaks: np.ndarray,
    grid_boxes: np.ndarray,
    word_boxes: np.ndarray,
    cell_height: float,
) -> None:
    """Repair displaced word boxes when consecutive peaks agree on one line.

    Update grid-cell and capture-pixel boxes together, preserving word heights.
    Both neighbors must agree vertically and all three peaks must advance left
    to right on one row; a line wrap or isolated peak cannot trigger correction.
    """
    ordered = [lookup[u] for u, _ in element_units if u in lookup]
    accepted = set(selected)
    for k in range(1, len(ordered) - 1):
        left, mid, right = ordered[k - 1 : k + 2]
        if not {left, mid, right} <= accepted:
            continue
        ax, ay = peaks[left]
        bx, by = peaks[mid]
        cx, cy = peaks[right]
        if max(ay, by, cy) - min(ay, by, cy) > 1 or not ax < bx < cx:
            continue
        ltop, lbottom = grid_boxes[left, 1], grid_boxes[left, 3]
        rtop, rbottom = grid_boxes[right, 1], grid_boxes[right, 3]
        height = float((lbottom - ltop + rbottom - rtop) / 2)
        lcenter, rcenter = (ltop + lbottom) / 2, (rtop + rbottom) / 2
        target = float((lcenter + rcenter) / 2)
        center = float((grid_boxes[mid, 1] + grid_boxes[mid, 3]) / 2)
        if abs(lcenter - rcenter) <= height and abs(center - target) > max(
            2, 2 * height
        ):
            delta = target - center
            grid_boxes[mid, [1, 3]] += delta
            word_boxes[mid, [1, 3]] += delta * cell_height


def align_word_boxes_to_reading_order(
    selected: list[int],
    element_units: list[tuple[int, tuple[int, int]]],
    lookup: dict[int, int],
    peaks: np.ndarray,
    grid_boxes: np.ndarray,
    word_boxes: np.ndarray,
    cell_width: float,
) -> None:
    """Place an isolated reversed word between agreeing same-row neighbors.

    Require both its peak and box center to violate the neighbors' reading
    order. The positive inter-word gap is bounded by word width and height;
    preserve box width while updating grid-cell and capture-pixel coordinates.
    """
    ordered = [lookup[u] for u, _ in element_units if u in lookup]
    accepted = set(selected)
    for k in range(1, len(ordered) - 1):
        left, mid, right = ordered[k - 1 : k + 2]
        if not {left, mid, right} <= accepted:
            continue
        ax, ay = peaks[left]
        bx, by = peaks[mid]
        cx, cy = peaks[right]
        if max(ay, by, cy) - min(ay, by, cy) > 1 or not ax < cx or ax <= bx <= cx:
            continue
        height = (
            grid_boxes[left, 3]
            - grid_boxes[left, 1]
            + grid_boxes[right, 3]
            - grid_boxes[right, 1]
        ) / 2
        lo, hi = grid_boxes[left, 2], grid_boxes[right, 0]
        width = grid_boxes[mid, 2] - grid_boxes[mid, 0]
        center = (grid_boxes[mid, 0] + grid_boxes[mid, 2]) / 2
        if 0 < hi - lo <= 2 * width + 2 * height and (center < ax or center > cx):
            delta = (lo + hi) / 2 - center
            grid_boxes[mid, [0, 2]] += delta
            word_boxes[mid, [0, 2]] += delta * cell_width


def coherent_paragraph_words(
    selected: list[int], peaks: np.ndarray, boxes: np.ndarray
) -> list[int]:
    """Check attention peaks and predicted box centers for isolated internal words.

    A word regressor can shift a box away from an otherwise coherent peak band.
    Both passes preserve transcript endpoints and retain at least 90% of words.
    """
    selected = _coherent_vertical_words(selected, peaks[:, 1], boxes)
    if len(selected) < 12:
        return selected
    centers = (boxes[:, 1] + boxes[:, 3]) / 2
    return _coherent_vertical_words(selected, centers, boxes)


def _coherent_vertical_words(
    selected: list[int], vertical: np.ndarray, boxes: np.ndarray
) -> list[int]:
    """Remove up to two internal word positions detached from a dominant text band.

    Coordinates are grid cells. The gap scales with median word height; at least
    90% of selected words must stay connected vertically. Transcript endpoints
    remain intact because short opening or closing lines may be widely spaced.
    """
    if len(selected) < 12:
        return selected
    ordered = sorted(selected, key=lambda j: vertical[j])
    height = float(np.median(boxes[selected, 3] - boxes[selected, 1]))
    gap = max(2, 2 * height)
    bands: list[list[int]] = [[]]
    for j in ordered:
        if bands[-1] and vertical[j] - vertical[bands[-1][-1]] > gap:
            bands.append([])
        bands[-1].append(j)
    largest = max(bands, key=len)
    if (
        len(largest) == len(selected)
        or len(largest) < 0.9 * len(selected)
        or len(selected) - len(largest) > 2
    ):
        return selected
    removed = set(selected) - set(largest)
    if min(selected) in removed or max(selected) in removed:
        return selected
    return sorted(largest)


_SOURCE_FOOTER = re.compile(
    r"<tr>\s*<td\b[^>]*colspan=[\"']?\d+[\"']?[^>]*>"
    r"(Source:(?:(?!</?(?:td|th|tr|table)\b).)*)</td>\s*</tr>\s*</table>\s*$",
    re.I | re.S,
)


def separate_table_sources(
    answer: str,
    elements: list[dict],
    units: list[tuple[int, int]],
    lookup: dict[int, int],
    peaks: np.ndarray,
    grid_boxes: np.ndarray,
    word_boxes: np.ndarray,
) -> list[dict]:
    """Ground explicit final source rows using existing word predictions.

    Spans remain offsets into the original transcript and boxes use capture
    pixels. Table geometry is already refined and stays unchanged. A marker
    tells serialization to restore the closing tag after removing the row.
    """
    rebuilt: list[dict] = []
    for element in elements:
        match = (
            _SOURCE_FOOTER.search(answer, element["start"], element["end"])
            if element["type"] == "table"
            else None
        )
        if match:
            start, end = match.span(1)
            selected = [
                lookup[u]
                for u, (s, e) in enumerate(units)
                if start <= s and e <= end and u in lookup
            ]
            selected = coherent_paragraph_words(selected, peaks, grid_boxes)
            if selected:
                boxes = word_boxes[selected]
                bounds = np.r_[boxes[:, :2].min(0), boxes[:, 2:].max(0)]
                rebuilt.append({**element, "end": match.start(), "close_table": True})
                rebuilt.append(
                    {
                        "type": "text",
                        "start": start,
                        "end": end,
                        "box": np.round(bounds, 1).tolist(),
                    }
                )
                continue
        rebuilt.append(element)
    return rebuilt


def ground_cached(
    answer: str,
    capture: dict,
    models: list[Predictor] | None = None,
    with_context: bool = False,
    picture_model: PicturePredictor | None = None,
    with_extended_context: bool = False,
    region_models: list[Predictor] | None = None,
    collect_region_features: bool = False,
    table_model: TablePredictor | None = None,
    with_region_context: bool = False,
    peak_model: PeakPredictor | None = None,
    *,
    _rotated_spans: set[tuple[int, int]] | None = None,
) -> dict:
    """Reconstruct pixel-coordinate boxes from dimensions and cached attention.

    Models predict center dx/dy and log width/height in attention-grid cells.
    The caller owns model loading; this function performs no file or image I/O.
    Without models, return the deterministic rectangle baseline. Region models
    adjust outer edges in local word-height units. Feature collection returns
    each region's element index, feature row, grid-cell anchor, and word height
    for offline training-label construction.
    """
    if (region_models is not None or collect_region_features) and models is None:
        raise ValueError("Region refinement requires word boundary models")
    if region_models is not None and len(region_models) != 4:
        raise ValueError("Expected four region edge predictors")
    width, height = capture["width"], capture["height"]
    gh, gw = capture["grid"]
    cw, ch = width / gw, height / gh
    blocks = split_column_blocks(answer, capture, split_blocks(answer))
    blocks = split_bullet_tables(answer, blocks)
    blocks = split_navigation_headers(answer, capture, blocks)
    units, per_block = units_for(answer, blocks)
    sparse = capture["sparse_maps"]
    if len(units) != len(sparse["idx"]):
        raise ValueError("Cached attention units do not match the transcript")
    if get_rust() is not None:
        maps, has = (
            SparseWordMaps(sparse, (gh, gw)),
            np.asarray(sparse["has"], dtype=bool),
        )
    else:
        maps, has = dense_maps(sparse, (gh, gw))
    base = rectangle_boxes(
        (width, height),
        answer,
        blocks,
        units,
        per_block,
        maps,
        (gh, gw),
        has,
        BASE_CONFIG,
    )
    if picture_model is not None:
        refine_pictures(capture, blocks, per_block, base, picture_model, answer=answer)
    if table_model is not None:
        refine_tables(capture, answer, blocks, per_block, units, base, table_model)
    if models is None:
        return base
    if len(models) != 4:
        raise ValueError(
            "Expected center-x, center-y, log-width, and log-height predictors"
        )
    features, valid, peaks = attention_features(answer, units, sparse, (gh, gw))
    if not len(valid):
        if collect_region_features:
            base["region_features"] = []
        return base
    if peak_model is not None:
        context = contextual_features(answer, units, per_block, features, valid, peaks)
        anchors = select_word_peaks(
            context, valid, peaks, sparse, (gh, gw), blocks, per_block, peak_model
        )
        if anchors:
            # Local attention features depend only on the changed word's map.
            # Recompute those rows; contextual features below still see every peak.
            changed = [u for u in valid if u in anchors]
            changed_sparse = {
                key: [values[u] for u in changed] for key, values in sparse.items()
            }
            changed_features, _, changed_peaks = attention_features(
                answer,
                [units[u] for u in changed],
                changed_sparse,
                (gh, gw),
                {i: anchors[u] for i, u in enumerate(changed)},
            )
            lookup = {u: row for row, u in enumerate(valid)}
            rows = [lookup[u] for u in changed]
            features[rows] = changed_features
            peaks[rows] = changed_peaks
    if with_context or with_extended_context:
        if peak_model is not None and not anchors:
            features = context
        else:
            features = contextual_features(
                answer, units, per_block, features, valid, peaks
            )
    if with_extended_context:
        features = extended_features(
            answer, units, blocks, per_block, features, valid, peaks, sparse, (gh, gw)
        )
    predicted = np.column_stack([predict(model, features) for model in models])
    centers, sizes = peaks + predicted[:, :2], np.exp(predicted[:, 2:])
    grid_boxes = np.column_stack([centers - sizes / 2, centers + sizes / 2])
    word_boxes = grid_boxes * [
        cw,
        ch,
        cw,
        ch,
    ]
    lookup = {u: j for j, u in enumerate(valid)}
    valid_starts = [units[u][0] for u in valid]
    # Descriptions inside image references are not printed text. Keep their
    # cached indices intact, but exclude them from text-region boundaries.
    image_units = set()
    for match in _INLINE_IMAGE_REFERENCE.finditer(answer):
        first = bisect_left(valid_starts, match.start())
        last = bisect_left(valid_starts, match.end())
        image_units.update(u for u in valid[first:last] if units[u][1] <= match.end())
    region_records = []
    cell_scale = np.array([cw, ch, cw, ch])
    refine_table_word_boxes(
        answer, base["elements"], units, valid, grid_boxes, peaks, cell_scale
    )
    # Snapshot pixel-coordinate paragraph edges before any word-based updates.
    # Three agreeing right edges provide a candidate width for the same left column.
    column_evidence = [
        list(e["box"])
        for e in base["elements"]
        if e["box"] is not None
        and e["type"] in {"text", "list"}
        and e["end"] - e["start"] >= 80
        and e["box"][3] - e["box"][1] >= 2 * ch
    ]
    for element_index, element in enumerate(base["elements"]):
        box = element["box"]
        if box is None or element["type"] not in _TEXT_TYPES:
            continue
        # Units are in transcript order; only this element's span can contribute.
        first = bisect_left(valid_starts, element["start"])
        last = bisect_right(valid_starts, element["end"])
        element_units = [
            (u, units[u]) for u in valid[first:last] if u not in image_units
        ]
        column_right = box[2]
        if element["type"] in {"text", "list"}:
            rights = np.array(
                [
                    b[2]
                    for b in column_evidence
                    if abs(b[0] - box[0]) <= 2 * cw and b[2] > box[2] + cw
                ]
            )
            if len(rights) >= 3:
                groups = [rights[abs(rights - r) <= cw] for r in rights]
                support = max(groups, key=len)
                if len(support) >= 3:
                    column_right = float(np.median(support))
        # Require two consecutive valid words in the added band to advance along
        # one attention row. This guards against isolated peaks in adjacent blocks.
        # Peak distances are grid cells; the original vertical band stays fixed.
        if column_right > box[2]:
            outer = [
                lookup[u]
                for u, (start, end) in element_units
                if u in lookup
                and element["start"] <= start
                and end <= element["end"]
                and box[2] + cw < peaks[lookup[u], 0] * cw <= column_right + cw
                and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch
            ]
            coherent = any(
                b == a + 1
                and abs(peaks[a, 1] - peaks[b, 1]) <= 1
                and 0 <= peaks[b, 0] - peaks[a, 0] <= 3
                for a, b in zip(outer, outer[1:])
            )
            if not coherent:
                column_right = box[2]
        selected = [
            lookup[u]
            for u, (start, end) in element_units
            if u in lookup
            and element["start"] <= start
            and end <= element["end"]
            and (
                element["type"] in {"heading", "header", "footer"}
                or (element["start"], element["end"]) in (_rotated_spans or ())
                or box[0] - cw <= peaks[lookup[u], 0] * cw <= column_right + cw
            )
            and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch
        ]
        # Extend paragraph and list lines through nearby transcript neighbors. Cell
        # distances keep the rule independent of render resolution; the original
        # vertical guard keeps recovery within the existing vertical band.
        if selected and element["type"] in {"text", "list"}:
            candidates = {
                lookup[u]
                for u, (start, end) in element_units
                if u in lookup
                and element["start"] <= start
                and end <= element["end"]
                and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch
            }
            accepted = set(selected)
            changed = True
            while changed:
                changed = False
                for j in sorted(candidates - accepted):
                    for neighbor in (j - 1, j + 1):
                        if (
                            neighbor not in accepted
                            or abs(peaks[j, 1] - peaks[neighbor, 1]) > 1
                        ):
                            continue
                        gap = max(
                            0,
                            grid_boxes[j, 0] - grid_boxes[neighbor, 2],
                            grid_boxes[neighbor, 0] - grid_boxes[j, 2],
                        )
                        if gap <= 1:
                            accepted.add(j)
                            changed = True
                            break
            selected = recover_line_tails(accepted, candidates, peaks)
            selected = recover_short_line_tails(selected, candidates, peaks, grid_boxes)
        if selected and element["type"] in {"text", "list"} and _rotated_spans is None:
            selected = coherent_paragraph_words(selected, peaks, grid_boxes)
            # Short key/value blocks can have distant right-aligned values.
            # Require overlapping word extents on distinct rows; one isolated
            # numeric peak cannot expand the paragraph's horizontal boundary.
            if 4 <= len(element_units) <= 16:
                numeric = [
                    lookup[u]
                    for u, (start, end) in element_units
                    if u in lookup
                    and lookup[u] not in selected
                    and _NUMERIC_WORD.fullmatch(answer[start:end])
                    and box[1] - ch <= peaks[lookup[u], 1] * ch <= box[3] + ch
                    and peaks[lookup[u], 0] * cw > box[2] + cw
                ]
                supported = [
                    j
                    for j in numeric
                    if any(
                        k != j
                        and max(grid_boxes[j, 0], grid_boxes[k, 0])
                        <= min(grid_boxes[j, 2], grid_boxes[k, 2])
                        and abs(peaks[j, 1] - peaks[k, 1]) >= 2
                        for k in numeric
                    )
                ]
                selected = sorted(set(selected) | set(supported))

        if element["type"] in {"text", "list"}:
            selected = recover_paragraph_opening(
                selected, element_units, lookup, peaks, grid_boxes
            )
        if selected and (element["start"], element["end"]) in (_rotated_spans or ()):
            selected = coherent_rotated_words(selected, peaks)
        if selected and element["type"] in {"text", "list", "heading"}:
            align_word_boxes_to_neighbor_row(
                selected, element_units, lookup, peaks, grid_boxes, word_boxes, ch
            )
            align_word_boxes_to_reading_order(
                selected, element_units, lookup, peaks, grid_boxes, word_boxes, cw
            )
        if selected:
            boxes = word_boxes[selected]
            bounds = np.r_[boxes[:, :2].min(0), boxes[:, 2:].max(0)]
            bounds = np.clip(bounds, 0, [width, height, width, height])
            if bounds[2] > bounds[0] and bounds[3] > bounds[1]:
                element["box"] = np.round(bounds, 1).tolist()
                if region_models is not None or collect_region_features:
                    anchor = np.asarray(element["box"]) / cell_scale
                    row, word_height = region_features(
                        element["type"],
                        answer[element["start"] : element["end"]],
                        anchor,
                        np.asarray(box) / cell_scale,
                        grid_boxes[selected],
                        features[selected, 0],
                        (gh, gw),
                    )
                    region_records.append(
                        {
                            "element_index": element_index,
                            "text": element_text(
                                answer, element["start"], element["end"]
                            ),
                            "features": row,
                            "anchor": anchor.tolist(),
                            "height": word_height,
                        }
                    )
    if with_region_context and region_records:
        for record, row in zip(
            region_records, contextual_region_features(region_records)
        ):
            record["features"] = row.tolist()
    if region_models is not None and region_records:
        rows = np.asarray([record["features"] for record in region_records])
        glyph_rows = None
        if any(isinstance(model, HeadingGlyphRegionBlend) for model in region_models):
            glyph_rows = np.column_stack(
                [
                    rows,
                    heading_glyph_features(
                        [record["text"] for record in region_records]
                    ),
                ]
            )
        residuals = np.column_stack(
            [
                predict(
                    model,
                    glyph_rows if isinstance(model, HeadingGlyphRegionBlend) else rows,
                )
                for model in region_models
            ]
        )
        for record, residual in zip(region_records, residuals):
            # Limit extrapolation to two local word heights on each edge.
            bounds = np.clip(
                np.asarray(record["anchor"]) + residual.clip(-2, 2) * record["height"],
                0,
                [gw, gh, gw, gh],
            )
            if bounds[2] > bounds[0] and bounds[3] > bounds[1]:
                base["elements"][record["element_index"]]["box"] = np.round(
                    bounds * cell_scale, 1
                ).tolist()
    base["elements"] = separate_table_sources(
        answer, base["elements"], units, lookup, peaks, grid_boxes, word_boxes
    )
    if collect_region_features:
        base["region_features"] = region_records
    # Region feature records describe the original pre-refinement anchors.
    # Orientation recovery only replaces final boxes; the private span set
    # marks the normalized pass and prevents recursively rotating it again.
    if _rotated_spans is None:
        spans = vertical_text_spans(answer, capture)
        if spans:
            rotated = ground_cached(
                answer,
                rotate_attention_clockwise(capture),
                models,
                with_context=with_context,
                picture_model=picture_model,
                with_extended_context=with_extended_context,
                region_models=region_models,
                table_model=table_model,
                with_region_context=with_region_context,
                peak_model=peak_model,
                _rotated_spans=spans,
            )
            lookup_boxes = {
                (element["start"], element["end"]): element["box"]
                for element in rotated["elements"]
            }
            for element in base["elements"]:
                key = (element["start"], element["end"])
                rotated_box = lookup_boxes.get(key)
                if key in spans and rotated_box is not None:
                    x0, y0, x1, y1 = rotated_box
                    element["box"] = [y0, height - x1, y1, height - x0]
    if _rotated_spans is None:
        recover_repeated_paragraphs(answer, capture, base["elements"], units)
    return base