"""Group predicted word rows into annotation box regions using spatial coverage. Entry point for the box-grouping stage. Downstream stages (evaluation) call :func:`group_words_into_regions` and receive a plain dict describing which predicted rows belong to which annotation box, without any text-metric logic. """ from __future__ import annotations from typing import Any from loading import watermark_row_ids as _watermark_row_ids_from_loading from models import AnnotationBox, PredictedRow, annotation_box_type from spatial import ( best_box_detail_for_multiple_row, box_detail_meets_single_box_threshold, classify_row, detect_split_line_pair, edge_words_in_box, local_boxes_share_line, non_empty_words, row_box, row_location_coverage, row_overlap_coverage, row_sequence_prefix, single_uncovered_word_against_box, sorted_row_words, split_line_row_order_key, treat_multiple_row_as_single_box, uncovered_words_against_box, word_coverage_in_box, ) def _watermark_row_ids(predicted_rows: list[PredictedRow]) -> set[str]: return _watermark_row_ids_from_loading(predicted_rows, local_boxes_share_line) def _apply_split_line_failures( details: list[dict[str, Any]], annotation_box_by_id: dict[str, AnnotationBox], predicted_rows_by_id: dict[str, PredictedRow], ) -> list[dict[str, Any]]: """Detect split-column row pairs and mark them as split_line in *details* (mutates in place).""" row_indexes_by_box: dict[str, list[int]] = {} row_by_id: dict[str, dict[str, Any]] = {row["row_id"]: row for row in details} for index, row in enumerate(details): row["split_line_group_id"] = None row["split_line_group_row_ids"] = [] row["split_line_group_size"] = 0 assigned_box_id = row.get("assigned_box_id") or row["dominant_box_id"] if row["status"] != "exactly_one_box" or not assigned_box_id: continue row_indexes_by_box.setdefault(assigned_box_id, []).append(index) split_line_pairs_by_box: dict[str, list[dict[str, Any]]] = {} for box_id, row_indexes in row_indexes_by_box.items(): annotation_box = annotation_box_by_id[box_id] prefix_row_counts: dict[str, int] = {} for row_index in row_indexes: sequence_prefix = row_sequence_prefix(details[row_index]["row_id"]) prefix_row_counts[sequence_prefix] = ( prefix_row_counts.get(sequence_prefix, 0) + 1 ) for left_position, left_index in enumerate(row_indexes): left_row = details[left_index] left_predicted_row = predicted_rows_by_id[left_row["row_id"]] for right_index in row_indexes[left_position + 1:]: right_row = details[right_index] right_predicted_row = predicted_rows_by_id[right_row["row_id"]] left_prefix = row_sequence_prefix(left_row["row_id"]) right_prefix = row_sequence_prefix(right_row["row_id"]) if left_prefix != right_prefix and ( prefix_row_counts.get(left_prefix, 0) > 1 or prefix_row_counts.get(right_prefix, 0) > 1 ): continue left_first_word, _ = edge_words_in_box(left_predicted_row, annotation_box) right_first_word, _ = edge_words_in_box(right_predicted_row, annotation_box) if left_first_word is None or right_first_word is None: continue if left_first_word["local_box"].x_min <= right_first_word["local_box"].x_min: ordered_left_row = left_row ordered_right_row = right_row ordered_left_predicted_row = left_predicted_row ordered_right_predicted_row = right_predicted_row else: ordered_left_row = right_row ordered_right_row = left_row ordered_left_predicted_row = right_predicted_row ordered_right_predicted_row = left_predicted_row pair = detect_split_line_pair( ordered_left_row, ordered_right_row, ordered_left_predicted_row, ordered_right_predicted_row, annotation_box, ) if pair is None: continue split_line_pairs_by_box.setdefault(box_id, []).append(pair) split_line_groups: list[dict[str, Any]] = [] for box_id, box_pairs in split_line_pairs_by_box.items(): adjacency: dict[str, set[str]] = {} for pair in box_pairs: left_row_id = pair["left_row_id"] right_row_id = pair["right_row_id"] adjacency.setdefault(left_row_id, set()).add(right_row_id) adjacency.setdefault(right_row_id, set()).add(left_row_id) annotation_box = annotation_box_by_id[box_id] visited: set[str] = set() for start_row_id in sorted(adjacency): if start_row_id in visited: continue stack = [start_row_id] component_row_ids: list[str] = [] while stack: current_row_id = stack.pop() if current_row_id in visited: continue visited.add(current_row_id) component_row_ids.append(current_row_id) stack.extend(sorted(adjacency.get(current_row_id, ()))) if len(component_row_ids) < 2: continue ordered_row_ids = sorted( component_row_ids, key=lambda row_id: split_line_row_order_key( predicted_rows_by_id[row_id], annotation_box, ), ) group_id = f"{box_id}:{ordered_row_ids[0]}" split_line_groups.append( { "group_id": group_id, "box_id": box_id, "box_text": annotation_box.text, "fragment_count": len(ordered_row_ids), "row_ids": ordered_row_ids, "row_texts": [ row_by_id[row_id]["row_text"] for row_id in ordered_row_ids ], } ) for row_id in ordered_row_ids: row = row_by_id[row_id] row["split_line_group_id"] = group_id row["split_line_group_row_ids"] = [ other_row_id for other_row_id in ordered_row_ids if other_row_id != row_id ] row["split_line_group_size"] = len(ordered_row_ids) row["status"] = "split_line" return sorted( split_line_groups, key=lambda group: (group["box_id"], group["row_ids"][0]), ) def group_words_into_regions( predicted_rows: list[PredictedRow], annotation_boxes: list[AnnotationBox], *, coverage_threshold: float = 1.0, unit_level: str = "word", ) -> dict[str, Any]: """Assign predicted word rows to annotation box regions using spatial coverage. Parameters ---------- predicted_rows: Word-box rows produced by ``loading.load_predicted_rows``. Each row groups word bounding boxes under a common ``row_id``. annotation_boxes: Ground-truth annotation boxes produced by ``loading.load_annotation_boxes``. coverage_threshold: Fraction of words in a row that must lie inside a box to count as a full match. Default ``1.0`` (all words must fit). unit_level: Granularity of the predicted rows: ``"word"`` (each row is a single word) or ``"line"`` (each row is a full text line). Does not affect the spatial algorithm — recorded in the return value so downstream reports can surface it. Returns ------- dict with: ``assignments`` List of row-assignment dicts, one per non-watermark predicted row. Each entry contains ``row_id``, ``status`` (``exactly_one_box`` / ``multiple_boxes`` / ``no_box`` / ``split_line``), ``assigned_box_id``, ``dominant_box_id``, ``dominant_coverage``, ``touched_box_ids``, ``per_box_coverages``, and auxiliary fields. ``watermark_rows`` List of dicts describing rows that were identified as watermarks and excluded from ``assignments``. ``split_line_groups`` List of split-line group dicts describing rows that form split-column fragments of the same annotation-box line. ``best_coverages`` Per-row dominant coverage values (one float per assignment). ``counts`` Dict with keys ``exactly_one_box``, ``multiple_boxes``, ``no_box``, ``split_line`` counting rows by final status. """ annotation_box_by_id = {box.box_id: box for box in annotation_boxes} predicted_rows_by_id = {row.row_id: row for row in predicted_rows} ignored_watermark_row_ids = _watermark_row_ids(predicted_rows) best_coverages: list[float] = [] details: list[dict[str, Any]] = [] ignored_rows: list[dict[str, Any]] = [] for predicted_row in predicted_rows: if predicted_row.row_id in ignored_watermark_row_ids: ignored_rows.append( { "row_id": predicted_row.row_id, "row_text": predicted_row.text, "words": [word.text for word in predicted_row.words], "reason": "watermark", } ) continue touched_box_ids: list[str] = [] all_word_box_ids: list[str] = [] per_box_details: list[dict[str, Any]] = [] relevant_words = non_empty_words(predicted_row) ordered_words = sorted_row_words( PredictedRow(predicted_row.row_id, relevant_words) ) for annotation_box in annotation_boxes: word_coverages = [ word_coverage_in_box(word, annotation_box) for word in relevant_words ] matched_word_count = sum( coverage >= coverage_threshold for coverage in word_coverages ) location_coverage = row_location_coverage(predicted_row, annotation_box) overlap_coverage = row_overlap_coverage(predicted_row, annotation_box) covered_word_indexes = [ index for index, word in enumerate(ordered_words) if annotation_box.contains_point(word.center[0], word.center[1]) ] first_word_index = ( covered_word_indexes[0] if covered_word_indexes else len(ordered_words) ) leading_word_count = 0 for expected_index, actual_index in enumerate(covered_word_indexes): if actual_index != expected_index: break leading_word_count += 1 if matched_word_count > 0: touched_box_ids.append(annotation_box.box_id) if relevant_words and location_coverage >= coverage_threshold: all_word_box_ids.append(annotation_box.box_id) if location_coverage > 0 or overlap_coverage > 0: per_box_details.append( { "box_id": annotation_box.box_id, "box_type": annotation_box_type(annotation_box), "labels": list(annotation_box.labels), "box_text": annotation_box.text, "coverage": round(location_coverage, 6), "overlap_coverage": round(overlap_coverage, 6), "matched_words": matched_word_count, "total_words": len(relevant_words), "first_word_index": first_word_index, "leading_word_count": leading_word_count, } ) per_box_details.sort( key=lambda item: (item["coverage"], item["overlap_coverage"]), reverse=True, ) dominant = per_box_details[0] if per_box_details else None dominant_coverage = dominant["coverage"] if dominant else 0.0 dominant_annotation_box = ( annotation_box_by_id[dominant["box_id"]] if dominant is not None else None ) status = classify_row(touched_box_ids, all_word_box_ids) raw_status = status dominant_box_id = dominant["box_id"] if dominant else None dominant_coverage_for_report = dominant_coverage assigned_box_id = dominant_box_id use_full_row_for_assigned_box = False is_detected_empty = False if raw_status == "multiple_boxes": assigned_box_detail = best_box_detail_for_multiple_row(per_box_details) assigned_box_id = ( assigned_box_detail["box_id"] if assigned_box_detail is not None else assigned_box_id ) use_full_row_for_assigned_box = assigned_box_id is not None if treat_multiple_row_as_single_box(per_box_details): status = "exactly_one_box" dominant_box_id = assigned_box_id if assigned_box_detail is not None: dominant_coverage_for_report = assigned_box_detail["coverage"] elif len(touched_box_ids) == 1 and box_detail_meets_single_box_threshold(dominant): status = "exactly_one_box" assigned_box_id = dominant_box_id elif not relevant_words: # All words are empty (detected but unreadable): check if any empty word # center falls inside a GT box with non-empty text. empty_words_per_box: dict[str, int] = {} for word in predicted_row.words: for annotation_box in annotation_boxes: if not (annotation_box.has_transcription and annotation_box.text.strip()): continue if annotation_box.contains_point(word.center[0], word.center[1]): empty_words_per_box[annotation_box.box_id] = ( empty_words_per_box.get(annotation_box.box_id, 0) + 1 ) if empty_words_per_box: detected_empty_box_ids = sorted( empty_words_per_box, key=lambda bid: (-empty_words_per_box[bid], bid), ) for box_id in detected_empty_box_ids: if box_id not in touched_box_ids: touched_box_ids.append(box_id) status = "exactly_one_box" is_detected_empty = True dominant_box_id = detected_empty_box_ids[0] dominant_coverage_for_report = 0.0 assigned_box_id = detected_empty_box_ids[0] use_full_row_for_assigned_box = False uncovered_words = ( uncovered_words_against_box(predicted_row, dominant_annotation_box) if status == "no_box" and dominant_annotation_box is not None else [] ) single_uncovered_word = ( single_uncovered_word_against_box(predicted_row, dominant_annotation_box) if status == "no_box" and dominant_annotation_box is not None else None ) best_coverages.append(dominant_coverage) details.append( { "row_id": predicted_row.row_id, "status": status, "is_detected_empty": is_detected_empty, "touched_box_ids": touched_box_ids, "all_word_box_ids": all_word_box_ids, "dominant_box_id": dominant_box_id, "main_box_id": assigned_box_id, "assigned_box_id": assigned_box_id, "use_full_row_for_assigned_box": use_full_row_for_assigned_box, "dominant_coverage": dominant_coverage_for_report, "row_box": [ round(value, 3) for value in row_box(predicted_row).to_list() ], "row_text": predicted_row.text, "words": [word.text for word in predicted_row.words], "single_uncovered_word_against_dominant_box": single_uncovered_word, "uncovered_words_against_dominant_box": uncovered_words, "per_box_coverages": per_box_details, } ) split_line_groups = _apply_split_line_failures( details=details, annotation_box_by_id=annotation_box_by_id, predicted_rows_by_id=predicted_rows_by_id, ) counts = { "exactly_one_box": sum(row["status"] == "exactly_one_box" for row in details), "multiple_boxes": sum(row["status"] == "multiple_boxes" for row in details), "no_box": sum(row["status"] == "no_box" for row in details), "split_line": sum(row["status"] == "split_line" for row in details), "detected_empty": sum(row.get("is_detected_empty", False) for row in details), } return { "assignments": details, "watermark_rows": ignored_rows, "split_line_groups": split_line_groups, "best_coverages": best_coverages, "counts": counts, "unit_level": unit_level, }