File size: 9,639 Bytes
551cc83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6de936
551cc83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e97ee6f
 
 
 
 
551cc83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e97ee6f
 
 
 
 
 
551cc83
 
e97ee6f
551cc83
 
 
 
 
e97ee6f
 
 
 
 
 
 
 
 
 
551cc83
 
 
 
 
 
 
 
a6de936
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#!/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()