File size: 7,918 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
"""Build per-box, per-region and filtered-text reports for a page."""

from __future__ import annotations

import sys
from pathlib import Path

_BOX_GROUPING = str(Path(__file__).resolve().parent.parent / "box_grouping")
if _BOX_GROUPING not in sys.path:
    sys.path.insert(0, _BOX_GROUPING)

from typing import Any

from models import AnnotationBox, annotation_box_type, annotation_box_metadata
from spatial import (
    normalize_whitespace,
    rounded_box,
    flatten_text_units,
    group_items_left_to_right_top_to_bottom,
)
from text_metrics import (
    safe_mean,
    safe_error_rate,
    build_cer_bucket_summary,
    compute_text_metrics,
)
from prediction import build_region_predicted_text
from models import gt_box_report


def filtered_box_report(annotation_box: AnnotationBox) -> dict[str, Any]:
    """Build a report dict for a box that was excluded by a label-based filter."""
    return {
        **annotation_box_metadata(annotation_box),
        "gt_box": rounded_box(annotation_box.bounds),
        "gt_normalized_text": normalize_whitespace(annotation_box.text),
        "has_transcription": annotation_box.has_transcription,
        "excluded_as_non_armenian_text": annotation_box.excluded_as_non_armenian_text,
    }


def build_region_summary(region_reports: list[dict[str, Any]]) -> dict[str, Any]:
    """Aggregate CER/bucket stats from a list of already-built region reports.

    Shared by build_ocr_region_reports (per-page) and aggregate_reports
    (across pages) so the two levels can't drift apart on which fields get
    computed how.
    """
    total_gt_chars = 0
    total_char_distance = 0
    total_char_distance_lower = 0
    region_cers: list[float] = []
    normal_single_box_region_cers: list[float] = []
    normal_single_box_region_gt_chars = 0
    normal_single_box_region_char_distance = 0
    multibox_region_count = 0

    for region in region_reports:
        text_metrics = region["text_metrics"]
        total_gt_chars += text_metrics["gt_char_count"]
        total_char_distance += text_metrics["char_edit_distance"]
        total_char_distance_lower += text_metrics["char_edit_distance_lowercase"]
        region_cers.append(text_metrics["cer"])
        if len(region["box_ids"]) > 1:
            multibox_region_count += 1
        if region.get("normal_single_box_region"):
            normal_single_box_region_cers.append(text_metrics["cer"])
            normal_single_box_region_gt_chars += text_metrics["gt_char_count"]
            normal_single_box_region_char_distance += text_metrics[
                "char_edit_distance"
            ]

    return {
        "ocr_region_count": len(region_reports),
        "multibox_region_count": multibox_region_count,
        "mean_cer": safe_mean(region_cers),
        "gt_char_count": total_gt_chars,
        "char_edit_distance": total_char_distance,
        "char_edit_distance_lowercase": total_char_distance_lower,
        "cer": safe_error_rate(total_char_distance, total_gt_chars),
        "cer_lowercase": safe_error_rate(total_char_distance_lower, total_gt_chars),
        "cer_buckets": build_cer_bucket_summary(region_cers),
        "normal_single_box_region": {
            "count": len(normal_single_box_region_cers),
            "mean_cer": safe_mean(normal_single_box_region_cers),
            "cer": safe_error_rate(
                normal_single_box_region_char_distance,
                normal_single_box_region_gt_chars,
            ),
        },
    }


def build_ocr_region_reports(
    details: list[dict[str, Any]],
    annotation_boxes: list[AnnotationBox],
    predicted_rows_by_id: dict[str, Any],
    should_exclude_box: Any = None,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
    """Group boxes into reading-order regions and compute per-region text metrics."""
    annotation_box_by_id = {
        box.box_id: box for box in annotation_boxes if box.has_transcription
    }
    excluded_annotation_boxes = (
        [box for box in annotation_box_by_id.values() if should_exclude_box(box)]
        if should_exclude_box is not None
        else None
    )
    row_by_id = {row["row_id"]: row for row in details}
    adjacency: dict[str, set[str]] = {
        box_id: set() for box_id in annotation_box_by_id
    }

    for row in details:
        touched_text_box_ids = [
            box_id
            for box_id in row.get("touched_box_ids", [])
            if box_id in annotation_box_by_id
        ]
        if len(touched_text_box_ids) < 2:
            continue
        for left_position, left_box_id in enumerate(touched_text_box_ids):
            for right_box_id in touched_text_box_ids[left_position + 1 :]:
                adjacency[left_box_id].add(right_box_id)
                adjacency[right_box_id].add(left_box_id)

    visited: set[str] = set()
    region_reports: list[dict[str, Any]] = []

    for start_box_id in sorted(annotation_box_by_id):
        if start_box_id in visited:
            continue

        stack = [start_box_id]
        component_box_ids: list[str] = []
        while stack:
            current_box_id = stack.pop()
            if current_box_id in visited:
                continue
            visited.add(current_box_id)
            component_box_ids.append(current_box_id)
            stack.extend(sorted(adjacency.get(current_box_id, ())))

        ordered_box_columns = group_items_left_to_right_top_to_bottom(
            [annotation_box_by_id[box_id] for box_id in component_box_ids],
            lambda box: box.bounds,
        )
        ordered_boxes = [
            box for column_boxes in ordered_box_columns for box in column_boxes
        ]
        if should_exclude_box is not None:
            ordered_boxes = [
                box for box in ordered_boxes if not should_exclude_box(box)
            ]
            if not ordered_boxes:
                continue
        ordered_box_ids = [box.box_id for box in ordered_boxes]
        gt_text = flatten_text_units([box.text for box in ordered_boxes])
        region_box_ids = set(ordered_box_ids)
        region_rows = [
            row
            for row in details
            if any(
                box_id in region_box_ids
                for box_id in row.get("touched_box_ids", [])
            )
        ]
        (
            predicted_text,
            predicted_line_count,
            assigned_row_ids,
            predicted_box,
            join_word_indices,
        ) = build_region_predicted_text(
            region_rows,
            predicted_rows_by_id,
            ordered_boxes,
            excluded_annotation_boxes=excluded_annotation_boxes,
        )
        text_metrics = compute_text_metrics(
            gt_text,
            predicted_text,
            predicted_hyphen_join_word_indices=join_word_indices,
        )
        normal_single_box_region = (
            len(ordered_boxes) == 1
            and bool(assigned_row_ids)
            and all(
                row_by_id[row_id]["status"] == "exactly_one_box"
                for row_id in assigned_row_ids
            )
        )

        region_reports.append(
            {
                "region_id": ordered_box_ids[0],
                "box_ids": ordered_box_ids,
                "box_types": [
                    annotation_box_type(box) for box in ordered_boxes
                ],
                "gt_boxes": [rounded_box(box.bounds) for box in ordered_boxes],
                "gt_box_details": [gt_box_report(box) for box in ordered_boxes],
                "predicted_box": (
                    rounded_box(predicted_box) if predicted_box is not None else None
                ),
                "predicted_line_count": predicted_line_count,
                "normal_single_box_region": normal_single_box_region,
                "text_metrics": text_metrics,
            }
        )

    region_summary = build_region_summary(region_reports)
    return region_reports, region_summary