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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Spatial utilities: box merging, word placement, reading order, split-line detection."""

from __future__ import annotations

import math
from typing import Any, Sequence

from geometry import Box, polygon_bounds
from models import Word, AnnotationBox, PredictedRow


SPLIT_LINE_VERTICAL_OVERLAP_THRESHOLD = 0.5
SPLIT_LINE_HORIZONTAL_OVERLAP_TOLERANCE_RATIO = 0.25
SPLIT_LINE_MAX_GAP_HEIGHT_MULTIPLIER = 2.0
LINE_END_HYPHENS = "-֊‐‑‒–—"
MULTI_BOX_SINGLE_COLUMN_LOCATION_THRESHOLD = 0.8
MULTI_BOX_SINGLE_COLUMN_OVERLAP_THRESHOLD = 0.8
MULTI_BOX_OVERLAP_TIE_TOLERANCE = 0.05
MULTI_BOX_BEGINNING_BOX_OVERLAP_TOLERANCE = 0.25
MULTI_BOX_BEGINNING_BOX_MIN_LEADING_WORDS = 2
MULTI_BOX_BEGINNING_BOX_MIN_COVERAGE = 0.35
BOX_LINE_VERTICAL_OVERLAP_THRESHOLD = 0.60
READING_ORDER_ROW_OVERLAP_THRESHOLD = 0.5
READING_ORDER_COLUMN_OVERLAP_THRESHOLD = 0.5


def merge_boxes(boxes: list[Box]) -> Box:
    return Box(
        x_min=min(box.x_min for box in boxes),
        y_min=min(box.y_min for box in boxes),
        x_max=max(box.x_max for box in boxes),
        y_max=max(box.y_max for box in boxes),
    )


def row_box(predicted_row: PredictedRow) -> Box:
    return merge_boxes([word.box for word in predicted_row.words])


def interval_overlap(
    start_a: float, end_a: float, start_b: float, end_b: float
) -> float:
    return max(0.0, min(end_a, end_b) - max(start_a, start_b))


def point_to_box_local_coordinates(
    point: tuple[float, float],
    annotation_box: AnnotationBox,
) -> tuple[float, float]:
    origin_x = annotation_box.rect.x_min
    origin_y = annotation_box.rect.y_min
    rotation_radians = math.radians(annotation_box.rotation)
    cos_theta = math.cos(rotation_radians)
    sin_theta = math.sin(rotation_radians)
    delta_x = point[0] - origin_x
    delta_y = point[1] - origin_y
    return (
        delta_x * cos_theta + delta_y * sin_theta,
        -delta_x * sin_theta + delta_y * cos_theta,
    )


def box_to_local_bounds(box: Box, annotation_box: AnnotationBox) -> Box:
    local_points = [
        point_to_box_local_coordinates(point, annotation_box)
        for point in box.to_polygon()
    ]
    return polygon_bounds(local_points)


def word_local_center(
    word: Word, annotation_box: AnnotationBox
) -> tuple[float, float]:
    return point_to_box_local_coordinates(word.center, annotation_box)


def local_box_to_list(box: Box) -> list[float]:
    return [
        round(box.x_min, 3),
        round(box.y_min, 3),
        round(box.x_max, 3),
        round(box.y_max, 3),
    ]


def rounded_box(box: Box) -> list[float]:
    return [round(value, 3) for value in box.to_list()]


def report_box(box_values: list[float]) -> Box:
    return Box(
        x_min=float(box_values[0]),
        y_min=float(box_values[1]),
        x_max=float(box_values[2]),
        y_max=float(box_values[3]),
    )


def edge_words_in_box(
    predicted_row: PredictedRow,
    annotation_box: AnnotationBox,
) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
    edge_words: list[dict[str, Any]] = []

    for index, word in enumerate(predicted_row.words):
        local_box = box_to_local_bounds(word.box, annotation_box)
        edge_words.append(
            {
                "index": index,
                "text": word.text,
                "global_box": [round(value, 3) for value in word.box.to_list()],
                "local_box": local_box,
            }
        )

    if not edge_words:
        return (None, None)

    first_word = min(
        edge_words, key=lambda item: (item["local_box"].x_min, item["index"])
    )
    last_word = max(
        edge_words, key=lambda item: (item["local_box"].x_max, -item["index"])
    )
    return (first_word, last_word)


def word_coverage_in_box(word: Word, annotation_box: AnnotationBox) -> float:
    center_x, center_y = word.center
    return 1.0 if annotation_box.contains_point(center_x, center_y) else 0.0


def word_overlap_coverage_in_box(word: Word, annotation_box: AnnotationBox) -> float:
    if word.box.area <= 0:
        return 0.0
    overlap_area = annotation_box.overlap_area_with_box(word.box)
    return overlap_area / word.box.area


def word_non_overlapping_area(word: Word, annotation_box: AnnotationBox) -> float:
    overlap_area = annotation_box.overlap_area_with_box(word.box)
    return max(0.0, word.box.area - overlap_area)


def non_empty_words(predicted_row: PredictedRow) -> list[Word]:
    return [word for word in predicted_row.words if word.text.strip()]


def uncovered_words_against_box(
    predicted_row: PredictedRow,
    annotation_box: AnnotationBox,
) -> list[dict[str, Any]]:
    uncovered_words: list[dict[str, Any]] = []

    for word in non_empty_words(predicted_row):
        if word_coverage_in_box(word, annotation_box) >= 1.0:
            continue

        non_overlapping_area = word_non_overlapping_area(word, annotation_box)
        uncovered_words.append(
            {
                "text": word.text,
                "word_box": [round(value, 3) for value in word.box.to_list()],
                "non_overlapping_area": round(non_overlapping_area, 6),
                "non_overlapping_fraction": (
                    round(non_overlapping_area / word.box.area, 6)
                    if word.box.area > 0
                    else 0.0
                ),
                "overlap_coverage": round(
                    word_overlap_coverage_in_box(word, annotation_box), 6
                ),
            }
        )

    return uncovered_words


def single_uncovered_word_against_box(
    predicted_row: PredictedRow,
    annotation_box: AnnotationBox,
) -> dict[str, Any] | None:
    uncovered_words = uncovered_words_against_box(predicted_row, annotation_box)
    if len(uncovered_words) != 1:
        return None
    return uncovered_words[0]


def row_location_coverage(
    predicted_row: PredictedRow, annotation_box: AnnotationBox
) -> float:
    words = non_empty_words(predicted_row)
    total_words = len(words)
    if total_words == 0:
        return 0.0
    matched_words = sum(word_coverage_in_box(word, annotation_box) for word in words)
    return matched_words / total_words


def row_overlap_coverage(
    predicted_row: PredictedRow, annotation_box: AnnotationBox
) -> float:
    words = non_empty_words(predicted_row)
    total_area = sum(word.box.area for word in words)
    if total_area <= 0:
        return 0.0

    covered_area = 0.0
    for word in words:
        covered_area += annotation_box.overlap_area_with_box(word.box)
    return covered_area / total_area


def classify_row(touched_box_ids: list[str], all_word_box_ids: list[str]) -> str:
    if not touched_box_ids:
        return "no_box"
    if len(all_word_box_ids) == 1 and len(touched_box_ids) == 1:
        return "exactly_one_box"
    if len(touched_box_ids) > 1 or len(all_word_box_ids) > 1:
        return "multiple_boxes"
    return "no_box"


def best_box_detail_for_multiple_row(
    per_box_details: list[dict[str, Any]],
) -> dict[str, Any] | None:
    if not per_box_details:
        return None

    strongest_match = max(
        per_box_details,
        key=lambda item: (
            item["overlap_coverage"],
            item["coverage"],
            item["matched_words"],
            -item["first_word_index"],
            item["leading_word_count"],
            item["box_id"],
        ),
    )
    beginning_match = min(
        per_box_details,
        key=lambda item: (
            item["first_word_index"],
            -item["leading_word_count"],
            -item["coverage"],
            -item["overlap_coverage"],
            item["box_id"],
        ),
    )
    if (
        beginning_match["first_word_index"] == 0
        and (
            beginning_match["leading_word_count"]
            >= MULTI_BOX_BEGINNING_BOX_MIN_LEADING_WORDS
            or beginning_match["coverage"] >= MULTI_BOX_BEGINNING_BOX_MIN_COVERAGE
        )
        and strongest_match["overlap_coverage"]
        - beginning_match["overlap_coverage"]
        <= MULTI_BOX_BEGINNING_BOX_OVERLAP_TOLERANCE
    ):
        return beginning_match

    tied_matches = [
        item
        for item in per_box_details
        if strongest_match["overlap_coverage"] - item["overlap_coverage"]
        <= MULTI_BOX_OVERLAP_TIE_TOLERANCE
    ]
    return max(
        tied_matches,
        key=lambda item: (
            item["leading_word_count"],
            -item["first_word_index"],
            item["matched_words"],
            item["coverage"],
            item["overlap_coverage"],
            item["box_id"],
        ),
    )


def box_detail_meets_single_box_threshold(
    box_detail: dict[str, Any] | None,
) -> bool:
    if box_detail is None:
        return False
    return (
        box_detail["coverage"] >= MULTI_BOX_SINGLE_COLUMN_LOCATION_THRESHOLD
        or box_detail["overlap_coverage"] >= MULTI_BOX_SINGLE_COLUMN_OVERLAP_THRESHOLD
    )


def treat_multiple_row_as_single_box(per_box_details: list[dict[str, Any]]) -> bool:
    best_match = best_box_detail_for_multiple_row(per_box_details)
    return box_detail_meets_single_box_threshold(best_match)


def _fix_armenian_yev_at_join(prev: str, next_line: str) -> tuple[str, str]:
    """Replace ե-|վ split across a hyphenation boundary with the ligature և."""
    if prev.endswith("ե") and next_line.startswith("վ"):
        prev = prev[:-1] + "և"
        next_line = next_line[1:]
    return prev, next_line


def join_box_lines_with_hyphenation(
    line_texts: list[str],
) -> tuple[str, frozenset[int]]:
    """Join lines, stripping line-end hyphens.

    Returns (text, hyphen_join_word_indices) where hyphen_join_word_indices is
    the set of word indices (in the space-normalised result) whose text was
    formed by merging across a hyphen boundary.  Callers that only need the
    text can unpack with ``text, _ = join_box_lines_with_hyphenation(...)``.
    """
    merged_lines: list[str] = []
    words_before_current: int = 0  # word count of all finalized lines
    hyphen_join_word_indices: set[int] = set()

    for line_text in line_texts:
        normalized_line = normalize_whitespace(line_text)
        if not normalized_line:
            continue

        if merged_lines and merged_lines[-1].rstrip().endswith(
            tuple(LINE_END_HYPHENS)
        ):
            prev = merged_lines[-1].rstrip()[:-1]
            next_line = normalized_line.lstrip()

            prev, next_line = _fix_armenian_yev_at_join(prev, next_line)

            words_in_prev = len(prev.split())
            if words_in_prev > 0:
                hyphen_join_word_indices.add(words_before_current + words_in_prev - 1)

            merged_lines[-1] = prev + next_line
        else:
            if merged_lines:
                words_before_current += len(merged_lines[-1].split())
            merged_lines.append(normalized_line)

    return "\n".join(merged_lines), frozenset(hyphen_join_word_indices)


def local_boxes_share_line(left: Box, right: Box) -> bool:
    min_height = min(left.height, right.height)
    if min_height <= 0:
        return False
    vertical_overlap = interval_overlap(
        left.y_min, left.y_max, right.y_min, right.y_max
    )
    vertical_overlap_ratio = vertical_overlap / min_height
    return vertical_overlap_ratio >= BOX_LINE_VERTICAL_OVERLAP_THRESHOLD


def horizontal_overlap_ratio(left: Box, right: Box) -> float:
    min_width = min(left.width, right.width)
    if min_width <= 0:
        return 0.0
    return (
        interval_overlap(left.x_min, left.x_max, right.x_min, right.x_max)
        / min_width
    )


def row_sequence_prefix(row_id: str) -> str:
    parts = row_id.split("_", 1)
    return parts[0]


def boxes_share_reading_row(left: Box, right: Box) -> bool:
    min_height = min(left.height, right.height)
    if min_height <= 0:
        return False
    vertical_overlap = interval_overlap(
        left.y_min, left.y_max, right.y_min, right.y_max
    )
    return (vertical_overlap / min_height) >= READING_ORDER_ROW_OVERLAP_THRESHOLD


def boxes_share_reading_column(left: Box, right: Box) -> bool:
    min_width = min(left.width, right.width)
    if min_width <= 0:
        return False
    horizontal_overlap = interval_overlap(
        left.x_min, left.x_max, right.x_min, right.x_max
    )
    return (
        horizontal_overlap / min_width
    ) >= READING_ORDER_COLUMN_OVERLAP_THRESHOLD


def _group_items_spatially(
    items: Sequence[Any],
    box_getter: Any,
    primary_axis: str,
) -> list[list[Any]]:
    ltr = primary_axis == "x"
    shares_band = boxes_share_reading_column if ltr else boxes_share_reading_row
    primary_sort = (
        (lambda b: (b.x_min, b.y_min, b.x_max, b.y_max))
        if ltr
        else (lambda b: (b.y_min, b.x_min, b.y_max, b.x_max))
    )
    secondary_sort = (
        (lambda b: (b.y_min, b.x_min, b.y_max, b.x_max))
        if ltr
        else (lambda b: (b.x_min, b.x_max, b.y_min, b.y_max))
    )
    center = (
        (lambda b: (b.x_min + b.x_max) / 2.0)
        if ltr
        else (lambda b: (b.y_min + b.y_max) / 2.0)
    )

    ordered_items = sorted(items, key=lambda item: primary_sort(box_getter(item)))
    groups: list[dict[str, Any]] = []
    for item in ordered_items:
        item_box = box_getter(item)
        best_group: dict[str, Any] | None = None
        best_distance = float("inf")
        for group in groups:
            if not shares_band(group["box"], item_box):
                continue
            distance = abs(center(group["box"]) - center(item_box))
            if distance < best_distance:
                best_distance = distance
                best_group = group
        if best_group is None:
            groups.append({"items": [item], "box": item_box})
        else:
            best_group["items"].append(item)
            best_group["box"] = merge_boxes([best_group["box"], item_box])

    return [
        sorted(g["items"], key=lambda item: secondary_sort(box_getter(item)))
        for g in sorted(groups, key=lambda g: primary_sort(g["box"]))
    ]


def group_items_left_to_right_top_to_bottom(
    items: Sequence[Any], box_getter: Any
) -> list[list[Any]]:
    return _group_items_spatially(items, box_getter, "x")


def flatten_text_units(text_units: list[str]) -> str:
    flattened_units: list[str] = []
    for text_unit in text_units:
        unit_lines = split_text_lines(text_unit)
        if not unit_lines:
            continue
        text, _ = join_box_lines_with_hyphenation(unit_lines)
        flattened_units.append(text)
    return "\n".join(flattened_units)


def detect_split_line_pair(
    left_row: dict[str, Any],
    right_row: dict[str, Any],
    left_predicted_row: PredictedRow,
    right_predicted_row: PredictedRow,
    annotation_box: AnnotationBox,
) -> dict[str, Any] | None:
    left_first_word, left_last_word = edge_words_in_box(
        left_predicted_row, annotation_box
    )
    right_first_word, right_last_word = edge_words_in_box(
        right_predicted_row, annotation_box
    )
    if (
        left_first_word is None
        or left_last_word is None
        or right_first_word is None
        or right_last_word is None
    ):
        return None

    left_last_local_box = left_last_word["local_box"]
    right_first_local_box = right_first_word["local_box"]

    vertical_overlap = interval_overlap(
        left_last_local_box.y_min,
        left_last_local_box.y_max,
        right_first_local_box.y_min,
        right_first_local_box.y_max,
    )
    min_height = min(left_last_local_box.height, right_first_local_box.height)
    if min_height <= 0:
        return None

    vertical_overlap_ratio = vertical_overlap / min_height
    if vertical_overlap_ratio < SPLIT_LINE_VERTICAL_OVERLAP_THRESHOLD:
        return None

    horizontal_gap = right_first_local_box.x_min - left_last_local_box.x_max
    if horizontal_gap < (
        -SPLIT_LINE_HORIZONTAL_OVERLAP_TOLERANCE_RATIO * min_height
    ):
        return None
    if horizontal_gap > SPLIT_LINE_MAX_GAP_HEIGHT_MULTIPLIER * max(
        left_last_local_box.height,
        right_first_local_box.height,
    ):
        return None

    return {
        "box_id": annotation_box.box_id,
        "left_row_id": left_row["row_id"],
        "right_row_id": right_row["row_id"],
        "horizontal_gap": round(horizontal_gap, 6),
        "vertical_overlap_ratio": round(vertical_overlap_ratio, 6),
        "left_row_text": left_row["row_text"],
        "right_row_text": right_row["row_text"],
        "left_last_word_text": left_last_word["text"],
        "right_first_word_text": right_first_word["text"],
        "left_last_word_box": left_last_word["global_box"],
        "right_first_word_box": right_first_word["global_box"],
        "left_last_word_local_box": local_box_to_list(left_last_local_box),
        "right_first_word_local_box": local_box_to_list(right_first_local_box),
    }


def split_line_row_order_key(
    predicted_row: PredictedRow,
    annotation_box: AnnotationBox,
) -> tuple[float, float, float, float, str]:
    if not predicted_row.words:
        return (
            float("inf"),
            float("inf"),
            float("inf"),
            float("inf"),
            predicted_row.row_id,
        )
    local_bounds = box_to_local_bounds(row_box(predicted_row), annotation_box)
    return (
        local_bounds.x_min,
        local_bounds.x_max,
        local_bounds.y_min,
        local_bounds.y_max,
        predicted_row.row_id,
    )


def order_words_in_box_context(
    words: list[Word], annotation_box: AnnotationBox
) -> list[Word]:
    return sorted(
        list(words),
        key=lambda word: (
            point_to_box_local_coordinates(word.center, annotation_box)[0],
            point_to_box_local_coordinates(word.center, annotation_box)[1],
            word.box.x_min,
            word.box.y_min,
        ),
    )


def words_in_box(predicted_row: PredictedRow, annotation_box: AnnotationBox) -> list[Word]:
    words = [
        word
        for word in predicted_row.words
        if annotation_box.contains_point(word.center[0], word.center[1])
    ]
    return order_words_in_box_context(words, annotation_box)


def sorted_row_words(predicted_row: PredictedRow) -> list[Word]:
    return sorted(
        predicted_row.words,
        key=lambda word: (
            word.box.y_min,
            word.box.x_min,
            word.box.x_max,
            word.text,
        ),
    )


def normalize_whitespace(text: str) -> str:
    return " ".join(text.split())


def split_text_lines(text: str) -> list[str]:
    return [
        normalize_whitespace(line)
        for line in text.splitlines()
        if normalize_whitespace(line)
    ]