#!/usr/bin/env python3 """Evaluate CSV `group_row` predictions against annotated text boxes. Input 1: Label Studio-style JSON annotations. We use one text-bearing result per annotation id and convert each box from `x, y, width, height` to `x1, y1, x2, y2`. Input 2: CSV with predicted word boxes and `group_row`. Rows are grouped by `group_row`, then each row is checked against the annotation boxes. Row classification: - `exactly_one_box`: exactly one annotation box contains every word in the row, and no other annotation box significantly contains any word from that row. We also treat a row as `exactly_one_box` when it touches multiple boxes but one box covers almost all of that row, which usually means one stray word was pulled across columns by OCR. - `multiple_boxes`: words from the row significantly fall into multiple annotation boxes. - `no_box`: the row does not fit cleanly into any annotation box. Coverage in this script is location-first: - a word belongs to an annotation box when the word center lies inside that box - row coverage is the fraction of words in the row whose centers lie inside a given annotation box Label Studio box rotation is taken into account using the rotated rectangle geometry stored in the annotation results. """ from __future__ import annotations import json import sys from collections.abc import Callable from pathlib import Path from typing import Any _BOX_GROUPING = str(Path(__file__).resolve().parent.parent / "box_grouping") if _BOX_GROUPING not in sys.path: sys.path.insert(0, _BOX_GROUPING) # Geometry primitives (re-exported for callers and tests) from geometry import Box, polygon_bounds, rotated_rectangle_points # Domain models and constants from models import ( AnnotationBox, HEADER_TITLE_LIKE_LABELS, IMAGE_HEADER_FILTER_LABELS, IMAGE_RELATED_LABELS, PredictedRow, Word, annotation_box_metadata, annotation_box_type, gt_box_report, ) # Loading (re-exported for callers and tests) from loading import ( NON_ARMENIAN_BOX_LETTER_RATIO_THRESHOLD, is_watermark_row, load_annotation_boxes, load_predicted_rows, non_armenian_letter_ratio, parse_args, ) # Spatial utilities (re-exported for callers and tests) from spatial import row_box # Box-grouping entry point (spatial assignment) from group import group_words_into_regions # Text metrics from text_metrics import ( CER_BUCKET_KEYS, HIGH_IMPACT_REGION_EXAMPLE_COUNT, build_cer_bucket_summary, cer_bucket_key, compute_text_metrics, edit_distance, normalize_punctuation_chars, safe_error_rate, safe_mean, safe_rate, summarize_region_example, ) # Prediction builders from prediction import ( build_region_predicted_text, count_empty_words_in_non_empty_boxes, ) # Report builders from reports import ( build_ocr_region_reports, build_region_summary, filtered_box_report, ) def report_excluded_labels() -> dict[str, list[str]]: return { "image_related_boxes": sorted(IMAGE_RELATED_LABELS), "header_title_like_boxes": sorted(HEADER_TITLE_LIKE_LABELS), "image_header_boxes": sorted(IMAGE_HEADER_FILTER_LABELS), } FILTER_NON_ARMENIAN = "non-armenian" FILTER_LABEL_GROUPS: dict[str, frozenset[str]] = { "graphics": frozenset({"Graphics"}), "photo": frozenset({"Photo"}), "image": IMAGE_RELATED_LABELS, "header": HEADER_TITLE_LIKE_LABELS, "image-header": IMAGE_HEADER_FILTER_LABELS, } FILTER_ALIASES = { "nonarmenian": FILTER_NON_ARMENIAN, "non-armenian": FILTER_NON_ARMENIAN, "non_armenian": FILTER_NON_ARMENIAN, "latin": FILTER_NON_ARMENIAN, "latin-cyrillic": FILTER_NON_ARMENIAN, "latin_or_cyrillic": FILTER_NON_ARMENIAN, "image-header": "image-header", "image_header": "image-header", "imageheader": "image-header", "image-related": "image", "image_related": "image", "images": "image", "headers": "header", } AVAILABLE_FILTERS = (FILTER_NON_ARMENIAN, *FILTER_LABEL_GROUPS.keys()) def parse_filter_names( raw_filters: str | list[str] | tuple[str, ...] | None, ) -> tuple[str, ...]: if raw_filters is None: return () tokens: list[str] = [] if isinstance(raw_filters, str): tokens = raw_filters.split(",") else: for raw_filter in raw_filters: tokens.extend(str(raw_filter).split(",")) selected_filters: list[str] = [] seen_filters: set[str] = set() for token in tokens: normalized = token.strip().lower().replace(" ", "-") if not normalized: continue canonical = FILTER_ALIASES.get(normalized, normalized) if canonical not in AVAILABLE_FILTERS: available = ", ".join(AVAILABLE_FILTERS) raise ValueError( f"Unknown filter '{token}'. Available filters: {available}" ) if canonical not in seen_filters: selected_filters.append(canonical) seen_filters.add(canonical) return tuple(selected_filters) def labels_for_filters(filter_names: tuple[str, ...]) -> frozenset[str]: labels: set[str] = set() for filter_name in filter_names: labels.update(FILTER_LABEL_GROUPS.get(filter_name, ())) return frozenset(labels) def filter_matches_for_box( annotation_box: AnnotationBox, filter_names: tuple[str, ...], ) -> list[str]: matches: list[str] = [] box_labels = set(annotation_box.labels) for filter_name in filter_names: if ( filter_name == FILTER_NON_ARMENIAN and annotation_box.excluded_as_non_armenian_text ): matches.append(filter_name) continue label_group = FILTER_LABEL_GROUPS.get(filter_name) if label_group and box_labels & label_group: matches.append(filter_name) return matches def should_exclude_box_for_filters( filter_names: tuple[str, ...], ) -> Callable[[AnnotationBox], bool] | None: if not filter_names: return None def should_exclude_box(annotation_box: AnnotationBox) -> bool: return bool(filter_matches_for_box(annotation_box, filter_names)) return should_exclude_box def filtered_region_box_report( annotation_box: AnnotationBox, filter_names: tuple[str, ...], ) -> dict[str, Any]: report = filtered_box_report(annotation_box) report["matched_filters"] = filter_matches_for_box(annotation_box, filter_names) report["letter_count"] = annotation_box.letter_count report["latin_or_cyrillic_letter_count"] = ( annotation_box.latin_or_cyrillic_letter_count ) report["non_armenian_letter_ratio"] = round( annotation_box.non_armenian_letter_ratio, 6, ) report["non_armenian_letter_percentage"] = round( annotation_box.non_armenian_letter_ratio * 100, 6, ) return report def build_region_filter_report( annotation_boxes: list[AnnotationBox], filter_names: tuple[str, ...], ) -> dict[str, Any]: text_boxes = [box for box in annotation_boxes if box.has_transcription] excluded_boxes = [ box for box in text_boxes if filter_matches_for_box(box, filter_names) ] report = { "filters": list(filter_names), "text_box_count": len(text_boxes), "excluded_box_count": len(excluded_boxes), "excluded_box_rate": safe_rate(len(excluded_boxes), len(text_boxes)), "included_box_count": len(text_boxes) - len(excluded_boxes), "excluded_boxes": [ filtered_region_box_report(box, filter_names) for box in excluded_boxes ], } if FILTER_NON_ARMENIAN in filter_names: report["threshold"] = NON_ARMENIAN_BOX_LETTER_RATIO_THRESHOLD label_filters = labels_for_filters(filter_names) if label_filters: report["labels"] = sorted(label_filters) return report def summarize_region_filter_report(filter_report: dict[str, Any]) -> dict[str, Any]: return { key: value for key, value in filter_report.items() if key != "excluded_boxes" } def nonzero_cer_records(records: list[dict[str, Any]]) -> list[dict[str, Any]]: return [ record for record in records if (record.get("text_metrics") or {}).get("cer", 0.0) != 0.0 ] def select_no_box_failure_examples( rows: list[dict[str, Any]], example_count: int, ) -> list[dict[str, Any]]: non_empty_rows = [row for row in rows if row["row_text"].strip()] if non_empty_rows: return non_empty_rows[:example_count] return rows[:1] def build_failure_examples( details: list[dict[str, Any]], ocr_regions: list[dict[str, Any]], example_count: int, split_line_groups: list[dict[str, Any]] | None = None, ) -> dict[str, list[dict[str, Any]]]: def simplify(row: dict[str, Any]) -> dict[str, Any]: simplified = { "row_id": row["row_id"], "row_text": row["row_text"], "dominant_box_id": row["dominant_box_id"], "dominant_coverage": row["dominant_coverage"], "touched_box_ids": row["touched_box_ids"], "candidate_boxes": row["per_box_coverages"][:3], } if row["status"] == "no_box": simplified["single_uncovered_word_against_dominant_box"] = row[ "single_uncovered_word_against_dominant_box" ] simplified["uncovered_words_against_dominant_box"] = row[ "uncovered_words_against_dominant_box" ] return simplified multiple_rows = [row for row in details if row["status"] == "multiple_boxes"] no_box_rows = [row for row in details if row["status"] == "no_box"] detected_empty_rows = [row for row in details if row.get("is_detected_empty")] multiple_examples = sorted( multiple_rows, key=lambda row: ( -len(row["touched_box_ids"]), row["dominant_coverage"], row["row_id"], ), )[:example_count] no_box_examples = select_no_box_failure_examples(no_box_rows, example_count) high_impact_examples = sorted( [ region for region in ocr_regions if region["text_metrics"]["char_edit_distance"] > 0 ], key=lambda region: ( -region["text_metrics"]["char_edit_distance"], region["region_id"], ), )[:HIGH_IMPACT_REGION_EXAMPLE_COUNT] normal_single_box_error_examples = sorted( [ region for region in ocr_regions if ( region.get("normal_single_box_region") and region["text_metrics"]["char_edit_distance"] > 0 ) ], key=lambda region: ( -region["text_metrics"]["cer"], -region["text_metrics"]["char_edit_distance"], region["region_id"], ), )[:example_count] return { "multiple_boxes": [simplify(row) for row in multiple_examples], "no_box": [simplify(row) for row in no_box_examples], "detected_empty": [simplify(row) for row in detected_empty_rows[:example_count]], "split_line": ( [] if split_line_groups is None else split_line_groups[:example_count] ), "high_impact_regions": [ summarize_region_example(region, include_error_stats=True) for region in high_impact_examples ], "normal_single_box_region_errors": [ summarize_region_example(region, include_error_stats=True) for region in normal_single_box_error_examples ], } def evaluate_rows( predicted_rows: list[PredictedRow], annotation_boxes: list[AnnotationBox], coverage_threshold: float, failure_example_count: int, hide_zero_cer_details: bool = True, filters: str | list[str] | tuple[str, ...] | None = None, unit_level: str = "word", ) -> dict[str, Any]: filter_names = parse_filter_names(filters) should_exclude_box = should_exclude_box_for_filters(filter_names) grouping = group_words_into_regions( predicted_rows=predicted_rows, annotation_boxes=annotation_boxes, coverage_threshold=coverage_threshold, unit_level=unit_level, ) details = grouping["assignments"] ignored_rows = grouping["watermark_rows"] split_line_groups = grouping["split_line_groups"] best_coverages = grouping["best_coverages"] counts = grouping["counts"] total_rows = len(details) predicted_rows_by_id = {row.row_id: row for row in predicted_rows} total_detected_word_boxes = sum(len(row.words) for row in predicted_rows) missing_text_boxes = count_empty_words_in_non_empty_boxes( predicted_rows, annotation_boxes, ) gt_text_boxes = [box for box in annotation_boxes if box.has_transcription] gt_box_count = len(gt_text_boxes) gt_char_count = sum(len(box.text) for box in gt_text_boxes) ocr_regions, ocr_region_summary = build_ocr_region_reports( details=details, annotation_boxes=annotation_boxes, predicted_rows_by_id=predicted_rows_by_id, should_exclude_box=should_exclude_box, ) filter_report = ( build_region_filter_report(annotation_boxes, filter_names) if filter_names else None ) summary = { "unit_level": unit_level, "total_rows": total_rows, "ignored_watermark_rows": len(ignored_rows), "exactly_one_box": counts["exactly_one_box"], "exactly_one_box_rate": safe_rate(counts["exactly_one_box"], total_rows), "multiple_boxes": counts["multiple_boxes"], "multiple_boxes_rate": safe_rate(counts["multiple_boxes"], total_rows), "no_box": counts["no_box"], "no_box_rate": safe_rate(counts["no_box"], total_rows), "detected_empty": counts["detected_empty"], "split_line": len(split_line_groups), "split_line_rate": safe_rate(len(split_line_groups), total_rows), "split_line_rows": counts["split_line"], "split_line_rows_rate": safe_rate(counts["split_line"], total_rows), "mean_best_coverage": safe_mean(best_coverages), "gt_box_count": gt_box_count, "gt_char_count": gt_char_count, "ocr_region_count": ocr_region_summary["ocr_region_count"], "multibox_region_count": ocr_region_summary["multibox_region_count"], "ocr_region_mean_cer": ocr_region_summary["mean_cer"], "ocr_region_gt_char_count": ocr_region_summary["gt_char_count"], "ocr_region_char_edit_distance": ocr_region_summary["char_edit_distance"], "ocr_region_char_edit_distance_lowercase": ocr_region_summary["char_edit_distance_lowercase"], "ocr_region_cer": ocr_region_summary["cer"], "ocr_region_cer_lowercase": ocr_region_summary["cer_lowercase"], "ocr_region_cer_buckets": ocr_region_summary["cer_buckets"], "normal_single_box_region": ocr_region_summary["normal_single_box_region"], "missing_text_boxes": missing_text_boxes, "total_detected_word_boxes": total_detected_word_boxes, "missing_text_box_rate": safe_rate( missing_text_boxes, total_detected_word_boxes, ), } if filter_report is not None: summary["filter"] = summarize_region_filter_report(filter_report) failure_examples = build_failure_examples( details, ocr_regions, failure_example_count, split_line_groups, ) report = { "summary": summary, "ocr_regions": ( nonzero_cer_records(ocr_regions) if hide_zero_cer_details else ocr_regions ), "failure_examples": failure_examples, "split_line_groups": split_line_groups, "ignored_rows": ignored_rows, "rows": details, "excluded_labels": report_excluded_labels(), } if filter_report is not None: report["filter"] = filter_report report["filtered_text_boxes"] = filter_report["excluded_boxes"] return report def main() -> None: args = parse_args() annotation_boxes = load_annotation_boxes(args.annotations_json) predicted_rows = load_predicted_rows(args.predictions_csv, unit_level=args.unit_level) try: filters = parse_filter_names(args.filters) except ValueError as error: raise SystemExit(str(error)) from error 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=True, filters=filters, unit_level=args.unit_level, ) print( json.dumps( { "summary": report["summary"], "ocr_regions": report["ocr_regions"], }, ensure_ascii=False, indent=2, ) ) if args.output: args.output.write_text( json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8" ) if __name__ == "__main__": main()