Datasets:
Download evaluation_kit/evaluate_from_hf_fast.py from RLALT/ACoPPer: direct link, hf CLI and curl.
- Browser
- Download file 6.72 kB
-
https://huggingface.co/datasets/RLALT/ACoPPer/resolve/main/evaluation_kit/evaluate_from_hf_fast.py
- Command line
-
hf download hf://datasets/RLALT/ACoPPer/evaluation_kit/evaluate_from_hf_fast.py
-
curl -L -o evaluate_from_hf_fast.py https://huggingface.co/datasets/RLALT/ACoPPer/resolve/main/evaluation_kit/evaluate_from_hf_fast.py
6.72 kB
| #!/usr/bin/env python3 | |
| """Fast variant of evaluate_from_hf.py for image-heavy datasets (ACoPPer). | |
| `evaluate_from_hf.py`'s `Dataset.from_parquet(...)` materializes every | |
| column, including full-page scan images -- on ACoPPer this took 15-20+ | |
| minutes per invocation even with the parquet files already cached | |
| locally, because the `datasets` library decodes/rewrites the embedded | |
| image bytes into its own arrow cache regardless of whether anything | |
| downstream actually reads them. Scoring only needs `page_id` and | |
| `annotations`; reading just those two columns directly via | |
| `pyarrow.parquet.read_table(files, columns=[...])` takes well under a | |
| second for the same 197 pages. | |
| Two modes this enables that the slow path made impractical for iterative | |
| work: | |
| - `--pages page1 page2 ...`: score only a specific subset (e.g. the | |
| handful of pages a candidate repair actually touched) for a fast | |
| accept/reject signal before paying for a full run. | |
| - default (no `--pages`): score every page, same as `evaluate_from_hf.py` | |
| -- now fast too, so "compute the total CER to confirm" is cheap once a | |
| subset check looks promising. | |
| Same evaluation engine, same output shape, same GT-blind contract as | |
| `evaluate_from_hf.py` (ground truth is only ever consulted inside the | |
| scorer to produce the final CER numbers, never surfaced as text to the | |
| caller). Kept as a separate script rather than a flag on | |
| `evaluate_from_hf.py` so the original stays untouched. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sys | |
| from pathlib import Path | |
| from typing import Any | |
| _ROOT = Path(__file__).resolve().parent | |
| for _subdir in ("evaluation", "box_grouping"): | |
| _path = str(_ROOT / _subdir) | |
| if _path not in sys.path: | |
| sys.path.insert(0, _path) | |
| from measure_accuracy import evaluate_rows, parse_filter_names # noqa: E402 | |
| from measure_overall_accuracy import aggregate_reports # noqa: E402 | |
| from generate_accuracy_report_variants import REPORT_VARIANTS # noqa: E402 | |
| from loading import load_predicted_rows # noqa: E402 | |
| sys.path.insert(0, str(_ROOT)) | |
| from evaluate_from_hf import annotation_boxes_from_hf_row # noqa: E402 | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--dataset", default="RLALT/ACoPPer") | |
| parser.add_argument("--split", default="test") | |
| parser.add_argument("--predictions-dir", type=Path, required=True) | |
| parser.add_argument("--output-dir", type=Path, required=True) | |
| parser.add_argument("--unit-level", choices=["word", "line"], default="word") | |
| parser.add_argument("--coverage-threshold", type=float, default=1.0) | |
| parser.add_argument("--failure-example-count", type=int, default=5) | |
| parser.add_argument("--variant", choices=[v["name"] for v in REPORT_VARIANTS], default=None) | |
| parser.add_argument( | |
| "--pages", | |
| nargs="*", | |
| default=None, | |
| help="Score only these page_ids (fast subset check). Omit to score all pages.", | |
| ) | |
| return parser.parse_args() | |
| def load_annotations_only(dataset: str, split: str) -> list[dict[str, Any]]: | |
| import pyarrow.parquet as pq | |
| from huggingface_hub import snapshot_download | |
| snapshot_dir = Path( | |
| snapshot_download(repo_id=dataset, repo_type="dataset", allow_patterns=[f"data/{split}-*.parquet"]) | |
| ) | |
| parquet_files = sorted(str(p) for p in snapshot_dir.glob(f"data/{split}-*.parquet")) | |
| if not parquet_files: | |
| raise ValueError(f"{dataset}: no data/{split}-*.parquet files found") | |
| table = pq.read_table(parquet_files, columns=["page_id", "annotations"]) | |
| return table.to_pylist() | |
| def main() -> None: | |
| args = parse_args() | |
| rows = load_annotations_only(args.dataset, args.split) | |
| if args.pages: | |
| wanted = set(args.pages) | |
| rows = [r for r in rows if r["page_id"] in wanted] | |
| missing_requested = wanted - {r["page_id"] for r in rows} | |
| if missing_requested: | |
| print(f"Warning: requested page(s) not found in dataset: {sorted(missing_requested)}") | |
| print(f"Scoring {len(rows)} page(s) from {args.dataset}[{args.split}]" + (" (subset)" if args.pages else "")) | |
| variants = REPORT_VARIANTS | |
| if args.variant: | |
| variants = tuple(v for v in REPORT_VARIANTS if v["name"] == args.variant) | |
| page_reports_by_variant: dict[str, list[dict[str, Any]]] = {v["name"]: [] for v in variants} | |
| missing_predictions: list[str] = [] | |
| for row in rows: | |
| page_id = row["page_id"] | |
| predictions_csv = args.predictions_dir / f"{page_id}.csv" | |
| if not predictions_csv.exists(): | |
| missing_predictions.append(page_id) | |
| continue | |
| annotation_boxes = annotation_boxes_from_hf_row(row) | |
| predicted_rows = load_predicted_rows(predictions_csv, unit_level=args.unit_level) | |
| for variant in variants: | |
| filters = parse_filter_names(variant["filters"]) | |
| 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_by_variant[variant["name"]].append( | |
| { | |
| "page_name": page_id, | |
| "predictions_csv": str(predictions_csv), | |
| "annotations_json": f"hf://{args.dataset}/{args.split}#{page_id}", | |
| "report": report, | |
| } | |
| ) | |
| if missing_predictions: | |
| print( | |
| f"Warning: {len(missing_predictions)} page(s) had no matching CSV, skipped: " | |
| f"{', '.join(sorted(missing_predictions)[:10])}" + (" ..." if len(missing_predictions) > 10 else ""), | |
| flush=True, | |
| ) | |
| args.output_dir.mkdir(parents=True, exist_ok=True) | |
| for variant in variants: | |
| aggregate_report = aggregate_reports( | |
| page_reports=page_reports_by_variant[variant["name"]], | |
| coverage_threshold=args.coverage_threshold, | |
| failure_example_count=args.failure_example_count, | |
| unit_level=args.unit_level, | |
| ) | |
| output_path = args.output_dir / variant["filename"] | |
| output_path.write_text(json.dumps(aggregate_report, ensure_ascii=False, indent=2), encoding="utf-8") | |
| summary = aggregate_report["summary"] | |
| print( | |
| f"{variant['name']}: cer={summary['ocr_region_cer']:.4f} " | |
| f"({summary['pair_count']} page(s)) -> {output_path}", | |
| flush=True, | |
| ) | |
| if __name__ == "__main__": | |
| main() | |