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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
#!/usr/bin/env python3

"""Evaluate CSV `group_row` predictions against annotated text boxes.

Input 1: Label Studio-style JSON annotations.
We use one text-bearing result per annotation id and convert each box from
`x, y, width, height` to `x1, y1, x2, y2`.

Input 2: CSV with predicted word boxes and `group_row`.
Rows are grouped by `group_row`, then each row is checked against the
annotation boxes.

Row classification:
- `exactly_one_box`: exactly one annotation box contains every word in the row,
  and no other annotation box significantly contains any word from that row.
  We also treat a row as `exactly_one_box` when it touches multiple boxes but
  one box covers almost all of that row, which usually means one stray word was
  pulled across columns by OCR.
- `multiple_boxes`: words from the row significantly fall into multiple
  annotation boxes.
- `no_box`: the row does not fit cleanly into any annotation box.

Coverage in this script is location-first:
- a word belongs to an annotation box when the word center lies inside that box
- row coverage is the fraction of words in the row whose centers lie inside
  a given annotation box

Label Studio box rotation is taken into account using the rotated rectangle
geometry stored in the annotation results.
"""

from __future__ import annotations

import json
import sys
from collections.abc import Callable
from pathlib import Path
from typing import Any

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

# Geometry primitives (re-exported for callers and tests)
from geometry import Box, polygon_bounds, rotated_rectangle_points

# Domain models and constants
from models import (
    AnnotationBox,
    HEADER_TITLE_LIKE_LABELS,
    IMAGE_HEADER_FILTER_LABELS,
    IMAGE_RELATED_LABELS,
    PredictedRow,
    Word,
    annotation_box_metadata,
    annotation_box_type,
    gt_box_report,
)

# Loading (re-exported for callers and tests)
from loading import (
    NON_ARMENIAN_BOX_LETTER_RATIO_THRESHOLD,
    is_watermark_row,
    load_annotation_boxes,
    load_predicted_rows,
    non_armenian_letter_ratio,
    parse_args,
)

# Spatial utilities (re-exported for callers and tests)
from spatial import row_box

# Box-grouping entry point (spatial assignment)
from group import group_words_into_regions

# Text metrics
from text_metrics import (
    CER_BUCKET_KEYS,
    HIGH_IMPACT_REGION_EXAMPLE_COUNT,
    build_cer_bucket_summary,
    cer_bucket_key,
    compute_text_metrics,
    edit_distance,
    normalize_punctuation_chars,
    safe_error_rate,
    safe_mean,
    safe_rate,
    summarize_region_example,
)

# Prediction builders
from prediction import (
    build_region_predicted_text,
    count_empty_words_in_non_empty_boxes,
)

# Report builders
from reports import (
    build_ocr_region_reports,
    build_region_summary,
    filtered_box_report,
)


def report_excluded_labels() -> dict[str, list[str]]:
    return {
        "image_related_boxes": sorted(IMAGE_RELATED_LABELS),
        "header_title_like_boxes": sorted(HEADER_TITLE_LIKE_LABELS),
        "image_header_boxes": sorted(IMAGE_HEADER_FILTER_LABELS),
    }


FILTER_NON_ARMENIAN = "non-armenian"
FILTER_LABEL_GROUPS: dict[str, frozenset[str]] = {
    "graphics": frozenset({"Graphics"}),
    "photo": frozenset({"Photo"}),
    "image": IMAGE_RELATED_LABELS,
    "header": HEADER_TITLE_LIKE_LABELS,
    "image-header": IMAGE_HEADER_FILTER_LABELS,
}
FILTER_ALIASES = {
    "nonarmenian": FILTER_NON_ARMENIAN,
    "non-armenian": FILTER_NON_ARMENIAN,
    "non_armenian": FILTER_NON_ARMENIAN,
    "latin": FILTER_NON_ARMENIAN,
    "latin-cyrillic": FILTER_NON_ARMENIAN,
    "latin_or_cyrillic": FILTER_NON_ARMENIAN,
    "image-header": "image-header",
    "image_header": "image-header",
    "imageheader": "image-header",
    "image-related": "image",
    "image_related": "image",
    "images": "image",
    "headers": "header",
}
AVAILABLE_FILTERS = (FILTER_NON_ARMENIAN, *FILTER_LABEL_GROUPS.keys())


def parse_filter_names(
    raw_filters: str | list[str] | tuple[str, ...] | None,
) -> tuple[str, ...]:
    if raw_filters is None:
        return ()

    tokens: list[str] = []
    if isinstance(raw_filters, str):
        tokens = raw_filters.split(",")
    else:
        for raw_filter in raw_filters:
            tokens.extend(str(raw_filter).split(","))

    selected_filters: list[str] = []
    seen_filters: set[str] = set()
    for token in tokens:
        normalized = token.strip().lower().replace(" ", "-")
        if not normalized:
            continue
        canonical = FILTER_ALIASES.get(normalized, normalized)
        if canonical not in AVAILABLE_FILTERS:
            available = ", ".join(AVAILABLE_FILTERS)
            raise ValueError(
                f"Unknown filter '{token}'. Available filters: {available}"
            )
        if canonical not in seen_filters:
            selected_filters.append(canonical)
            seen_filters.add(canonical)
    return tuple(selected_filters)


def labels_for_filters(filter_names: tuple[str, ...]) -> frozenset[str]:
    labels: set[str] = set()
    for filter_name in filter_names:
        labels.update(FILTER_LABEL_GROUPS.get(filter_name, ()))
    return frozenset(labels)


def filter_matches_for_box(
    annotation_box: AnnotationBox,
    filter_names: tuple[str, ...],
) -> list[str]:
    matches: list[str] = []
    box_labels = set(annotation_box.labels)
    for filter_name in filter_names:
        if (
            filter_name == FILTER_NON_ARMENIAN
            and annotation_box.excluded_as_non_armenian_text
        ):
            matches.append(filter_name)
            continue
        label_group = FILTER_LABEL_GROUPS.get(filter_name)
        if label_group and box_labels & label_group:
            matches.append(filter_name)
    return matches


def should_exclude_box_for_filters(
    filter_names: tuple[str, ...],
) -> Callable[[AnnotationBox], bool] | None:
    if not filter_names:
        return None

    def should_exclude_box(annotation_box: AnnotationBox) -> bool:
        return bool(filter_matches_for_box(annotation_box, filter_names))

    return should_exclude_box


def filtered_region_box_report(
    annotation_box: AnnotationBox,
    filter_names: tuple[str, ...],
) -> dict[str, Any]:
    report = filtered_box_report(annotation_box)
    report["matched_filters"] = filter_matches_for_box(annotation_box, filter_names)
    report["letter_count"] = annotation_box.letter_count
    report["latin_or_cyrillic_letter_count"] = (
        annotation_box.latin_or_cyrillic_letter_count
    )
    report["non_armenian_letter_ratio"] = round(
        annotation_box.non_armenian_letter_ratio,
        6,
    )
    report["non_armenian_letter_percentage"] = round(
        annotation_box.non_armenian_letter_ratio * 100,
        6,
    )
    return report


def build_region_filter_report(
    annotation_boxes: list[AnnotationBox],
    filter_names: tuple[str, ...],
) -> dict[str, Any]:
    text_boxes = [box for box in annotation_boxes if box.has_transcription]
    excluded_boxes = [
        box for box in text_boxes if filter_matches_for_box(box, filter_names)
    ]
    report = {
        "filters": list(filter_names),
        "text_box_count": len(text_boxes),
        "excluded_box_count": len(excluded_boxes),
        "excluded_box_rate": safe_rate(len(excluded_boxes), len(text_boxes)),
        "included_box_count": len(text_boxes) - len(excluded_boxes),
        "excluded_boxes": [
            filtered_region_box_report(box, filter_names) for box in excluded_boxes
        ],
    }
    if FILTER_NON_ARMENIAN in filter_names:
        report["threshold"] = NON_ARMENIAN_BOX_LETTER_RATIO_THRESHOLD
    label_filters = labels_for_filters(filter_names)
    if label_filters:
        report["labels"] = sorted(label_filters)
    return report


def summarize_region_filter_report(filter_report: dict[str, Any]) -> dict[str, Any]:
    return {
        key: value
        for key, value in filter_report.items()
        if key != "excluded_boxes"
    }


def nonzero_cer_records(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
    return [
        record
        for record in records
        if (record.get("text_metrics") or {}).get("cer", 0.0) != 0.0
    ]


def select_no_box_failure_examples(
    rows: list[dict[str, Any]],
    example_count: int,
) -> list[dict[str, Any]]:
    non_empty_rows = [row for row in rows if row["row_text"].strip()]
    if non_empty_rows:
        return non_empty_rows[:example_count]
    return rows[:1]


def build_failure_examples(
    details: list[dict[str, Any]],
    ocr_regions: list[dict[str, Any]],
    example_count: int,
    split_line_groups: list[dict[str, Any]] | None = None,
) -> dict[str, list[dict[str, Any]]]:
    def simplify(row: dict[str, Any]) -> dict[str, Any]:
        simplified = {
            "row_id": row["row_id"],
            "row_text": row["row_text"],
            "dominant_box_id": row["dominant_box_id"],
            "dominant_coverage": row["dominant_coverage"],
            "touched_box_ids": row["touched_box_ids"],
            "candidate_boxes": row["per_box_coverages"][:3],
        }
        if row["status"] == "no_box":
            simplified["single_uncovered_word_against_dominant_box"] = row[
                "single_uncovered_word_against_dominant_box"
            ]
            simplified["uncovered_words_against_dominant_box"] = row[
                "uncovered_words_against_dominant_box"
            ]
        return simplified

    multiple_rows = [row for row in details if row["status"] == "multiple_boxes"]
    no_box_rows = [row for row in details if row["status"] == "no_box"]
    detected_empty_rows = [row for row in details if row.get("is_detected_empty")]
    multiple_examples = sorted(
        multiple_rows,
        key=lambda row: (
            -len(row["touched_box_ids"]),
            row["dominant_coverage"],
            row["row_id"],
        ),
    )[:example_count]
    no_box_examples = select_no_box_failure_examples(no_box_rows, example_count)
    high_impact_examples = sorted(
        [
            region
            for region in ocr_regions
            if region["text_metrics"]["char_edit_distance"] > 0
        ],
        key=lambda region: (
            -region["text_metrics"]["char_edit_distance"],
            region["region_id"],
        ),
    )[:HIGH_IMPACT_REGION_EXAMPLE_COUNT]
    normal_single_box_error_examples = sorted(
        [
            region
            for region in ocr_regions
            if (
                region.get("normal_single_box_region")
                and region["text_metrics"]["char_edit_distance"] > 0
            )
        ],
        key=lambda region: (
            -region["text_metrics"]["cer"],
            -region["text_metrics"]["char_edit_distance"],
            region["region_id"],
        ),
    )[:example_count]

    return {
        "multiple_boxes": [simplify(row) for row in multiple_examples],
        "no_box": [simplify(row) for row in no_box_examples],
        "detected_empty": [simplify(row) for row in detected_empty_rows[:example_count]],
        "split_line": (
            [] if split_line_groups is None else split_line_groups[:example_count]
        ),
        "high_impact_regions": [
            summarize_region_example(region, include_error_stats=True)
            for region in high_impact_examples
        ],
        "normal_single_box_region_errors": [
            summarize_region_example(region, include_error_stats=True)
            for region in normal_single_box_error_examples
        ],
    }


def evaluate_rows(
    predicted_rows: list[PredictedRow],
    annotation_boxes: list[AnnotationBox],
    coverage_threshold: float,
    failure_example_count: int,
    hide_zero_cer_details: bool = True,
    filters: str | list[str] | tuple[str, ...] | None = None,
    unit_level: str = "word",
) -> dict[str, Any]:
    filter_names = parse_filter_names(filters)
    should_exclude_box = should_exclude_box_for_filters(filter_names)

    grouping = group_words_into_regions(
        predicted_rows=predicted_rows,
        annotation_boxes=annotation_boxes,
        coverage_threshold=coverage_threshold,
        unit_level=unit_level,
    )
    details = grouping["assignments"]
    ignored_rows = grouping["watermark_rows"]
    split_line_groups = grouping["split_line_groups"]
    best_coverages = grouping["best_coverages"]
    counts = grouping["counts"]

    total_rows = len(details)
    predicted_rows_by_id = {row.row_id: row for row in predicted_rows}
    total_detected_word_boxes = sum(len(row.words) for row in predicted_rows)
    missing_text_boxes = count_empty_words_in_non_empty_boxes(
        predicted_rows,
        annotation_boxes,
    )
    gt_text_boxes = [box for box in annotation_boxes if box.has_transcription]
    gt_box_count = len(gt_text_boxes)
    gt_char_count = sum(len(box.text) for box in gt_text_boxes)

    ocr_regions, ocr_region_summary = build_ocr_region_reports(
        details=details,
        annotation_boxes=annotation_boxes,
        predicted_rows_by_id=predicted_rows_by_id,
        should_exclude_box=should_exclude_box,
    )
    filter_report = (
        build_region_filter_report(annotation_boxes, filter_names)
        if filter_names
        else None
    )
    summary = {
        "unit_level": unit_level,
        "total_rows": total_rows,
        "ignored_watermark_rows": len(ignored_rows),
        "exactly_one_box": counts["exactly_one_box"],
        "exactly_one_box_rate": safe_rate(counts["exactly_one_box"], total_rows),
        "multiple_boxes": counts["multiple_boxes"],
        "multiple_boxes_rate": safe_rate(counts["multiple_boxes"], total_rows),
        "no_box": counts["no_box"],
        "no_box_rate": safe_rate(counts["no_box"], total_rows),
        "detected_empty": counts["detected_empty"],
        "split_line": len(split_line_groups),
        "split_line_rate": safe_rate(len(split_line_groups), total_rows),
        "split_line_rows": counts["split_line"],
        "split_line_rows_rate": safe_rate(counts["split_line"], total_rows),
        "mean_best_coverage": safe_mean(best_coverages),
        "gt_box_count": gt_box_count,
        "gt_char_count": gt_char_count,
        "ocr_region_count": ocr_region_summary["ocr_region_count"],
        "multibox_region_count": ocr_region_summary["multibox_region_count"],
        "ocr_region_mean_cer": ocr_region_summary["mean_cer"],
        "ocr_region_gt_char_count": ocr_region_summary["gt_char_count"],
        "ocr_region_char_edit_distance": ocr_region_summary["char_edit_distance"],
        "ocr_region_char_edit_distance_lowercase": ocr_region_summary["char_edit_distance_lowercase"],
        "ocr_region_cer": ocr_region_summary["cer"],
        "ocr_region_cer_lowercase": ocr_region_summary["cer_lowercase"],
        "ocr_region_cer_buckets": ocr_region_summary["cer_buckets"],
        "normal_single_box_region": ocr_region_summary["normal_single_box_region"],
        "missing_text_boxes": missing_text_boxes,
        "total_detected_word_boxes": total_detected_word_boxes,
        "missing_text_box_rate": safe_rate(
            missing_text_boxes,
            total_detected_word_boxes,
        ),
    }
    if filter_report is not None:
        summary["filter"] = summarize_region_filter_report(filter_report)

    failure_examples = build_failure_examples(
        details,
        ocr_regions,
        failure_example_count,
        split_line_groups,
    )
    report = {
        "summary": summary,
        "ocr_regions": (
            nonzero_cer_records(ocr_regions) if hide_zero_cer_details else ocr_regions
        ),
        "failure_examples": failure_examples,
        "split_line_groups": split_line_groups,
        "ignored_rows": ignored_rows,
        "rows": details,
        "excluded_labels": report_excluded_labels(),
    }
    if filter_report is not None:
        report["filter"] = filter_report
        report["filtered_text_boxes"] = filter_report["excluded_boxes"]
    return report


def main() -> None:
    args = parse_args()
    annotation_boxes = load_annotation_boxes(args.annotations_json)
    predicted_rows = load_predicted_rows(args.predictions_csv, unit_level=args.unit_level)
    try:
        filters = parse_filter_names(args.filters)
    except ValueError as error:
        raise SystemExit(str(error)) from error
    report = evaluate_rows(
        predicted_rows=predicted_rows,
        annotation_boxes=annotation_boxes,
        coverage_threshold=args.coverage_threshold,
        failure_example_count=args.failure_example_count,
        hide_zero_cer_details=True,
        filters=filters,
        unit_level=args.unit_level,
    )

    print(
        json.dumps(
            {
                "summary": report["summary"],
                "ocr_regions": report["ocr_regions"],
            },
            ensure_ascii=False,
            indent=2,
        )
    )

    if args.output:
        args.output.write_text(
            json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8"
        )


if __name__ == "__main__":
    main()