Datasets:

Modalities:
Image
Text
Formats:
parquet
Languages:
Armenian
Size:
< 1K
ArXiv:
License:
File size: 8,662 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
"""Text accuracy metrics: edit distance, CER, bucket summaries."""

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)

import unicodedata
from typing import Any, Sequence

from spatial import normalize_whitespace


CER_BUCKET_KEYS = (
    "lt_0_1",
    "0_1_to_0_3",
    "0_3_to_0_6",
    "0_6_to_1",
    "gt_1",
)
HIGH_IMPACT_REGION_EXAMPLE_COUNT = 3


def safe_rate(count: int, total: int) -> float:
    if total == 0:
        return 0.0
    return round(count / total, 6)


def safe_mean(values: list[float]) -> float:
    if not values:
        return 0.0
    return round(sum(values) / len(values), 6)


def safe_error_rate(edit_distance_value: int, gt_length: int) -> float:
    if gt_length == 0:
        return 0.0 if edit_distance_value == 0 else 1.0
    return round(edit_distance_value / gt_length, 6)


def cer_bucket_key(cer: float) -> str:
    if cer < 0.1:
        return "lt_0_1"
    if cer < 0.3:
        return "0_1_to_0_3"
    if cer < 0.6:
        return "0_3_to_0_6"
    if cer <= 1.0:
        return "0_6_to_1"
    return "gt_1"


def build_cer_bucket_summary(
    cers: list[float],
) -> dict[str, dict[str, int | float]]:
    counts = {bucket_key: 0 for bucket_key in CER_BUCKET_KEYS}
    for cer in cers:
        counts[cer_bucket_key(cer)] += 1
    total = len(cers)
    return {
        bucket_key: {
            "count": count,
            "rate": safe_rate(count, total),
        }
        for bucket_key, count in counts.items()
    }


def normalize_punctuation_chars(text: str) -> str:
    """Normalize visually similar or OCR-confused characters to canonical form.

    Applied to both gt and predicted text before CER so that encoding
    differences do not count as errors.  Rules are explicit char-to-char (or
    string-to-string) mappings — extend CHAR_MAP or SEQUENCE_MAP as needed.
    """
    CHAR_LAST = ":"
    CHAR_MAP: dict[str, str] = {
        "֊":  "-",
         "—":  "-",
        "́": "՛",  # COMBINING ACUTE ACCENT ́       → ՛ ARMENIAN EMPHASIS MARK
        "`": "`",  # GRAVE ACCENT ` — canonical form (paired with ՝ → ` below)
        "՝": "`",  # ՝ ARMENIAN COMMA → ` GRAVE ACCENT
        "․": ".",  # ONE DOT LEADER ․               → . FULL STOP
        "…": "...",     # HORIZONTAL ELLIPSIS …           → ...
        "№": "N",  # U+2116 NUMERO SIGN              → N
        "։": CHAR_LAST,
        ":":  CHAR_LAST,  # U+003A  COLON
        "˸":  CHAR_LAST,  # U+02F8  MODIFIER LETTER RAISED COLON
        "︓":  CHAR_LAST,  # U+FE13  PRESENTATION FORM FOR VERTICAL COLON
        "︰":  CHAR_LAST,  # U+FE30  PRESENTATION FORM FOR VERTICAL TWO DOT LEADER
        ":": CHAR_LAST,  # U+FF1A  FULLWIDTH COLON
        "∶":  CHAR_LAST,  # U+2236  RATIO
        "꞉":  CHAR_LAST,  # U+A789  MODIFIER LETTER COLON
    }

    # Multi-character substitutions — applied BEFORE single-char replacements
    SEQUENCE_MAP: list[tuple[str, str]] = [
        ("--", "—"),    # double hyphen --               → — EM DASH
        ("եւ", "և"),   # old Armenian yev spelling      → և ligature
    ]

    for wrong, correct in SEQUENCE_MAP:
        text = text.replace(wrong, correct)

    return "".join(CHAR_MAP.get(ch, ch) for ch in text)


def edit_distance(left: Sequence[Any] | str, right: Sequence[Any] | str) -> int:
    left_items = list(left)
    right_items = list(right)

    if left_items == right_items:
        return 0
    if not left_items:
        return len(right_items)
    if not right_items:
        return len(left_items)

    if len(left_items) < len(right_items):
        left_items, right_items = right_items, left_items

    previous = list(range(len(right_items) + 1))
    for left_index, left_item in enumerate(left_items, start=1):
        current = [left_index]
        for right_index, right_item in enumerate(right_items, start=1):
            insertion = current[right_index - 1] + 1
            deletion = previous[right_index] + 1
            substitution = previous[right_index - 1] + (left_item != right_item)
            current.append(min(insertion, deletion, substitution))
        previous = current
    return previous[-1]


_ARMENIAN_SCHWA = "ը"


def _schwa_free_char_positions(
    text: str, join_word_indices: frozenset[int]
) -> frozenset[int]:
    """Return char positions in *text* that belong to hyphen-joined words."""
    if not join_word_indices:
        return frozenset()
    positions: set[int] = set()
    char_offset = 0
    for idx, word in enumerate(text.split()):
        if idx in join_word_indices:
            for i in range(len(word)):
                positions.add(char_offset + i)
        char_offset += len(word) + 1
    return frozenset(positions)


def edit_distance_schwa_forgiving(
    left: str, right: str, right_schwa_free: frozenset[int]
) -> int:
    """Edit distance where inserting ը at positions in right_schwa_free costs 0."""
    if not right_schwa_free:
        return edit_distance(left, right)

    left_items = list(left)
    right_items = list(right)

    if left_items == right_items:
        return 0
    if not left_items:
        return sum(
            0 if (j in right_schwa_free and ch == _ARMENIAN_SCHWA) else 1
            for j, ch in enumerate(right_items)
        )
    if not right_items:
        return len(left_items)

    # Initialise first row (all insertions from right)
    previous = [0]
    for j, ch in enumerate(right_items):
        ins_cost = 0 if (j in right_schwa_free and ch == _ARMENIAN_SCHWA) else 1
        previous.append(previous[-1] + ins_cost)

    for left_index, left_item in enumerate(left_items, start=1):
        current = [left_index]
        for right_index, right_item in enumerate(right_items, start=1):
            j = right_index - 1
            ins_cost = 0 if (j in right_schwa_free and right_item == _ARMENIAN_SCHWA) else 1
            insertion = current[right_index - 1] + ins_cost
            deletion = previous[right_index] + 1
            substitution = previous[right_index - 1] + (left_item != right_item)
            current.append(min(insertion, deletion, substitution))
        previous = current
    return previous[-1]


def compute_text_metrics(
    gt_text: str,
    predicted_text: str,
    *,
    predicted_hyphen_join_word_indices: frozenset[int] = frozenset(),
) -> dict[str, Any]:
    gt_normalized = unicodedata.normalize(
        "NFC", normalize_whitespace(gt_text)
    )
    predicted_normalized = unicodedata.normalize(
        "NFC", normalize_whitespace(predicted_text)
    )
    gt_normalized = normalize_punctuation_chars(normalize_whitespace(gt_normalized))
    predicted_normalized = normalize_punctuation_chars(
        normalize_whitespace(predicted_normalized)
    )
    schwa_free = _schwa_free_char_positions(
        predicted_normalized, predicted_hyphen_join_word_indices
    )
    char_distance = edit_distance_schwa_forgiving(gt_normalized, predicted_normalized, schwa_free)
    char_distance_lower = edit_distance_schwa_forgiving(
        gt_normalized.lower(), predicted_normalized.lower(), schwa_free
    )

    return {
        "gt_normalized_text": gt_normalized,
        "pr_normalized_text": predicted_normalized,
        "gt_char_count": len(gt_normalized),
        "predicted_char_count": len(predicted_normalized),
        "char_edit_distance": char_distance,
        "cer": safe_error_rate(char_distance, len(gt_normalized)),
        "char_edit_distance_lowercase": char_distance_lower,
        "cer_lowercase": safe_error_rate(char_distance_lower, len(gt_normalized)),
    }


def summarize_region_example(
    region: dict[str, Any],
    *,
    include_error_stats: bool = False,
) -> dict[str, Any]:
    text_metrics = region["text_metrics"]
    summary = {
        "gt_normalized_text": text_metrics["gt_normalized_text"],
        "pr_normalized_text": text_metrics["pr_normalized_text"],
    }
    for field_name in ("region_id", "box_ids", "gt_box_details"):
        if field_name in region:
            summary[field_name] = region[field_name]
    if include_error_stats:
        summary.update(
            {
                "gt_char_count": text_metrics["gt_char_count"],
                "char_edit_distance": text_metrics["char_edit_distance"],
                "cer": text_metrics["cer"],
            }
        )
    for field_name in ("page_name", "predictions_csv", "annotations_json"):
        if field_name in region:
            summary[field_name] = region[field_name]
    return summary