#!/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()