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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
"""Load annotation boxes and predicted rows from disk, and detect watermark rows."""

from __future__ import annotations

import argparse
import csv
import json
import sys
import unicodedata
from collections import Counter
from pathlib import Path
from typing import Any

from geometry import Box, rotated_rectangle_points, polygon_bounds
from models import (
    Word,
    AnnotationBox,
    PredictedRow,
    decomposable_container_box_ids,
    filter_redundant_annotation_boxes,
)


WATERMARK_PATTERNS = (
    {
        "tokens": ("national", "library", "of", "armenia", "ocr", "by", "portmind"),
        "token_counts": Counter(
            ("national", "library", "of", "armenia", "ocr", "by", "portmind")
        ),
        "distinctive_tokens": {"national", "library", "armenia", "ocr", "portmind"},
        "normalized_text": "nationallibraryofarmeniaocrbyportmind",
        "max_edit_distance": 2,
        "min_distinctive_token_matches": 3,
        "min_token_count": 6,
    },
    {
        "tokens": ("armenia", "ocr", "by", "portmind"),
        "token_counts": Counter(("armenia", "ocr", "by", "portmind")),
        "distinctive_tokens": {"armenia", "ocr", "portmind"},
        "normalized_text": "armeniaocrbyportmind",
        "max_edit_distance": 2,
        "min_distinctive_token_matches": 2,
        "min_token_count": 4,
    },
    {
        "tokens": ("national", "library", "of", "armenia"),
        "token_counts": Counter(("national", "library", "of", "armenia")),
        "distinctive_tokens": {"national", "library", "armenia"},
        "normalized_text": "nationallibraryofarmenia",
        "max_edit_distance": 2,
        "min_distinctive_token_matches": 2,
        "min_token_count": 3,
    },
)
WATERMARK_TOKEN_VOCABULARY = frozenset(
    token for pattern in WATERMARK_PATTERNS for token in pattern["tokens"]
)
NON_ARMENIAN_BOX_LETTER_RATIO_THRESHOLD = 0.9


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--annotations-json",
        type=Path,
        required=True,
        help="Path to the annotation JSON file.",
    )
    parser.add_argument(
        "--predictions-csv",
        type=Path,
        required=True,
        help="Path to the predicted word-box CSV file.",
    )
    parser.add_argument(
        "--coverage-threshold",
        type=float,
        default=1.0,
        help="Minimum fraction of words in a row that must fit a box for a full match.",
    )
    parser.add_argument(
        "--failure-example-count",
        type=int,
        default=5,
        help="Number of example failures to include per failure type in the report.",
    )
    parser.add_argument(
        "--filter",
        dest="filters",
        help=(
            "Optional comma-separated region filters, e.g. "
            "`non-armenian`, `graphics`, or `non-armenian,graphics`."
        ),
    )
    parser.add_argument(
        "--unit-level",
        dest="unit_level",
        choices=["word", "line"],
        default="word",
        help="Granularity of predicted rows: 'word' or 'line'.",
    )
    parser.add_argument(
        "--output",
        type=Path,
        help="Optional JSON path for the full report.",
    )
    return parser.parse_args()


def load_json(path: Path) -> Any:
    with path.open("r", encoding="utf-8") as handle:
        return json.load(handle)


def pick_geometry_result(results: list[dict[str, Any]]) -> dict[str, Any] | None:
    candidates = [
        result
        for result in results
        if {"x", "y", "width", "height"} <= set(result.get("value", {}).keys())
    ]
    if not candidates:
        return None

    def priority(result: dict[str, Any]) -> tuple[int, str]:
        from_name = result.get("from_name", "")
        if from_name == "label":
            return (0, from_name)
        return (1, from_name)

    return sorted(candidates, key=priority)[0]


def pick_transcription_result(results: list[dict[str, Any]]) -> dict[str, Any] | None:
    candidates = [
        result
        for result in results
        if result.get("from_name") == "transcription"
        and "text" in result.get("value", {})
    ]
    if not candidates:
        return None
    return candidates[0]


def text_from_result(result: dict[str, Any]) -> str:
    raw_text = result.get("value", {}).get("text", [])
    if isinstance(raw_text, list):
        return "\n".join(str(item) for item in raw_text)
    if raw_text is None:
        return ""
    return str(raw_text)


def parent_box_id_from_results(results: list[dict[str, Any]]) -> str | None:
    for result in results:
        if result.get("from_name") != "parent_id":
            continue
        raw_text = result.get("value", {}).get("text")
        if isinstance(raw_text, list) and raw_text:
            return str(raw_text[0])
    return None


def reading_order_from_results(results: list[dict[str, Any]]) -> int | None:
    for result in results:
        if result.get("from_name") != "reading_order":
            continue
        raw_text = result.get("value", {}).get("text")
        if isinstance(raw_text, list) and raw_text:
            try:
                return int(raw_text[0])
            except (TypeError, ValueError):
                return None
    return None


def labels_from_result(result: dict[str, Any]) -> tuple[str, ...]:
    raw_labels = result.get("value", {}).get("rectanglelabels", [])
    if not isinstance(raw_labels, list):
        return ()
    return tuple(str(label) for label in raw_labels if str(label).strip())


def letter_script(character: str) -> str | None:
    if not unicodedata.category(character).startswith("L"):
        return None
    character_name = unicodedata.name(character, "")
    if character_name.startswith("ARMENIAN"):
        return "armenian"
    if character_name.startswith("LATIN"):
        return "latin"
    if character_name.startswith("CYRILLIC"):
        return "cyrillic"
    return "other_letter"


def count_text_letter_scripts(text: str) -> Counter[str]:
    return Counter(
        script
        for character in text
        if (script := letter_script(character)) is not None
    )


def non_armenian_letter_ratio(text: str) -> tuple[int, int, float]:
    script_counts = count_text_letter_scripts(text)
    letter_count = sum(script_counts.values())
    latin_or_cyrillic_letter_count = (
        script_counts["latin"] + script_counts["cyrillic"]
    )
    ratio = (
        latin_or_cyrillic_letter_count / letter_count if letter_count else 0.0
    )
    return letter_count, latin_or_cyrillic_letter_count, ratio


def load_annotation_boxes(path: Path) -> list[AnnotationBox]:
    data = load_json(path)
    grouped_results: dict[str, list[dict[str, Any]]] = {}

    for annotation in data.get("annotations", []):
        for result in annotation.get("result", []):
            result_id = result.get("id")
            if result_id is None:
                continue
            grouped_results.setdefault(str(result_id), []).append(result)

    boxes: list[AnnotationBox] = []
    for box_id, results in grouped_results.items():
        transcription_result = pick_transcription_result(results)
        geometry_result = pick_geometry_result(results)
        if geometry_result is None:
            continue

        geometry = geometry_result["value"]
        x = float(geometry["x"])
        y = float(geometry["y"])
        width = float(geometry["width"])
        height = float(geometry["height"])
        rotation = float(geometry.get("rotation", 0.0))
        rect = Box(
            x_min=x,
            y_min=y,
            x_max=x + width,
            y_max=y + height,
        )
        polygon = rotated_rectangle_points(x, y, width, height, rotation)
        text = (
            text_from_result(transcription_result)
            if transcription_result is not None
            else ""
        )
        labels = labels_from_result(geometry_result)
        if "Rule" in labels:
            continue
        letter_count, latin_or_cyrillic_count, ratio = non_armenian_letter_ratio(
            text
        )
        boxes.append(
            AnnotationBox(
                box_id=box_id,
                rect=rect,
                text=text,
                has_transcription=transcription_result is not None,
                rotation=rotation,
                polygon=polygon,
                bounds=polygon_bounds(polygon),
                labels=labels,
                letter_count=letter_count,
                latin_or_cyrillic_letter_count=latin_or_cyrillic_count,
                non_armenian_letter_ratio=ratio,
                excluded_as_non_armenian_text=(
                    ratio > NON_ARMENIAN_BOX_LETTER_RATIO_THRESHOLD
                ),
                parent_box_id=parent_box_id_from_results(results),
                reading_order=reading_order_from_results(results),
            )
        )

    decomposable_ids = decomposable_container_box_ids(boxes)
    boxes = [box for box in boxes if box.box_id not in decomposable_ids]

    return sorted(
        filter_redundant_annotation_boxes(boxes),
        key=lambda item: (item.bounds.y_min, item.bounds.x_min, item.box_id),
    )


def load_predicted_rows(path: Path, unit_level: str = "word") -> list[PredictedRow]:
    """Load predicted word boxes from an evaluation CSV, grouped into rows.

    For ``unit_level="line"``, rows sharing the same ``group_row`` value are
    assembled into one PredictedRow (a full text line built from its
    constituent words) — the CSV's own row grouping is authoritative.

    For ``unit_level="word"`` (the default), ``group_row`` is ignored and
    every CSV row becomes its own single-word PredictedRow. This matters for
    CSVs where multiple individual word boxes share a ``group_row`` because
    an upstream step assigned them to the same visual line (e.g. raw
    box_grouping/data CSVs): without this, a word-level evaluation would
    incorrectly treat that whole line as one atomic unit instead of scoring
    each word independently against the ground truth.
    """
    grouped_words: dict[str, list[Word]] = {}

    with path.open("r", encoding="utf-8", newline="") as handle:
        reader = csv.DictReader(handle)
        for index, row in enumerate(reader):
            row_id = str(index) if unit_level == "word" else row["group_row"]
            word = Word(
                box=Box(
                    x_min=float(row["x1"]),
                    y_min=float(row["y1"]),
                    x_max=float(row["x2"]),
                    y_max=float(row["y2"]),
                ),
                text=row.get("text", ""),
            )
            grouped_words.setdefault(row_id, []).append(word)

    return [
        PredictedRow(
            row_id=row_id,
            words=sorted(words, key=lambda w: (w.box.x_min, w.box.y_min)),
        )
        for row_id, words in grouped_words.items()
    ]


def normalize_token(text: str) -> str:
    return "".join(character.lower() for character in text if character.isalnum())


def normalized_token_segments(text: str) -> list[str]:
    segments: list[str] = []
    current_characters: list[str] = []
    for character in text:
        if character.isalnum():
            current_characters.append(character)
            continue
        if current_characters:
            normalized = normalize_token("".join(current_characters))
            if normalized:
                segments.append(normalized)
            current_characters = []
    if current_characters:
        normalized = normalize_token("".join(current_characters))
        if normalized:
            segments.append(normalized)
    return segments


def matches_watermark_pattern(
    normalized_tokens: list[str], pattern: dict[str, Any]
) -> bool:
    # Deferred import: text_metrics lives in evaluation/, not box_grouping/.
    # Avoids a top-level cycle (loading → text_metrics → spatial → loading).
    _evaluation = str(Path(__file__).resolve().parent.parent / "evaluation")
    if _evaluation not in sys.path:
        sys.path.insert(0, _evaluation)
    from text_metrics import edit_distance

    token_counts = Counter(normalized_tokens)
    distinctive_token_matches = len(
        set(token_counts) & pattern["distinctive_tokens"]
    )
    if distinctive_token_matches < pattern["min_distinctive_token_matches"]:
        return False

    if len(normalized_tokens) >= pattern["min_token_count"] and all(
        count <= pattern["token_counts"].get(token, 0)
        for token, count in token_counts.items()
    ):
        return True

    normalized_text = "".join(normalized_tokens)
    if (
        abs(len(normalized_text) - len(pattern["normalized_text"]))
        > pattern["max_edit_distance"]
    ):
        return False

    return (
        edit_distance(normalized_text, pattern["normalized_text"])
        <= pattern["max_edit_distance"]
    )


def normalized_row_tokens(predicted_row: PredictedRow) -> list[str]:
    normalized_tokens: list[str] = []
    for word in predicted_row.words:
        normalized_tokens.extend(normalized_token_segments(word.text))
    return normalized_tokens


def is_watermark_row(predicted_row: PredictedRow) -> bool:
    normalized_tokens = normalized_row_tokens(predicted_row)
    if not normalized_tokens:
        return False
    return any(
        matches_watermark_pattern(normalized_tokens, pattern)
        for pattern in WATERMARK_PATTERNS
    )


def matches_watermark_subsequence(normalized_tokens: list[str]) -> bool:
    if not normalized_tokens:
        return False
    token_count = len(normalized_tokens)
    for pattern in WATERMARK_PATTERNS:
        pattern_tokens = pattern["tokens"]
        if token_count > len(pattern_tokens):
            continue
        for start_index in range(len(pattern_tokens) - token_count + 1):
            if (
                tuple(normalized_tokens)
                == pattern_tokens[start_index : start_index + token_count]
            ):
                return True
    return False


def watermark_row_ids(
    predicted_rows: list[PredictedRow],
    local_boxes_share_line_fn: Any,
) -> set[str]:
    """Return the set of row_ids that are part of a watermark (direct or fragmented)."""
    row_details = [
        {
            "predicted_row": predicted_row,
            "row_box": _row_box(predicted_row),
            "normalized_tokens": normalized_row_tokens(predicted_row),
            "is_direct_watermark": is_watermark_row(predicted_row),
        }
        for predicted_row in predicted_rows
    ]
    ignored_row_ids = {
        detail["predicted_row"].row_id
        for detail in row_details
        if detail["is_direct_watermark"]
    }
    candidate_indexes = [
        index
        for index, detail in enumerate(row_details)
        if detail["is_direct_watermark"]
        or (
            detail["normalized_tokens"]
            and all(
                token in WATERMARK_TOKEN_VOCABULARY
                for token in detail["normalized_tokens"]
            )
        )
    ]

    visited_indexes: set[int] = set()
    for candidate_index in candidate_indexes:
        if candidate_index in visited_indexes:
            continue

        component_indexes: list[int] = []
        pending_indexes = [candidate_index]
        visited_indexes.add(candidate_index)
        while pending_indexes:
            current_index = pending_indexes.pop()
            component_indexes.append(current_index)
            current_box = row_details[current_index]["row_box"]
            for other_index in candidate_indexes:
                if other_index in visited_indexes:
                    continue
                if not local_boxes_share_line_fn(
                    current_box, row_details[other_index]["row_box"]
                ):
                    continue
                visited_indexes.add(other_index)
                pending_indexes.append(other_index)

        if len(component_indexes) < 2:
            continue

        ordered_component_indexes = sorted(
            component_indexes,
            key=lambda i: (
                row_details[i]["row_box"].x_min,
                row_details[i]["row_box"].y_min,
                row_details[i]["predicted_row"].row_id,
            ),
        )
        combined_tokens: list[str] = []
        for component_index in ordered_component_indexes:
            combined_tokens.extend(row_details[component_index]["normalized_tokens"])

        if any(
            matches_watermark_pattern(combined_tokens, pattern)
            for pattern in WATERMARK_PATTERNS
        ) or matches_watermark_subsequence(combined_tokens):
            ignored_row_ids.update(
                row_details[component_index]["predicted_row"].row_id
                for component_index in component_indexes
            )

    return ignored_row_ids


def _row_box(predicted_row: PredictedRow) -> Box:
    """Compute the bounding box of a predicted row without importing from spatial."""
    return Box(
        x_min=min(word.box.x_min for word in predicted_row.words),
        y_min=min(word.box.y_min for word in predicted_row.words),
        x_max=max(word.box.x_max for word in predicted_row.words),
        y_max=max(word.box.y_max for word in predicted_row.words),
    )