| """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 |
|
|