Datasets:

Modalities:
Image
Text
Formats:
parquet
Languages:
Armenian
Size:
< 1K
ArXiv:
License:
File size: 28,182 Bytes
551cc83
 
 
 
 
 
 
 
 
 
 
 
3cfdd38
551cc83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfdd38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
551cc83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfdd38
 
 
 
 
 
 
 
551cc83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfdd38
 
 
 
 
 
 
 
551cc83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build predicted text for annotation boxes and OCR regions."""

from __future__ import annotations

import sys
from pathlib import Path

_BOX_GROUPING = str(Path(__file__).resolve().parent.parent / "box_grouping")
if _BOX_GROUPING not in sys.path:
    sys.path.insert(0, _BOX_GROUPING)

import statistics
from typing import Any, Callable

from geometry import Box
from models import Word, AnnotationBox, PredictedRow
from spatial import (
    merge_boxes,
    normalize_whitespace,
    join_box_lines_with_hyphenation,
    local_boxes_share_line,
    horizontal_overlap_ratio,
    interval_overlap,
    order_words_in_box_context,
    words_in_box,
    word_local_center,
    box_to_local_bounds,
    row_sequence_prefix,
    report_box,
    rounded_box,
)


SEQUENCE_PREFIX_COLUMN_MIN_VERTICAL_OVERLAP_RATIO = 0.5
SEQUENCE_PREFIX_COLUMN_MAX_HORIZONTAL_OVERLAP_RATIO = 0.5


def build_sequence_prefix_stats(
    items: list[dict[str, Any]],
) -> dict[str, dict[str, Any]]:
    prefix_stats: dict[str, dict[str, Any]] = {}
    for item in items:
        sequence_prefix = item["sequence_prefix"]
        stats = prefix_stats.setdefault(
            sequence_prefix,
            {
                "min_y": item["start_local_y"],
                "min_x": item["start_local_x"],
                "max_y": item["local_box"].y_max,
                "max_x": item["local_box"].x_max,
                "row_ids": set(),
            },
        )
        stats["min_y"] = min(stats["min_y"], item["start_local_y"])
        stats["min_x"] = min(stats["min_x"], item["start_local_x"])
        stats["max_y"] = max(stats["max_y"], item["local_box"].y_max)
        stats["max_x"] = max(stats["max_x"], item["local_box"].x_max)
        stats["row_ids"].add(item["row_id"])

    for stats in prefix_stats.values():
        stats["row_count"] = len(stats["row_ids"])

    return prefix_stats


def sequence_prefixes_look_like_columns(
    prefix_stats: dict[str, dict[str, Any]],
) -> bool:
    multi_row_prefixes = [
        prefix for prefix, stats in prefix_stats.items() if stats["row_count"] > 1
    ]
    if len(multi_row_prefixes) < 2:
        return False

    ordered_prefixes = sorted(
        multi_row_prefixes,
        key=lambda prefix: (
            prefix_stats[prefix]["min_x"],
            prefix_stats[prefix]["min_y"],
            prefix,
        ),
    )
    overlapping_column_pairs = 0
    for left_prefix, right_prefix in zip(ordered_prefixes, ordered_prefixes[1:]):
        left_stats = prefix_stats[left_prefix]
        right_stats = prefix_stats[right_prefix]
        left_height = left_stats["max_y"] - left_stats["min_y"]
        right_height = right_stats["max_y"] - right_stats["min_y"]
        left_width = left_stats["max_x"] - left_stats["min_x"]
        right_width = right_stats["max_x"] - right_stats["min_x"]
        min_height = min(left_height, right_height)
        min_width = min(left_width, right_width)
        if min_height <= 0 or min_width <= 0:
            continue

        vertical_overlap_ratio = (
            interval_overlap(
                left_stats["min_y"],
                left_stats["max_y"],
                right_stats["min_y"],
                right_stats["max_y"],
            )
            / min_height
        )
        horizontal_overlap_ratio_value = (
            interval_overlap(
                left_stats["min_x"],
                left_stats["max_x"],
                right_stats["min_x"],
                right_stats["max_x"],
            )
            / min_width
        )
        if (
            vertical_overlap_ratio >= SEQUENCE_PREFIX_COLUMN_MIN_VERTICAL_OVERLAP_RATIO
            and horizontal_overlap_ratio_value
            <= SEQUENCE_PREFIX_COLUMN_MAX_HORIZONTAL_OVERLAP_RATIO
        ):
            overlapping_column_pairs += 1

    return overlapping_column_pairs == len(ordered_prefixes) - 1


def sequence_prefix_column_indexes(
    prefix_stats: dict[str, dict[str, Any]],
) -> dict[str, int]:
    return {
        prefix: index
        for index, prefix in enumerate(
            sorted(
                prefix_stats,
                key=lambda item: (
                    prefix_stats[item]["min_x"],
                    prefix_stats[item]["min_y"],
                    item,
                ),
            )
        )
    }


def _build_line_groups(
    ordered_items: list[dict[str, Any]],
    items_key: str,
    prefix_guard: Callable[[str, set[str]], bool],
) -> list[dict[str, Any]]:
    """Group reading-order items into lines by vertical proximity.

    `prefix_guard(item_prefix, group_prefixes)` decides whether an item may
    join a candidate line group that doesn't yet contain its sequence
    prefix; callers pass path-specific rules here (kept faithful to the
    single-box and multi-box callers' historically divergent behavior).
    """
    line_groups: list[dict[str, Any]] = []
    for item in ordered_items:
        best_group: dict[str, Any] | None = None
        best_vertical_distance = float("inf")
        for line_group in line_groups:
            if not local_boxes_share_line(
                line_group["local_box"], item["local_box"]
            ):
                continue
            if any(
                horizontal_overlap_ratio(existing["local_box"], item["local_box"])
                > 0.35
                for existing in line_group[items_key]
            ):
                continue
            group_prefixes = {
                existing["sequence_prefix"] for existing in line_group[items_key]
            }
            if not prefix_guard(item["sequence_prefix"], group_prefixes):
                continue
            line_group_center_y = (
                line_group["local_box"].y_min + line_group["local_box"].y_max
            ) / 2.0
            item_center_y = (
                item["local_box"].y_min + item["local_box"].y_max
            ) / 2.0
            vertical_distance = abs(line_group_center_y - item_center_y)
            if vertical_distance < best_vertical_distance:
                best_vertical_distance = vertical_distance
                best_group = line_group

        if best_group is None:
            line_groups.append({items_key: [item], "local_box": item["local_box"]})
            continue

        best_group[items_key].append(item)
        best_group["local_box"] = merge_boxes(
            [best_group["local_box"], item["local_box"]]
        )

    return line_groups


def _order_line_groups(
    line_groups: list[dict[str, Any]],
    items_key: str,
    read_prefixes_as_columns: bool,
    prefix_column_indexes: dict[str, int],
    fallback_key: Callable[[dict[str, Any]], tuple[float, float]],
) -> list[dict[str, Any]]:
    """Sort line groups into reading order.

    `fallback_key(group)` supplies the (y, x) tiebreaker used when the
    prefixes don't read as columns; callers pass path-specific formulas
    here (kept faithful to the single-box and multi-box callers'
    historically divergent behavior).
    """

    def line_group_order_key(group: dict[str, Any]) -> tuple[float, ...]:
        group_prefixes = {item["sequence_prefix"] for item in group[items_key]}
        if read_prefixes_as_columns:
            column_index = min(
                prefix_column_indexes[prefix] for prefix in group_prefixes
            )
            return (
                float(column_index),
                group["local_box"].y_min,
                group["local_box"].x_min,
                group["local_box"].y_max,
            )

        fallback_y, fallback_x = fallback_key(group)
        return (
            fallback_y,
            fallback_x,
            group["local_box"].y_min,
            group["local_box"].x_min,
        )

    return sorted(line_groups, key=line_group_order_key)


def _group_items_into_ordered_lines(
    ordered_items: list[dict[str, Any]],
    items_key: str,
    item_type: str,
    prefix_stats: dict[str, dict[str, Any]],
    read_prefixes_as_columns: bool,
    prefix_column_indexes: dict[str, int],
) -> list[dict[str, Any]]:
    """Group items into lines and sort those lines into reading order.

    `item_type` ("fragment" or "row") selects the rules for (a) whether an
    item may join a line group that doesn't yet contain its sequence
    prefix, and (b) the fallback (y, x) sort key used when the prefixes
    don't read as columns. The single-box ("fragment") and multi-box
    ("row") callers have historically diverged on both rules; that
    divergence is preserved here rather than unified, since unifying it
    would change results.
    """
    if item_type == "fragment":

        def prefix_guard(item_prefix: str, group_prefixes: set[str]) -> bool:
            if item_prefix in group_prefixes:
                return True
            if prefix_stats[item_prefix]["row_count"] > 1:
                return False
            return not any(
                prefix_stats[prefix]["row_count"] > 1 for prefix in group_prefixes
            )

        def fallback_key(group: dict[str, Any]) -> tuple[float, float]:
            group_prefixes = {item["sequence_prefix"] for item in group[items_key]}
            return (
                min(prefix_stats[prefix]["min_y"] for prefix in group_prefixes),
                min(prefix_stats[prefix]["min_x"] for prefix in group_prefixes),
            )

    elif item_type == "row":

        def prefix_guard(item_prefix: str, group_prefixes: set[str]) -> bool:
            if not read_prefixes_as_columns:
                return True
            return item_prefix in group_prefixes

        def fallback_key(group: dict[str, Any]) -> tuple[float, float]:
            return (
                min(item["start_local_y"] for item in group[items_key]),
                min(item["start_local_x"] for item in group[items_key]),
            )

    else:
        raise ValueError(f"unknown item_type: {item_type!r}")

    line_groups = _build_line_groups(ordered_items, items_key, prefix_guard)
    return _order_line_groups(
        line_groups,
        items_key,
        read_prefixes_as_columns,
        prefix_column_indexes,
        fallback_key,
    )


def count_empty_words_in_non_empty_boxes(
    predicted_rows: list[PredictedRow],
    annotation_boxes: list[AnnotationBox],
) -> int:
    non_empty_annotation_boxes = [
        annotation_box
        for annotation_box in annotation_boxes
        if annotation_box.has_transcription and normalize_whitespace(annotation_box.text)
    ]
    count = 0
    for predicted_row in predicted_rows:
        for word in predicted_row.words:
            if word.text.strip():
                continue
            if any(
                annotation_box.contains_point(word.center[0], word.center[1])
                for annotation_box in non_empty_annotation_boxes
            ):
                count += 1
    return count


def build_box_line_items(
    annotation_box: AnnotationBox,
    rows: list[dict[str, Any]],
    predicted_rows_by_id: dict[str, PredictedRow],
    split_line_groups_by_id: dict[str, dict[str, Any]],
    excluded_annotation_boxes: list[AnnotationBox] | None = None,
) -> list[dict[str, Any]]:
    _ = split_line_groups_by_id

    def in_excluded_box(word: Word) -> bool:
        if not excluded_annotation_boxes:
            return False
        cx, cy = word.center
        return any(box.contains_point(cx, cy) for box in excluded_annotation_boxes)

    def build_row_fragments(
        row: dict[str, Any],
        predicted_row: PredictedRow,
    ) -> list[dict[str, Any]]:
        if (
            row.get("use_full_row_for_assigned_box")
            and row.get("assigned_box_id") == annotation_box.box_id
        ):
            fragment_words = order_words_in_box_context(
                predicted_row.words, annotation_box
            )
        else:
            fragment_words = words_in_box(predicted_row, annotation_box)

        if excluded_annotation_boxes:
            fragment_words = [w for w in fragment_words if not in_excluded_box(w)]

        word_items: list[dict[str, Any]] = []
        for word in fragment_words:
            if not word.text.strip():
                continue
            local_box = box_to_local_bounds(word.box, annotation_box)
            local_center_x, local_center_y = word_local_center(word, annotation_box)
            word_items.append(
                {
                    "text": word.text,
                    "global_box": word.box,
                    "local_box": local_box,
                    "start_local_x": local_center_x,
                    "start_local_y": local_center_y,
                }
            )

        if not word_items:
            return []

        fragments: list[dict[str, Any]] = []
        current_words: list[dict[str, Any]] = [word_items[0]]
        current_max_x = word_items[0]["local_box"].x_max

        for item in word_items[1:]:
            previous_local_box = current_words[-1]["local_box"]
            tolerance = max(
                8.0,
                min(previous_local_box.height, item["local_box"].height) * 0.15,
            )
            if item["local_box"].x_min < current_max_x - tolerance:
                fragments.append(
                    {
                        "row_id": row["row_id"],
                        "sequence_prefix": row_sequence_prefix(row["row_id"]),
                        "status": row["status"],
                        "text": normalize_whitespace(
                            " ".join(word["text"] for word in current_words)
                        ),
                        "global_box": merge_boxes(
                            [word["global_box"] for word in current_words]
                        ),
                        "local_box": merge_boxes(
                            [word["local_box"] for word in current_words]
                        ),
                        "start_local_x": current_words[0]["start_local_x"],
                        "start_local_y": current_words[0]["start_local_y"],
                    }
                )
                current_words = [item]
                current_max_x = item["local_box"].x_max
                continue

            current_words.append(item)
            current_max_x = max(current_max_x, item["local_box"].x_max)

        fragments.append(
            {
                "row_id": row["row_id"],
                "sequence_prefix": row_sequence_prefix(row["row_id"]),
                "status": row["status"],
                "text": normalize_whitespace(
                    " ".join(word["text"] for word in current_words)
                ),
                "global_box": merge_boxes(
                    [word["global_box"] for word in current_words]
                ),
                "local_box": merge_boxes(
                    [word["local_box"] for word in current_words]
                ),
                "start_local_x": current_words[0]["start_local_x"],
                "start_local_y": current_words[0]["start_local_y"],
            }
        )
        return fragments

    fragment_items: list[dict[str, Any]] = []
    for row in rows:
        predicted_row = predicted_rows_by_id[row["row_id"]]
        fragment_items.extend(build_row_fragments(row, predicted_row))

    if not fragment_items:
        return []

    prefix_stats = build_sequence_prefix_stats(fragment_items)
    read_prefixes_as_columns = sequence_prefixes_look_like_columns(prefix_stats)
    prefix_column_indexes = sequence_prefix_column_indexes(prefix_stats)

    ordered_fragment_items = sorted(
        fragment_items,
        key=lambda item: (
            item["start_local_y"],
            item["start_local_x"],
            item["row_id"],
            item["text"],
        ),
    )

    ordered_line_groups = _group_items_into_ordered_lines(
        ordered_fragment_items,
        "fragment_items",
        "fragment",
        prefix_stats,
        read_prefixes_as_columns,
        prefix_column_indexes,
    )
    line_items: list[dict[str, Any]] = []
    from spatial import local_box_to_list  # avoid re-listing at top level

    for line_index, line_group in enumerate(ordered_line_groups):
        ordered_fragment_items_in_line = sorted(
            line_group["fragment_items"],
            key=lambda item: (
                item["start_local_x"],
                item["start_local_y"],
                item["local_box"].x_max,
                item["row_id"],
                item["text"],
            ),
        )
        row_ids: list[str] = []
        row_statuses: list[str] = []
        for item in ordered_fragment_items_in_line:
            if item["row_id"] not in row_ids:
                row_ids.append(item["row_id"])
                row_statuses.append(item["status"])
        global_line_box = merge_boxes(
            [item["global_box"] for item in ordered_fragment_items_in_line]
        )
        local_line_box = merge_boxes(
            [item["local_box"] for item in ordered_fragment_items_in_line]
        )
        line_items.append(
            {
                "line_id": f"{annotation_box.box_id}:line_{line_index}",
                "row_ids": row_ids,
                "row_statuses": row_statuses,
                "line_text": normalize_whitespace(
                    " ".join(
                        item["text"] for item in ordered_fragment_items_in_line
                    )
                ),
                "box": rounded_box(global_line_box),
                "local_box": local_box_to_list(local_line_box),
            }
        )

    return line_items


def build_region_predicted_text(
    region_rows: list[dict[str, Any]],
    predicted_rows_by_id: dict[str, PredictedRow],
    ordered_boxes: list[AnnotationBox],
    excluded_annotation_boxes: list[AnnotationBox] | None = None,
) -> tuple[str, int, list[str], Box | None, frozenset[int]]:
    if not region_rows:
        return ("", 0, [], None, frozenset())

    def filtered_row_text(row: dict[str, Any]) -> str:
        if not excluded_annotation_boxes:
            return normalize_whitespace(row["row_text"])
        predicted_row = predicted_rows_by_id[row["row_id"]]
        words = [
            w
            for w in predicted_row.words
            if w.text.strip()
            and not any(
                box.contains_point(*w.center) for box in excluded_annotation_boxes
            )
        ]
        return normalize_whitespace(" ".join(w.text for w in words))

    if len(ordered_boxes) == 1:
        annotation_box = ordered_boxes[0]
        line_items = build_box_line_items(
            annotation_box=annotation_box,
            rows=region_rows,
            predicted_rows_by_id=predicted_rows_by_id,
            split_line_groups_by_id={},
            excluded_annotation_boxes=excluded_annotation_boxes,
        )
        if line_items:
            predicted_box = merge_boxes(
                [
                    Box(
                        x_min=float(item["box"][0]),
                        y_min=float(item["box"][1]),
                        x_max=float(item["box"][2]),
                        y_max=float(item["box"][3]),
                    )
                    for item in line_items
                ]
            )
            assigned_row_ids: list[str] = []
            for line_item in line_items:
                for row_id in line_item["row_ids"]:
                    if row_id not in assigned_row_ids:
                        assigned_row_ids.append(row_id)
            joined_text, join_word_indices = join_box_lines_with_hyphenation(
                [item["line_text"] for item in line_items]
            )
            return (
                joined_text,
                len(line_items),
                assigned_row_ids,
                predicted_box,
                join_word_indices,
            )

    if ordered_boxes:
        ordered_box_id_to_index = {
            annotation_box.box_id: index
            for index, annotation_box in enumerate(ordered_boxes)
        }

        def ordering_box_for_row(row: dict[str, Any]) -> AnnotationBox | None:
            touched_box_ids = [
                box_id
                for box_id in row.get("touched_box_ids", [])
                if box_id in ordered_box_id_to_index
            ]
            if touched_box_ids:
                leftmost_box_id = min(
                    touched_box_ids,
                    key=lambda box_id: (
                        ordered_box_id_to_index[box_id],
                        ordered_boxes[ordered_box_id_to_index[box_id]].bounds.x_min,
                        ordered_boxes[ordered_box_id_to_index[box_id]].bounds.y_min,
                    ),
                )
                return ordered_boxes[ordered_box_id_to_index[leftmost_box_id]]

            assigned_box_id = row.get("assigned_box_id")
            if assigned_box_id in ordered_box_id_to_index:
                return ordered_boxes[ordered_box_id_to_index[assigned_box_id]]

            dominant_box_id = row.get("dominant_box_id")
            if dominant_box_id in ordered_box_id_to_index:
                return ordered_boxes[ordered_box_id_to_index[dominant_box_id]]

            return None

        def relevant_words_in_box_context(
            row: dict[str, Any],
            annotation_box: AnnotationBox,
        ) -> list[Word]:
            predicted_row = predicted_rows_by_id[row["row_id"]]
            box_words = words_in_box(predicted_row, annotation_box)
            if box_words:
                return box_words
            return order_words_in_box_context(
                [word for word in predicted_row.words if word.text.strip()],
                annotation_box,
            )

        def row_order_key_within_box(
            row: dict[str, Any],
            annotation_box: AnnotationBox,
        ) -> tuple[float, float, float, str]:
            relevant_words = relevant_words_in_box_context(row, annotation_box)
            if not relevant_words:
                row_bounds = report_box(row["row_box"])
                return (
                    row_bounds.y_min,
                    row_bounds.x_min,
                    row_bounds.x_max,
                    row["row_id"],
                )

            local_word_centers = [
                word_local_center(word, annotation_box) for word in relevant_words
            ]
            first_word_local_x, first_word_local_y = local_word_centers[0]
            return (
                first_word_local_y,
                first_word_local_x,
                statistics.median(
                    local_center_y for _, local_center_y in local_word_centers
                ),
                row["row_id"],
            )

        grouped_rows: dict[str, list[dict[str, Any]]] = {}
        for row in region_rows:
            ordering_box = ordering_box_for_row(row)
            if ordering_box is None:
                continue
            grouped_rows.setdefault(ordering_box.box_id, []).append(row)

        line_texts: list[str] = []
        assigned_row_ids_multi: list[str] = []
        predicted_boxes: list[Box] = []
        for annotation_box in ordered_boxes:
            box_rows = grouped_rows.get(annotation_box.box_id, [])
            if not box_rows:
                continue

            ordered_row_items = []
            for row in sorted(
                box_rows,
                key=lambda item: row_order_key_within_box(item, annotation_box),
            ):
                relevant_words = relevant_words_in_box_context(row, annotation_box)
                if relevant_words:
                    relevant_box = merge_boxes([word.box for word in relevant_words])
                    start_local_x, start_local_y = word_local_center(
                        relevant_words[0], annotation_box
                    )
                else:
                    relevant_box = report_box(row["row_box"])
                    local_relevant_box = box_to_local_bounds(
                        relevant_box, annotation_box
                    )
                    start_local_x = local_relevant_box.x_min
                    start_local_y = local_relevant_box.y_min

                ordered_row_items.append(
                    {
                        "row_id": row["row_id"],
                        "sequence_prefix": row_sequence_prefix(row["row_id"]),
                        "status": row["status"],
                        "row_text": filtered_row_text(row),
                        "full_row_box": report_box(row["row_box"]),
                        "local_box": box_to_local_bounds(relevant_box, annotation_box),
                        "start_local_x": start_local_x,
                        "start_local_y": start_local_y,
                    }
                )

            prefix_stats = build_sequence_prefix_stats(ordered_row_items)
            read_prefixes_as_columns = sequence_prefixes_look_like_columns(
                prefix_stats
            )
            prefix_column_indexes = sequence_prefix_column_indexes(prefix_stats)

            ordered_line_groups = _group_items_into_ordered_lines(
                ordered_row_items,
                "row_items",
                "row",
                prefix_stats,
                read_prefixes_as_columns,
                prefix_column_indexes,
            )
            for line_group in ordered_line_groups:
                ordered_row_items_in_line = sorted(
                    line_group["row_items"],
                    key=lambda item: (
                        item["start_local_x"],
                        item["start_local_y"],
                        item["local_box"].x_max,
                        item["row_id"],
                    ),
                )
                line_text = normalize_whitespace(
                    " ".join(
                        item["row_text"]
                        for item in ordered_row_items_in_line
                        if item["row_text"]
                    )
                )
                if line_text:
                    line_texts.append(line_text)

                predicted_boxes.append(
                    merge_boxes(
                        [item["full_row_box"] for item in ordered_row_items_in_line]
                    )
                )
                for item in ordered_row_items_in_line:
                    if item["row_id"] not in assigned_row_ids_multi:
                        assigned_row_ids_multi.append(item["row_id"])

        if line_texts:
            predicted_box = merge_boxes(predicted_boxes) if predicted_boxes else None
            return (
                "\n".join(line_texts),
                len(line_texts),
                assigned_row_ids_multi,
                predicted_box,
                frozenset(),
            )

    def region_row_order_key(
        row: dict[str, Any],
    ) -> tuple[float, float, float, str]:
        predicted_row = predicted_rows_by_id[row["row_id"]]
        if not predicted_row.words:
            return (
                row["row_box"][1],
                row["row_box"][0],
                row["row_box"][2],
                row["row_id"],
            )

        word_center_ys = [word.center[1] for word in predicted_row.words]
        word_center_xs = [word.center[0] for word in predicted_row.words]
        return (
            statistics.median(word_center_ys),
            min(word_center_xs),
            statistics.median(word_center_xs),
            row["row_id"],
        )

    ordered_rows = sorted(region_rows, key=region_row_order_key)

    line_texts_fallback: list[str] = []
    assigned_row_ids_fallback: list[str] = []
    predicted_boxes_fallback: list[Box] = []
    for row in ordered_rows:
        row_text = filtered_row_text(row)
        if row_text:
            line_texts_fallback.append(row_text)
        assigned_row_ids_fallback.append(row["row_id"])
        predicted_boxes_fallback.append(report_box(row["row_box"]))

    predicted_box = (
        merge_boxes(predicted_boxes_fallback) if predicted_boxes_fallback else None
    )
    return (
        "\n".join(line_texts_fallback),
        len(line_texts_fallback),
        assigned_row_ids_fallback,
        predicted_box,
        frozenset(),
    )