Datasets:
File size: 7,259 Bytes
551cc83 | 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 | #!/usr/bin/env python3
"""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()
|