| |
|
|
| """Generate the standard overall accuracy report variants.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import datetime |
| import json |
| from pathlib import Path |
| from typing import Any |
|
|
| from measure_accuracy import ( |
| evaluate_rows, |
| load_annotation_boxes, |
| load_predicted_rows, |
| parse_filter_names, |
| ) |
| from measure_overall_accuracy import aggregate_reports, discover_pairs |
|
|
|
|
| REPORT_VARIANTS: tuple[dict[str, Any], ...] = ( |
| { |
| "name": "no_filter", |
| "filters": None, |
| "filename": "overall_accuracy_report.json", |
| }, |
| { |
| "name": "non_armenian", |
| "filters": "non-armenian", |
| "filename": "overall_accuracy_filtered_non_armenian_report.json", |
| }, |
| { |
| "name": "graphics_headers_images_photos", |
| "filters": "graphics,header,image,photo", |
| "filename": "overall_accuracy_filtered_graphics_headers_images_photos_report.json", |
| }, |
| { |
| "name": "all_filters", |
| "filters": "non-armenian,graphics,header,image,photo", |
| "filename": "overall_accuracy_filtered_all_report.json", |
| }, |
| ) |
|
|
|
|
| LoadedPage = tuple[str, Path, Path, Any, Any] |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| """Parse command-line arguments.""" |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument( |
| "--data-dir", |
| type=Path, |
| default=Path(__file__).resolve().parent.parent / "box_grouping" / "data", |
| 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( |
| "--output-dir", |
| type=Path, |
| default=Path(__file__).resolve().parent |
| / "results" |
| / datetime.datetime.now().isoformat(), |
| help="Directory where the four aggregate report JSON files are written.", |
| ) |
| 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( |
| "--unit-level", |
| dest="unit_level", |
| choices=["word", "line"], |
| default="word", |
| help="Granularity of predicted rows: 'word' or 'line'.", |
| ) |
| parser.add_argument( |
| "--variant", |
| choices=[v["name"] for v in REPORT_VARIANTS], |
| default=None, |
| help="Generate only this variant. Omit to generate all four.", |
| ) |
| parser.add_argument( |
| "--partial", |
| action="store_true", |
| help=( |
| "Allow evaluation when prediction CSVs exist for only a subset of " |
| "annotated pages. Missing pages are skipped with a warning." |
| ), |
| ) |
| return parser.parse_args() |
|
|
|
|
| def load_pages( |
| predictions_dir: Path, |
| annotations_dir: Path, |
| *, |
| partial: bool = False, |
| unit_level: str = "word", |
| ) -> list[LoadedPage]: |
| """Load all matched CSV/JSON page pairs from the given directories.""" |
| return [ |
| ( |
| name, |
| predictions_csv, |
| annotations_json, |
| load_predicted_rows(predictions_csv, unit_level=unit_level), |
| load_annotation_boxes(annotations_json), |
| ) |
| for name, predictions_csv, annotations_json in discover_pairs( |
| predictions_dir, annotations_dir, partial=partial |
| ) |
| ] |
|
|
|
|
| def build_report( |
| *, |
| loaded_pages: list[LoadedPage], |
| filters: tuple[str, ...], |
| coverage_threshold: float, |
| failure_example_count: int, |
| unit_level: str = "word", |
| ) -> dict[str, Any]: |
| """Run box grouping and evaluation for one filter variant.""" |
| page_reports: list[dict[str, Any]] = [] |
| for ( |
| name, |
| predictions_csv, |
| annotations_json, |
| predicted_rows, |
| annotation_boxes, |
| ) in loaded_pages: |
| report = evaluate_rows( |
| predicted_rows=predicted_rows, |
| annotation_boxes=annotation_boxes, |
| coverage_threshold=coverage_threshold, |
| failure_example_count=failure_example_count, |
| hide_zero_cer_details=False, |
| filters=filters, |
| unit_level=unit_level, |
| ) |
| page_reports.append( |
| { |
| "page_name": name, |
| "predictions_csv": predictions_csv, |
| "annotations_json": annotations_json, |
| "report": report, |
| } |
| ) |
|
|
| return aggregate_reports( |
| page_reports=page_reports, |
| coverage_threshold=coverage_threshold, |
| failure_example_count=failure_example_count, |
| unit_level=unit_level, |
| ) |
|
|
|
|
| def main() -> None: |
| """Run all report variants and write JSON files to the output directory.""" |
| args = parse_args() |
| predictions_dir = (args.predictions_dir or args.data_dir).resolve() |
| annotations_dir = (args.annotations_dir or args.data_dir).resolve() |
| output_dir = args.output_dir.resolve() |
| output_dir.mkdir(parents=True, exist_ok=True) |
| loaded_pages = load_pages( |
| predictions_dir, annotations_dir, partial=args.partial, unit_level=args.unit_level |
| ) |
|
|
| variants = REPORT_VARIANTS |
| if args.variant: |
| variants = tuple(v for v in REPORT_VARIANTS if v["name"] == args.variant) |
|
|
| for variant in variants: |
| filters = parse_filter_names(variant["filters"]) |
| filter_label = ",".join(filters) if filters else "none" |
| print(f"Generating {variant['name']} (filter={filter_label})...", flush=True) |
| report = build_report( |
| loaded_pages=loaded_pages, |
| filters=filters, |
| coverage_threshold=args.coverage_threshold, |
| failure_example_count=args.failure_example_count, |
| unit_level=args.unit_level, |
| ) |
|
|
| variant_dir = output_dir / Path(variant["filename"]).stem |
| variant_dir.mkdir(parents=True, exist_ok=True) |
|
|
| pages = report.get("pages", []) |
| for page in pages: |
| page_path = variant_dir / f"{page['page_name']}.json" |
| page_path.write_text( |
| json.dumps(page, ensure_ascii=False, indent=2), |
| encoding="utf-8", |
| ) |
|
|
| summary_doc = {k: v for k, v in report.items() if k != "pages"} |
| summary_path = variant_dir / "summary.json" |
| summary_path.write_text( |
| json.dumps(summary_doc, ensure_ascii=False, indent=2), |
| encoding="utf-8", |
| ) |
|
|
| summary = report["summary"] |
| print( |
| f"{variant['name']}: {variant_dir} " |
| f"(filter={filter_label}, ocr_region_cer={summary['ocr_region_cer']}, " |
| f"{len(pages)} page(s) + summary.json)", |
| flush=True, |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|