ACoPPer / evaluation_kit /evaluate_from_hf.py
Yeva's picture
Sync evaluate_from_hf.py: filter redundant/decomposable boxes and stable-sort ground truth to match loading.load_annotation_boxes
e97ee6f verified
Raw
History Blame Contribute Delete
9.64 kB
#!/usr/bin/env python3
"""Evaluate a model's predictions against RLALT/ACoPPer (or RLALT/ACoPDoc)
loaded directly from the Hugging Face Hub — no local annotation JSONs needed.
Ground truth comes from the dataset's `annotations` column, matched to your
own model's predictions by `page_id`. You still need to run your model
yourself and convert its output to one evaluation CSV per page (see
`convert_predictions_to_evaluation_csv.py` in this folder) before running
this script.
Usage:
python evaluate_from_hf.py \\
--dataset RLALT/ACoPPer \\
--split test \\
--predictions-dir path/to/your/evaluation_csvs \\
--output-dir results/ \\
--unit-level word
Dependencies (not required by the rest of this kit):
pip install -r requirements.txt
"""
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 geometry import Box, polygon_bounds, rotated_rectangle_points # noqa: E402
from models import ( # noqa: E402
AnnotationBox,
decomposable_container_box_ids,
filter_redundant_annotation_boxes,
)
from loading import ( # noqa: E402
NON_ARMENIAN_BOX_LETTER_RATIO_THRESHOLD,
load_predicted_rows,
non_armenian_letter_ratio,
)
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
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--dataset",
default="RLALT/ACoPPer",
help="HF dataset repo id, e.g. RLALT/ACoPPer or RLALT/ACoPDoc.",
)
parser.add_argument(
"--split",
default="test",
help=(
"Hub split key to load (default 'test' — both RLALT/ACoPPer and "
"RLALT/ACoPDoc are currently published with a single 'test' "
"split). Check the loaded dataset's split names if unsure."
),
)
parser.add_argument(
"--dataset-split-column",
default=None,
help=(
"Optional: filter rows further by the dataset's own `split` "
"column value (e.g. 'pilot'), which is separate from --split "
"(the Hub split key)."
),
)
parser.add_argument(
"--predictions-dir",
type=Path,
required=True,
help="Directory with one evaluation CSV per page_id (<page_id>.csv).",
)
parser.add_argument(
"--output-dir",
type=Path,
required=True,
help="Directory where report JSON files are written.",
)
parser.add_argument(
"--unit-level",
dest="unit_level",
choices=["word", "line"],
default="word",
help="Granularity of predicted rows: 'word' or 'line'.",
)
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(
"--variant",
choices=[v["name"] for v in REPORT_VARIANTS],
default=None,
help="Generate only this filter variant. Omit to generate all four.",
)
return parser.parse_args()
def annotation_box_from_hf_item(item: dict[str, Any]) -> AnnotationBox:
"""Build an AnnotationBox from one entry of the dataset's `annotations` column.
The HF schema is already flattened (id/label/transcription/reading_order/
parent_id/bbox/rotation) rather than the raw Label Studio export shape
`load_annotation_boxes` normally parses, so this constructs the object
directly instead of round-tripping through JSON.
"""
x1, y1, x2, y2 = item["bbox"]
width, height = x2 - x1, y2 - y1
rotation = item["rotation"]
polygon = rotated_rectangle_points(x1, y1, width, height, rotation)
text = item["transcription"]
letter_count, latin_or_cyrillic_count, ratio = non_armenian_letter_ratio(text)
return AnnotationBox(
box_id=item["id"],
rect=Box(x1, y1, x2, y2),
text=text,
# HF's flattened schema only keeps the resulting string, not whether
# a transcription field was present at all, so this is an
# approximation of the raw loader's has_transcription flag.
has_transcription=bool(text),
rotation=rotation,
polygon=polygon,
bounds=polygon_bounds(polygon),
labels=(item["label"],) if item["label"] else (),
letter_count=letter_count,
latin_or_cyrillic_letter_count=latin_or_cyrillic_count,
non_armenian_letter_ratio=ratio,
excluded_as_non_armenian_text=ratio > NON_ARMENIAN_BOX_LETTER_RATIO_THRESHOLD,
parent_box_id=item["parent_id"] or None,
reading_order=item["reading_order"] if item["reading_order"] != -1 else None,
)
def annotation_boxes_from_hf_row(row: dict[str, Any]) -> list[AnnotationBox]:
"""Build one page's ground-truth boxes from the dataset's `annotations` column.
Mirrors the tail of `loading.load_annotation_boxes` exactly: the same
post-processing has to run here or this entry point would score against a
different ground truth than the local-JSON scripts do.
"""
# Rule-labeled regions are decorative separator lines, not text — the
# raw-JSON loader (load_annotation_boxes) drops them the same way.
boxes = [
annotation_box_from_hf_item(item)
for item in row["annotations"]
if item["label"] != "Rule"
]
decomposable_ids = decomposable_container_box_ids(boxes)
boxes = [box for box in boxes if box.box_id not in decomposable_ids]
# The sort is load-bearing, not cosmetic: group.py ranks candidate boxes
# with a stable sort, so this order breaks coverage ties.
return sorted(
filter_redundant_annotation_boxes(boxes),
key=lambda item: (item.bounds.y_min, item.bounds.x_min, item.box_id),
)
def main() -> None:
args = parse_args()
try:
from datasets import load_dataset
except ImportError as exc:
raise SystemExit(
"This script needs the `datasets` package: pip install -r requirements.txt"
) from exc
dataset = load_dataset(args.dataset)[args.split]
if args.dataset_split_column:
dataset = dataset.filter(
lambda row: row["split"] == args.dataset_split_column
)
print(f"Loaded {len(dataset)} page(s) from {args.dataset}[{args.split}]")
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]]] = {
variant["name"]: [] for variant in variants
}
missing_predictions: list[str] = []
for row in dataset:
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 in "
f"{args.predictions_dir}, skipped: {', '.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()