| """Spatial utilities: box merging, word placement, reading order, split-line detection.""" |
|
|
| from __future__ import annotations |
|
|
| import math |
| from typing import Any, Sequence |
|
|
| from geometry import Box, polygon_bounds |
| from models import Word, AnnotationBox, PredictedRow |
|
|
|
|
| SPLIT_LINE_VERTICAL_OVERLAP_THRESHOLD = 0.5 |
| SPLIT_LINE_HORIZONTAL_OVERLAP_TOLERANCE_RATIO = 0.25 |
| SPLIT_LINE_MAX_GAP_HEIGHT_MULTIPLIER = 2.0 |
| LINE_END_HYPHENS = "-֊‐‑‒–—" |
| MULTI_BOX_SINGLE_COLUMN_LOCATION_THRESHOLD = 0.8 |
| MULTI_BOX_SINGLE_COLUMN_OVERLAP_THRESHOLD = 0.8 |
| MULTI_BOX_OVERLAP_TIE_TOLERANCE = 0.05 |
| MULTI_BOX_BEGINNING_BOX_OVERLAP_TOLERANCE = 0.25 |
| MULTI_BOX_BEGINNING_BOX_MIN_LEADING_WORDS = 2 |
| MULTI_BOX_BEGINNING_BOX_MIN_COVERAGE = 0.35 |
| BOX_LINE_VERTICAL_OVERLAP_THRESHOLD = 0.60 |
| READING_ORDER_ROW_OVERLAP_THRESHOLD = 0.5 |
| READING_ORDER_COLUMN_OVERLAP_THRESHOLD = 0.5 |
|
|
|
|
| def merge_boxes(boxes: list[Box]) -> Box: |
| return Box( |
| x_min=min(box.x_min for box in boxes), |
| y_min=min(box.y_min for box in boxes), |
| x_max=max(box.x_max for box in boxes), |
| y_max=max(box.y_max for box in boxes), |
| ) |
|
|
|
|
| def row_box(predicted_row: PredictedRow) -> Box: |
| return merge_boxes([word.box for word in predicted_row.words]) |
|
|
|
|
| def interval_overlap( |
| start_a: float, end_a: float, start_b: float, end_b: float |
| ) -> float: |
| return max(0.0, min(end_a, end_b) - max(start_a, start_b)) |
|
|
|
|
| def point_to_box_local_coordinates( |
| point: tuple[float, float], |
| annotation_box: AnnotationBox, |
| ) -> tuple[float, float]: |
| origin_x = annotation_box.rect.x_min |
| origin_y = annotation_box.rect.y_min |
| rotation_radians = math.radians(annotation_box.rotation) |
| cos_theta = math.cos(rotation_radians) |
| sin_theta = math.sin(rotation_radians) |
| delta_x = point[0] - origin_x |
| delta_y = point[1] - origin_y |
| return ( |
| delta_x * cos_theta + delta_y * sin_theta, |
| -delta_x * sin_theta + delta_y * cos_theta, |
| ) |
|
|
|
|
| def box_to_local_bounds(box: Box, annotation_box: AnnotationBox) -> Box: |
| local_points = [ |
| point_to_box_local_coordinates(point, annotation_box) |
| for point in box.to_polygon() |
| ] |
| return polygon_bounds(local_points) |
|
|
|
|
| def word_local_center( |
| word: Word, annotation_box: AnnotationBox |
| ) -> tuple[float, float]: |
| return point_to_box_local_coordinates(word.center, annotation_box) |
|
|
|
|
| def local_box_to_list(box: Box) -> list[float]: |
| return [ |
| round(box.x_min, 3), |
| round(box.y_min, 3), |
| round(box.x_max, 3), |
| round(box.y_max, 3), |
| ] |
|
|
|
|
| def rounded_box(box: Box) -> list[float]: |
| return [round(value, 3) for value in box.to_list()] |
|
|
|
|
| def report_box(box_values: list[float]) -> Box: |
| return Box( |
| x_min=float(box_values[0]), |
| y_min=float(box_values[1]), |
| x_max=float(box_values[2]), |
| y_max=float(box_values[3]), |
| ) |
|
|
|
|
| def edge_words_in_box( |
| predicted_row: PredictedRow, |
| annotation_box: AnnotationBox, |
| ) -> tuple[dict[str, Any] | None, dict[str, Any] | None]: |
| edge_words: list[dict[str, Any]] = [] |
|
|
| for index, word in enumerate(predicted_row.words): |
| local_box = box_to_local_bounds(word.box, annotation_box) |
| edge_words.append( |
| { |
| "index": index, |
| "text": word.text, |
| "global_box": [round(value, 3) for value in word.box.to_list()], |
| "local_box": local_box, |
| } |
| ) |
|
|
| if not edge_words: |
| return (None, None) |
|
|
| first_word = min( |
| edge_words, key=lambda item: (item["local_box"].x_min, item["index"]) |
| ) |
| last_word = max( |
| edge_words, key=lambda item: (item["local_box"].x_max, -item["index"]) |
| ) |
| return (first_word, last_word) |
|
|
|
|
| def word_coverage_in_box(word: Word, annotation_box: AnnotationBox) -> float: |
| center_x, center_y = word.center |
| return 1.0 if annotation_box.contains_point(center_x, center_y) else 0.0 |
|
|
|
|
| def word_overlap_coverage_in_box(word: Word, annotation_box: AnnotationBox) -> float: |
| if word.box.area <= 0: |
| return 0.0 |
| overlap_area = annotation_box.overlap_area_with_box(word.box) |
| return overlap_area / word.box.area |
|
|
|
|
| def word_non_overlapping_area(word: Word, annotation_box: AnnotationBox) -> float: |
| overlap_area = annotation_box.overlap_area_with_box(word.box) |
| return max(0.0, word.box.area - overlap_area) |
|
|
|
|
| def non_empty_words(predicted_row: PredictedRow) -> list[Word]: |
| return [word for word in predicted_row.words if word.text.strip()] |
|
|
|
|
| def uncovered_words_against_box( |
| predicted_row: PredictedRow, |
| annotation_box: AnnotationBox, |
| ) -> list[dict[str, Any]]: |
| uncovered_words: list[dict[str, Any]] = [] |
|
|
| for word in non_empty_words(predicted_row): |
| if word_coverage_in_box(word, annotation_box) >= 1.0: |
| continue |
|
|
| non_overlapping_area = word_non_overlapping_area(word, annotation_box) |
| uncovered_words.append( |
| { |
| "text": word.text, |
| "word_box": [round(value, 3) for value in word.box.to_list()], |
| "non_overlapping_area": round(non_overlapping_area, 6), |
| "non_overlapping_fraction": ( |
| round(non_overlapping_area / word.box.area, 6) |
| if word.box.area > 0 |
| else 0.0 |
| ), |
| "overlap_coverage": round( |
| word_overlap_coverage_in_box(word, annotation_box), 6 |
| ), |
| } |
| ) |
|
|
| return uncovered_words |
|
|
|
|
| def single_uncovered_word_against_box( |
| predicted_row: PredictedRow, |
| annotation_box: AnnotationBox, |
| ) -> dict[str, Any] | None: |
| uncovered_words = uncovered_words_against_box(predicted_row, annotation_box) |
| if len(uncovered_words) != 1: |
| return None |
| return uncovered_words[0] |
|
|
|
|
| def row_location_coverage( |
| predicted_row: PredictedRow, annotation_box: AnnotationBox |
| ) -> float: |
| words = non_empty_words(predicted_row) |
| total_words = len(words) |
| if total_words == 0: |
| return 0.0 |
| matched_words = sum(word_coverage_in_box(word, annotation_box) for word in words) |
| return matched_words / total_words |
|
|
|
|
| def row_overlap_coverage( |
| predicted_row: PredictedRow, annotation_box: AnnotationBox |
| ) -> float: |
| words = non_empty_words(predicted_row) |
| total_area = sum(word.box.area for word in words) |
| if total_area <= 0: |
| return 0.0 |
|
|
| covered_area = 0.0 |
| for word in words: |
| covered_area += annotation_box.overlap_area_with_box(word.box) |
| return covered_area / total_area |
|
|
|
|
| def classify_row(touched_box_ids: list[str], all_word_box_ids: list[str]) -> str: |
| if not touched_box_ids: |
| return "no_box" |
| if len(all_word_box_ids) == 1 and len(touched_box_ids) == 1: |
| return "exactly_one_box" |
| if len(touched_box_ids) > 1 or len(all_word_box_ids) > 1: |
| return "multiple_boxes" |
| return "no_box" |
|
|
|
|
| def best_box_detail_for_multiple_row( |
| per_box_details: list[dict[str, Any]], |
| ) -> dict[str, Any] | None: |
| if not per_box_details: |
| return None |
|
|
| strongest_match = max( |
| per_box_details, |
| key=lambda item: ( |
| item["overlap_coverage"], |
| item["coverage"], |
| item["matched_words"], |
| -item["first_word_index"], |
| item["leading_word_count"], |
| item["box_id"], |
| ), |
| ) |
| beginning_match = min( |
| per_box_details, |
| key=lambda item: ( |
| item["first_word_index"], |
| -item["leading_word_count"], |
| -item["coverage"], |
| -item["overlap_coverage"], |
| item["box_id"], |
| ), |
| ) |
| if ( |
| beginning_match["first_word_index"] == 0 |
| and ( |
| beginning_match["leading_word_count"] |
| >= MULTI_BOX_BEGINNING_BOX_MIN_LEADING_WORDS |
| or beginning_match["coverage"] >= MULTI_BOX_BEGINNING_BOX_MIN_COVERAGE |
| ) |
| and strongest_match["overlap_coverage"] |
| - beginning_match["overlap_coverage"] |
| <= MULTI_BOX_BEGINNING_BOX_OVERLAP_TOLERANCE |
| ): |
| return beginning_match |
|
|
| tied_matches = [ |
| item |
| for item in per_box_details |
| if strongest_match["overlap_coverage"] - item["overlap_coverage"] |
| <= MULTI_BOX_OVERLAP_TIE_TOLERANCE |
| ] |
| return max( |
| tied_matches, |
| key=lambda item: ( |
| item["leading_word_count"], |
| -item["first_word_index"], |
| item["matched_words"], |
| item["coverage"], |
| item["overlap_coverage"], |
| item["box_id"], |
| ), |
| ) |
|
|
|
|
| def box_detail_meets_single_box_threshold( |
| box_detail: dict[str, Any] | None, |
| ) -> bool: |
| if box_detail is None: |
| return False |
| return ( |
| box_detail["coverage"] >= MULTI_BOX_SINGLE_COLUMN_LOCATION_THRESHOLD |
| or box_detail["overlap_coverage"] >= MULTI_BOX_SINGLE_COLUMN_OVERLAP_THRESHOLD |
| ) |
|
|
|
|
| def treat_multiple_row_as_single_box(per_box_details: list[dict[str, Any]]) -> bool: |
| best_match = best_box_detail_for_multiple_row(per_box_details) |
| return box_detail_meets_single_box_threshold(best_match) |
|
|
|
|
| def _fix_armenian_yev_at_join(prev: str, next_line: str) -> tuple[str, str]: |
| """Replace ե-|վ split across a hyphenation boundary with the ligature և.""" |
| if prev.endswith("ե") and next_line.startswith("վ"): |
| prev = prev[:-1] + "և" |
| next_line = next_line[1:] |
| return prev, next_line |
|
|
|
|
| def join_box_lines_with_hyphenation( |
| line_texts: list[str], |
| ) -> tuple[str, frozenset[int]]: |
| """Join lines, stripping line-end hyphens. |
| |
| Returns (text, hyphen_join_word_indices) where hyphen_join_word_indices is |
| the set of word indices (in the space-normalised result) whose text was |
| formed by merging across a hyphen boundary. Callers that only need the |
| text can unpack with ``text, _ = join_box_lines_with_hyphenation(...)``. |
| """ |
| merged_lines: list[str] = [] |
| words_before_current: int = 0 |
| hyphen_join_word_indices: set[int] = set() |
|
|
| for line_text in line_texts: |
| normalized_line = normalize_whitespace(line_text) |
| if not normalized_line: |
| continue |
|
|
| if merged_lines and merged_lines[-1].rstrip().endswith( |
| tuple(LINE_END_HYPHENS) |
| ): |
| prev = merged_lines[-1].rstrip()[:-1] |
| next_line = normalized_line.lstrip() |
|
|
| prev, next_line = _fix_armenian_yev_at_join(prev, next_line) |
|
|
| words_in_prev = len(prev.split()) |
| if words_in_prev > 0: |
| hyphen_join_word_indices.add(words_before_current + words_in_prev - 1) |
|
|
| merged_lines[-1] = prev + next_line |
| else: |
| if merged_lines: |
| words_before_current += len(merged_lines[-1].split()) |
| merged_lines.append(normalized_line) |
|
|
| return "\n".join(merged_lines), frozenset(hyphen_join_word_indices) |
|
|
|
|
| def local_boxes_share_line(left: Box, right: Box) -> bool: |
| min_height = min(left.height, right.height) |
| if min_height <= 0: |
| return False |
| vertical_overlap = interval_overlap( |
| left.y_min, left.y_max, right.y_min, right.y_max |
| ) |
| vertical_overlap_ratio = vertical_overlap / min_height |
| return vertical_overlap_ratio >= BOX_LINE_VERTICAL_OVERLAP_THRESHOLD |
|
|
|
|
| def horizontal_overlap_ratio(left: Box, right: Box) -> float: |
| min_width = min(left.width, right.width) |
| if min_width <= 0: |
| return 0.0 |
| return ( |
| interval_overlap(left.x_min, left.x_max, right.x_min, right.x_max) |
| / min_width |
| ) |
|
|
|
|
| def row_sequence_prefix(row_id: str) -> str: |
| parts = row_id.split("_", 1) |
| return parts[0] |
|
|
|
|
| def boxes_share_reading_row(left: Box, right: Box) -> bool: |
| min_height = min(left.height, right.height) |
| if min_height <= 0: |
| return False |
| vertical_overlap = interval_overlap( |
| left.y_min, left.y_max, right.y_min, right.y_max |
| ) |
| return (vertical_overlap / min_height) >= READING_ORDER_ROW_OVERLAP_THRESHOLD |
|
|
|
|
| def boxes_share_reading_column(left: Box, right: Box) -> bool: |
| min_width = min(left.width, right.width) |
| if min_width <= 0: |
| return False |
| horizontal_overlap = interval_overlap( |
| left.x_min, left.x_max, right.x_min, right.x_max |
| ) |
| return ( |
| horizontal_overlap / min_width |
| ) >= READING_ORDER_COLUMN_OVERLAP_THRESHOLD |
|
|
|
|
| def _group_items_spatially( |
| items: Sequence[Any], |
| box_getter: Any, |
| primary_axis: str, |
| ) -> list[list[Any]]: |
| ltr = primary_axis == "x" |
| shares_band = boxes_share_reading_column if ltr else boxes_share_reading_row |
| primary_sort = ( |
| (lambda b: (b.x_min, b.y_min, b.x_max, b.y_max)) |
| if ltr |
| else (lambda b: (b.y_min, b.x_min, b.y_max, b.x_max)) |
| ) |
| secondary_sort = ( |
| (lambda b: (b.y_min, b.x_min, b.y_max, b.x_max)) |
| if ltr |
| else (lambda b: (b.x_min, b.x_max, b.y_min, b.y_max)) |
| ) |
| center = ( |
| (lambda b: (b.x_min + b.x_max) / 2.0) |
| if ltr |
| else (lambda b: (b.y_min + b.y_max) / 2.0) |
| ) |
|
|
| ordered_items = sorted(items, key=lambda item: primary_sort(box_getter(item))) |
| groups: list[dict[str, Any]] = [] |
| for item in ordered_items: |
| item_box = box_getter(item) |
| best_group: dict[str, Any] | None = None |
| best_distance = float("inf") |
| for group in groups: |
| if not shares_band(group["box"], item_box): |
| continue |
| distance = abs(center(group["box"]) - center(item_box)) |
| if distance < best_distance: |
| best_distance = distance |
| best_group = group |
| if best_group is None: |
| groups.append({"items": [item], "box": item_box}) |
| else: |
| best_group["items"].append(item) |
| best_group["box"] = merge_boxes([best_group["box"], item_box]) |
|
|
| return [ |
| sorted(g["items"], key=lambda item: secondary_sort(box_getter(item))) |
| for g in sorted(groups, key=lambda g: primary_sort(g["box"])) |
| ] |
|
|
|
|
| def group_items_left_to_right_top_to_bottom( |
| items: Sequence[Any], box_getter: Any |
| ) -> list[list[Any]]: |
| return _group_items_spatially(items, box_getter, "x") |
|
|
|
|
| def flatten_text_units(text_units: list[str]) -> str: |
| flattened_units: list[str] = [] |
| for text_unit in text_units: |
| unit_lines = split_text_lines(text_unit) |
| if not unit_lines: |
| continue |
| text, _ = join_box_lines_with_hyphenation(unit_lines) |
| flattened_units.append(text) |
| return "\n".join(flattened_units) |
|
|
|
|
| def detect_split_line_pair( |
| left_row: dict[str, Any], |
| right_row: dict[str, Any], |
| left_predicted_row: PredictedRow, |
| right_predicted_row: PredictedRow, |
| annotation_box: AnnotationBox, |
| ) -> dict[str, Any] | None: |
| left_first_word, left_last_word = edge_words_in_box( |
| left_predicted_row, annotation_box |
| ) |
| right_first_word, right_last_word = edge_words_in_box( |
| right_predicted_row, annotation_box |
| ) |
| if ( |
| left_first_word is None |
| or left_last_word is None |
| or right_first_word is None |
| or right_last_word is None |
| ): |
| return None |
|
|
| left_last_local_box = left_last_word["local_box"] |
| right_first_local_box = right_first_word["local_box"] |
|
|
| vertical_overlap = interval_overlap( |
| left_last_local_box.y_min, |
| left_last_local_box.y_max, |
| right_first_local_box.y_min, |
| right_first_local_box.y_max, |
| ) |
| min_height = min(left_last_local_box.height, right_first_local_box.height) |
| if min_height <= 0: |
| return None |
|
|
| vertical_overlap_ratio = vertical_overlap / min_height |
| if vertical_overlap_ratio < SPLIT_LINE_VERTICAL_OVERLAP_THRESHOLD: |
| return None |
|
|
| horizontal_gap = right_first_local_box.x_min - left_last_local_box.x_max |
| if horizontal_gap < ( |
| -SPLIT_LINE_HORIZONTAL_OVERLAP_TOLERANCE_RATIO * min_height |
| ): |
| return None |
| if horizontal_gap > SPLIT_LINE_MAX_GAP_HEIGHT_MULTIPLIER * max( |
| left_last_local_box.height, |
| right_first_local_box.height, |
| ): |
| return None |
|
|
| return { |
| "box_id": annotation_box.box_id, |
| "left_row_id": left_row["row_id"], |
| "right_row_id": right_row["row_id"], |
| "horizontal_gap": round(horizontal_gap, 6), |
| "vertical_overlap_ratio": round(vertical_overlap_ratio, 6), |
| "left_row_text": left_row["row_text"], |
| "right_row_text": right_row["row_text"], |
| "left_last_word_text": left_last_word["text"], |
| "right_first_word_text": right_first_word["text"], |
| "left_last_word_box": left_last_word["global_box"], |
| "right_first_word_box": right_first_word["global_box"], |
| "left_last_word_local_box": local_box_to_list(left_last_local_box), |
| "right_first_word_local_box": local_box_to_list(right_first_local_box), |
| } |
|
|
|
|
| def split_line_row_order_key( |
| predicted_row: PredictedRow, |
| annotation_box: AnnotationBox, |
| ) -> tuple[float, float, float, float, str]: |
| if not predicted_row.words: |
| return ( |
| float("inf"), |
| float("inf"), |
| float("inf"), |
| float("inf"), |
| predicted_row.row_id, |
| ) |
| local_bounds = box_to_local_bounds(row_box(predicted_row), annotation_box) |
| return ( |
| local_bounds.x_min, |
| local_bounds.x_max, |
| local_bounds.y_min, |
| local_bounds.y_max, |
| predicted_row.row_id, |
| ) |
|
|
|
|
| def order_words_in_box_context( |
| words: list[Word], annotation_box: AnnotationBox |
| ) -> list[Word]: |
| return sorted( |
| list(words), |
| key=lambda word: ( |
| point_to_box_local_coordinates(word.center, annotation_box)[0], |
| point_to_box_local_coordinates(word.center, annotation_box)[1], |
| word.box.x_min, |
| word.box.y_min, |
| ), |
| ) |
|
|
|
|
| def words_in_box(predicted_row: PredictedRow, annotation_box: AnnotationBox) -> list[Word]: |
| words = [ |
| word |
| for word in predicted_row.words |
| if annotation_box.contains_point(word.center[0], word.center[1]) |
| ] |
| return order_words_in_box_context(words, annotation_box) |
|
|
|
|
| def sorted_row_words(predicted_row: PredictedRow) -> list[Word]: |
| return sorted( |
| predicted_row.words, |
| key=lambda word: ( |
| word.box.y_min, |
| word.box.x_min, |
| word.box.x_max, |
| word.text, |
| ), |
| ) |
|
|
|
|
| def normalize_whitespace(text: str) -> str: |
| return " ".join(text.split()) |
|
|
|
|
| def split_text_lines(text: str) -> list[str]: |
| return [ |
| normalize_whitespace(line) |
| for line in text.splitlines() |
| if normalize_whitespace(line) |
| ] |
|
|