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

"""Aggregate row-grouping accuracy across matched CSV/JSON page pairs."""

from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any

from measure_accuracy import (
    HIGH_IMPACT_REGION_EXAMPLE_COUNT,
    build_region_summary,
    evaluate_rows,
    load_annotation_boxes,
    load_predicted_rows,
    parse_filter_names,
    report_excluded_labels,
    safe_mean,
    safe_rate,
    select_no_box_failure_examples,
    summarize_region_example,
)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--data-dir",
        type=Path,
        help="Directory containing both prediction CSVs and annotation JSONs.",
    )
    parser.add_argument(
        "--predictions-dir",
        type=Path,
        dest="predictions_dir",
        help="Directory containing prediction CSVs (overrides --data-dir for CSVs).",
    )
    parser.add_argument(
        "--annotations-dir",
        type=Path,
        dest="annotations_dir",
        help="Directory containing annotation JSONs (overrides --data-dir for JSONs).",
    )
    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 aggregate failure examples to keep per failure type.",
    )
    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 aggregated report.",
    )
    return parser.parse_args()


def discover_pairs(
    predictions_dir: Path,
    annotations_dir: Path,
    *,
    partial: bool = False,
) -> list[tuple[str, Path, Path]]:
    csv_by_stem = {path.stem: path for path in sorted(predictions_dir.glob("*.csv"))}
    json_by_stem = {
        "_".join(path.relative_to(annotations_dir).with_suffix("").parts): path
        for path in sorted(annotations_dir.rglob("*.json"))
        if not path.stem.endswith("_result")
    }

    missing_csv = sorted(json_by_stem.keys() - csv_by_stem.keys())
    missing_json = sorted(csv_by_stem.keys() - json_by_stem.keys())
    problems: list[str] = []
    if missing_csv:
        if partial:
            print(
                f"--partial: skipping {len(missing_csv)} page(s) with no prediction CSV",
                flush=True,
            )
        else:
            problems.append(f"missing CSV for: {', '.join(missing_csv)}")
    if missing_json:
        problems.append(f"missing JSON for: {', '.join(missing_json)}")
    if problems:
        raise SystemExit(
            f"Unmatched files (CSVs in {predictions_dir}, JSONs in {annotations_dir}): "
            f"{'; '.join(problems)}"
        )

    pair_names = sorted(csv_by_stem.keys() & json_by_stem.keys())
    if not pair_names:
        raise SystemExit(
            f"No matched CSV/JSON pairs found "
            f"(CSVs in {predictions_dir}, JSONs in {annotations_dir})"
        )

    return [(name, csv_by_stem[name], json_by_stem[name]) for name in pair_names]


def enrich_record(record: dict[str, Any], *, page_name: str, predictions_csv: Path, annotations_json: Path) -> dict[str, Any]:
    enriched = dict(record)
    enriched["page_name"] = page_name
    enriched["predictions_csv"] = str(predictions_csv)
    enriched["annotations_json"] = str(annotations_json)
    return enriched


def empty_filter_accumulator(page_filter: dict[str, Any]) -> dict[str, Any]:
    return {
        "filters": page_filter.get("filters", []),
        "text_box_count": 0,
        "excluded_box_count": 0,
        "included_box_count": 0,
        "threshold": page_filter.get("threshold"),
        "labels": page_filter.get("labels"),
    }


def update_filter_accumulator(
    accumulator: dict[str, Any],
    page_filter: dict[str, Any],
) -> None:
    accumulator["text_box_count"] += page_filter.get("text_box_count", 0)
    accumulator["excluded_box_count"] += page_filter.get("excluded_box_count", 0)
    accumulator["included_box_count"] += page_filter.get("included_box_count", 0)
    if accumulator["threshold"] is None and "threshold" in page_filter:
        accumulator["threshold"] = page_filter["threshold"]
    if accumulator["labels"] is None and "labels" in page_filter:
        accumulator["labels"] = page_filter["labels"]


def summarize_filter_accumulator(accumulator: dict[str, Any]) -> dict[str, Any]:
    summary = {
        "filters": accumulator["filters"],
        "text_box_count": accumulator["text_box_count"],
        "excluded_box_count": accumulator["excluded_box_count"],
        "excluded_box_rate": safe_rate(
            accumulator["excluded_box_count"],
            accumulator["text_box_count"],
        ),
        "included_box_count": accumulator["included_box_count"],
    }
    if accumulator["threshold"] is not None:
        summary["threshold"] = accumulator["threshold"]
    if accumulator["labels"] is not None:
        summary["labels"] = accumulator["labels"]
    return summary


def build_aggregate_failure_examples(
    rows: list[dict[str, Any]],
    split_line_groups: list[dict[str, Any]],
    ocr_regions: list[dict[str, Any]],
    example_count: int,
) -> dict[str, list[dict[str, Any]]]:
    def simplify(row: dict[str, Any]) -> dict[str, Any]:
        simplified = {
            "page_name": row["page_name"],
            "predictions_csv": row["predictions_csv"],
            "annotations_json": row["annotations_json"],
            "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 rows if row["status"] == "multiple_boxes"]
    no_box_rows = [row for row in rows if row["status"] == "no_box"]
    detected_empty_rows = [row for row in rows if row.get("is_detected_empty")]
    multiple_examples = sorted(
        multiple_rows,
        key=lambda row: (
            -len(row["touched_box_ids"]),
            row["dominant_coverage"],
            row["page_name"],
            row["row_id"],
        ),
    )[:example_count]
    no_box_examples = select_no_box_failure_examples(no_box_rows, example_count)
    split_line_examples = sorted(
        split_line_groups,
        key=lambda group: (group["page_name"], group["box_id"], group["row_ids"][0]),
    )
    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["page_name"],
            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["page_name"],
            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": split_line_examples,
        "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 aggregate_reports(
    page_reports: list[dict[str, Any]],
    coverage_threshold: float,
    failure_example_count: int,
    unit_level: str = "word",
) -> dict[str, Any]:
    all_rows: list[dict[str, Any]] = []
    all_ignored_rows: list[dict[str, Any]] = []
    all_split_line_groups: list[dict[str, Any]] = []
    all_filtered_text_boxes: list[dict[str, Any]] = []
    all_ocr_regions: list[dict[str, Any]] = []
    best_coverages: list[float] = []

    total_rows = 0
    ignored_watermark_rows = 0
    exactly_one_box = 0
    multiple_boxes = 0
    no_box = 0
    detected_empty = 0
    split_line = 0
    split_line_rows = 0
    missing_text_boxes = 0
    total_detected_word_boxes = 0
    total_gt_box_count = 0
    total_gt_char_count = 0
    filter_accumulator: dict[str, Any] | None = None

    pages: list[dict[str, Any]] = []

    for page in page_reports:
        name = page["page_name"]
        predictions_csv = page["predictions_csv"]
        annotations_json = page["annotations_json"]
        report = page["report"]
        summary = report["summary"]

        total_rows += summary["total_rows"]
        ignored_watermark_rows += summary["ignored_watermark_rows"]
        exactly_one_box += summary["exactly_one_box"]
        multiple_boxes += summary["multiple_boxes"]
        no_box += summary["no_box"]
        detected_empty += summary.get("detected_empty", 0)
        split_line += summary.get("split_line", 0)
        split_line_rows += summary.get("split_line_rows", 0)
        missing_text_boxes += summary.get("missing_text_boxes", 0)
        total_detected_word_boxes += summary.get("total_detected_word_boxes", 0)
        total_gt_box_count += summary.get("gt_box_count", 0)
        total_gt_char_count += summary.get("gt_char_count", 0)
        page_filter = summary.get("filter")
        if page_filter is not None:
            if filter_accumulator is None:
                filter_accumulator = empty_filter_accumulator(page_filter)
            update_filter_accumulator(filter_accumulator, page_filter)

        ignored_rows = [
            enrich_record(
                row,
                page_name=name,
                predictions_csv=predictions_csv,
                annotations_json=annotations_json,
            )
            for row in report["ignored_rows"]
        ]
        split_line_groups = [
            enrich_record(
                group,
                page_name=name,
                predictions_csv=predictions_csv,
                annotations_json=annotations_json,
            )
            for group in report.get("split_line_groups", [])
        ]
        filtered_text_boxes = [
            enrich_record(
                box,
                page_name=name,
                predictions_csv=predictions_csv,
                annotations_json=annotations_json,
            )
            for box in report.get("filtered_text_boxes", [])
        ]

        all_rows.extend(
            enrich_record(row, page_name=name, predictions_csv=predictions_csv, annotations_json=annotations_json)
            for row in report["rows"]
        )
        all_ignored_rows.extend(ignored_rows)
        all_split_line_groups.extend(split_line_groups)
        all_filtered_text_boxes.extend(filtered_text_boxes)
        best_coverages.extend(
            row["dominant_coverage"]
            for row in report["rows"]
            if row["status"] != "no_box"
        )
        all_ocr_regions.extend(
            enrich_record(
                region,
                page_name=name,
                predictions_csv=predictions_csv,
                annotations_json=annotations_json,
            )
            for region in report.get("ocr_regions", [])
        )

        page_entry = {
            "page_name": name,
            "predictions_csv": str(predictions_csv),
            "annotations_json": str(annotations_json),
            "summary": summary,
            "ocr_regions": report.get("ocr_regions", []),
            "split_line_groups": split_line_groups,
            "ignored_rows": ignored_rows,
        }
        if page_filter is not None:
            page_entry["filter"] = page_filter
            page_entry["filtered_text_boxes"] = filtered_text_boxes
        pages.append(page_entry)

    region_summary = build_region_summary(all_ocr_regions)
    summary = {
        "unit_level": unit_level,
        "coverage_threshold": coverage_threshold,
        "pair_count": len(page_reports),
        "total_rows": total_rows,
        "ignored_watermark_rows": ignored_watermark_rows,
        "exactly_one_box": exactly_one_box,
        "exactly_one_box_rate": safe_rate(exactly_one_box, total_rows),
        "multiple_boxes": multiple_boxes,
        "multiple_boxes_rate": safe_rate(multiple_boxes, total_rows),
        "no_box": no_box,
        "no_box_rate": safe_rate(no_box, total_rows),
        "detected_empty": detected_empty,
        "split_line": split_line,
        "split_line_rate": safe_rate(split_line, total_rows),
        "split_line_rows": split_line_rows,
        "split_line_rows_rate": safe_rate(split_line_rows, total_rows),
        "mean_best_coverage": safe_mean(best_coverages),
        "gt_box_count": total_gt_box_count,
        "gt_char_count": total_gt_char_count,
        "ocr_region_count": region_summary["ocr_region_count"],
        "multibox_region_count": region_summary["multibox_region_count"],
        "ocr_region_mean_cer": region_summary["mean_cer"],
        "ocr_region_gt_char_count": region_summary["gt_char_count"],
        "ocr_region_char_edit_distance": region_summary["char_edit_distance"],
        "ocr_region_cer": region_summary["cer"],
        "ocr_region_cer_lowercase": region_summary["cer_lowercase"],
        "ocr_region_cer_buckets": region_summary["cer_buckets"],
        "normal_single_box_region": 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_accumulator is not None:
        summary["filter"] = summarize_filter_accumulator(filter_accumulator)

    failure_examples = build_aggregate_failure_examples(
        rows=all_rows,
        split_line_groups=all_split_line_groups,
        ocr_regions=all_ocr_regions,
        example_count=failure_example_count,
    )
    aggregate_report = {
        "summary": summary,
        "pages": pages,
        "failure_examples": failure_examples,
        "split_line_groups": all_split_line_groups,
        "ignored_rows": all_ignored_rows,
        "excluded_labels": report_excluded_labels(),
    }
    if filter_accumulator is not None:
        aggregate_report["filtered_text_boxes"] = all_filtered_text_boxes
    return aggregate_report


def main() -> None:
    args = parse_args()
    predictions_dir = (args.predictions_dir or args.data_dir)
    annotations_dir = (args.annotations_dir or args.data_dir)
    if not predictions_dir or not annotations_dir:
        raise SystemExit(
            "Provide --data-dir or both --predictions-dir and --annotations-dir."
        )
    pairs = discover_pairs(predictions_dir.resolve(), annotations_dir.resolve())
    try:
        filters = parse_filter_names(args.filters)
    except ValueError as error:
        raise SystemExit(str(error)) from error

    page_reports: list[dict[str, Any]] = []
    for name, predictions_csv, annotations_json in pairs:
        predicted_rows = load_predicted_rows(predictions_csv, unit_level=args.unit_level)
        annotation_boxes = load_annotation_boxes(annotations_json)
        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=False,
            filters=filters,
            unit_level=args.unit_level,
        )
        page_reports.append(
            {
                "page_name": name,
                "predictions_csv": predictions_csv,
                "annotations_json": annotations_json,
                "report": report,
            }
        )

    aggregate_report = aggregate_reports(
        page_reports=page_reports,
        coverage_threshold=args.coverage_threshold,
        failure_example_count=args.failure_example_count,
        unit_level=args.unit_level,
    )

    print(json.dumps(aggregate_report["summary"], ensure_ascii=False, indent=2))

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


if __name__ == "__main__":
    main()