| """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] = { |
| "֊": "-", |
| "—": "-", |
| "́": "՛", |
| "`": "`", |
| "՝": "`", |
| "․": ".", |
| "…": "...", |
| "№": "N", |
| "։": CHAR_LAST, |
| ":": CHAR_LAST, |
| "˸": CHAR_LAST, |
| "︓": CHAR_LAST, |
| "︰": CHAR_LAST, |
| ":": CHAR_LAST, |
| "∶": CHAR_LAST, |
| "꞉": CHAR_LAST, |
| } |
|
|
| |
| SEQUENCE_MAP: list[tuple[str, str]] = [ |
| ("--", "—"), |
| ("եւ", "և"), |
| ] |
|
|
| 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) |
|
|
| |
| 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 |
|
|