ACoPPer / evaluation_kit /evaluation /prediction.py
Yeva's picture
Extract shared line-grouping/reading-order helper in prediction.py
3cfdd38 verified
Raw
History Blame Contribute Delete
28.2 kB
"""Build predicted text for annotation boxes and OCR regions."""
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 statistics
from typing import Any, Callable
from geometry import Box
from models import Word, AnnotationBox, PredictedRow
from spatial import (
merge_boxes,
normalize_whitespace,
join_box_lines_with_hyphenation,
local_boxes_share_line,
horizontal_overlap_ratio,
interval_overlap,
order_words_in_box_context,
words_in_box,
word_local_center,
box_to_local_bounds,
row_sequence_prefix,
report_box,
rounded_box,
)
SEQUENCE_PREFIX_COLUMN_MIN_VERTICAL_OVERLAP_RATIO = 0.5
SEQUENCE_PREFIX_COLUMN_MAX_HORIZONTAL_OVERLAP_RATIO = 0.5
def build_sequence_prefix_stats(
items: list[dict[str, Any]],
) -> dict[str, dict[str, Any]]:
prefix_stats: dict[str, dict[str, Any]] = {}
for item in items:
sequence_prefix = item["sequence_prefix"]
stats = prefix_stats.setdefault(
sequence_prefix,
{
"min_y": item["start_local_y"],
"min_x": item["start_local_x"],
"max_y": item["local_box"].y_max,
"max_x": item["local_box"].x_max,
"row_ids": set(),
},
)
stats["min_y"] = min(stats["min_y"], item["start_local_y"])
stats["min_x"] = min(stats["min_x"], item["start_local_x"])
stats["max_y"] = max(stats["max_y"], item["local_box"].y_max)
stats["max_x"] = max(stats["max_x"], item["local_box"].x_max)
stats["row_ids"].add(item["row_id"])
for stats in prefix_stats.values():
stats["row_count"] = len(stats["row_ids"])
return prefix_stats
def sequence_prefixes_look_like_columns(
prefix_stats: dict[str, dict[str, Any]],
) -> bool:
multi_row_prefixes = [
prefix for prefix, stats in prefix_stats.items() if stats["row_count"] > 1
]
if len(multi_row_prefixes) < 2:
return False
ordered_prefixes = sorted(
multi_row_prefixes,
key=lambda prefix: (
prefix_stats[prefix]["min_x"],
prefix_stats[prefix]["min_y"],
prefix,
),
)
overlapping_column_pairs = 0
for left_prefix, right_prefix in zip(ordered_prefixes, ordered_prefixes[1:]):
left_stats = prefix_stats[left_prefix]
right_stats = prefix_stats[right_prefix]
left_height = left_stats["max_y"] - left_stats["min_y"]
right_height = right_stats["max_y"] - right_stats["min_y"]
left_width = left_stats["max_x"] - left_stats["min_x"]
right_width = right_stats["max_x"] - right_stats["min_x"]
min_height = min(left_height, right_height)
min_width = min(left_width, right_width)
if min_height <= 0 or min_width <= 0:
continue
vertical_overlap_ratio = (
interval_overlap(
left_stats["min_y"],
left_stats["max_y"],
right_stats["min_y"],
right_stats["max_y"],
)
/ min_height
)
horizontal_overlap_ratio_value = (
interval_overlap(
left_stats["min_x"],
left_stats["max_x"],
right_stats["min_x"],
right_stats["max_x"],
)
/ min_width
)
if (
vertical_overlap_ratio >= SEQUENCE_PREFIX_COLUMN_MIN_VERTICAL_OVERLAP_RATIO
and horizontal_overlap_ratio_value
<= SEQUENCE_PREFIX_COLUMN_MAX_HORIZONTAL_OVERLAP_RATIO
):
overlapping_column_pairs += 1
return overlapping_column_pairs == len(ordered_prefixes) - 1
def sequence_prefix_column_indexes(
prefix_stats: dict[str, dict[str, Any]],
) -> dict[str, int]:
return {
prefix: index
for index, prefix in enumerate(
sorted(
prefix_stats,
key=lambda item: (
prefix_stats[item]["min_x"],
prefix_stats[item]["min_y"],
item,
),
)
)
}
def _build_line_groups(
ordered_items: list[dict[str, Any]],
items_key: str,
prefix_guard: Callable[[str, set[str]], bool],
) -> list[dict[str, Any]]:
"""Group reading-order items into lines by vertical proximity.
`prefix_guard(item_prefix, group_prefixes)` decides whether an item may
join a candidate line group that doesn't yet contain its sequence
prefix; callers pass path-specific rules here (kept faithful to the
single-box and multi-box callers' historically divergent behavior).
"""
line_groups: list[dict[str, Any]] = []
for item in ordered_items:
best_group: dict[str, Any] | None = None
best_vertical_distance = float("inf")
for line_group in line_groups:
if not local_boxes_share_line(
line_group["local_box"], item["local_box"]
):
continue
if any(
horizontal_overlap_ratio(existing["local_box"], item["local_box"])
> 0.35
for existing in line_group[items_key]
):
continue
group_prefixes = {
existing["sequence_prefix"] for existing in line_group[items_key]
}
if not prefix_guard(item["sequence_prefix"], group_prefixes):
continue
line_group_center_y = (
line_group["local_box"].y_min + line_group["local_box"].y_max
) / 2.0
item_center_y = (
item["local_box"].y_min + item["local_box"].y_max
) / 2.0
vertical_distance = abs(line_group_center_y - item_center_y)
if vertical_distance < best_vertical_distance:
best_vertical_distance = vertical_distance
best_group = line_group
if best_group is None:
line_groups.append({items_key: [item], "local_box": item["local_box"]})
continue
best_group[items_key].append(item)
best_group["local_box"] = merge_boxes(
[best_group["local_box"], item["local_box"]]
)
return line_groups
def _order_line_groups(
line_groups: list[dict[str, Any]],
items_key: str,
read_prefixes_as_columns: bool,
prefix_column_indexes: dict[str, int],
fallback_key: Callable[[dict[str, Any]], tuple[float, float]],
) -> list[dict[str, Any]]:
"""Sort line groups into reading order.
`fallback_key(group)` supplies the (y, x) tiebreaker used when the
prefixes don't read as columns; callers pass path-specific formulas
here (kept faithful to the single-box and multi-box callers'
historically divergent behavior).
"""
def line_group_order_key(group: dict[str, Any]) -> tuple[float, ...]:
group_prefixes = {item["sequence_prefix"] for item in group[items_key]}
if read_prefixes_as_columns:
column_index = min(
prefix_column_indexes[prefix] for prefix in group_prefixes
)
return (
float(column_index),
group["local_box"].y_min,
group["local_box"].x_min,
group["local_box"].y_max,
)
fallback_y, fallback_x = fallback_key(group)
return (
fallback_y,
fallback_x,
group["local_box"].y_min,
group["local_box"].x_min,
)
return sorted(line_groups, key=line_group_order_key)
def _group_items_into_ordered_lines(
ordered_items: list[dict[str, Any]],
items_key: str,
item_type: str,
prefix_stats: dict[str, dict[str, Any]],
read_prefixes_as_columns: bool,
prefix_column_indexes: dict[str, int],
) -> list[dict[str, Any]]:
"""Group items into lines and sort those lines into reading order.
`item_type` ("fragment" or "row") selects the rules for (a) whether an
item may join a line group that doesn't yet contain its sequence
prefix, and (b) the fallback (y, x) sort key used when the prefixes
don't read as columns. The single-box ("fragment") and multi-box
("row") callers have historically diverged on both rules; that
divergence is preserved here rather than unified, since unifying it
would change results.
"""
if item_type == "fragment":
def prefix_guard(item_prefix: str, group_prefixes: set[str]) -> bool:
if item_prefix in group_prefixes:
return True
if prefix_stats[item_prefix]["row_count"] > 1:
return False
return not any(
prefix_stats[prefix]["row_count"] > 1 for prefix in group_prefixes
)
def fallback_key(group: dict[str, Any]) -> tuple[float, float]:
group_prefixes = {item["sequence_prefix"] for item in group[items_key]}
return (
min(prefix_stats[prefix]["min_y"] for prefix in group_prefixes),
min(prefix_stats[prefix]["min_x"] for prefix in group_prefixes),
)
elif item_type == "row":
def prefix_guard(item_prefix: str, group_prefixes: set[str]) -> bool:
if not read_prefixes_as_columns:
return True
return item_prefix in group_prefixes
def fallback_key(group: dict[str, Any]) -> tuple[float, float]:
return (
min(item["start_local_y"] for item in group[items_key]),
min(item["start_local_x"] for item in group[items_key]),
)
else:
raise ValueError(f"unknown item_type: {item_type!r}")
line_groups = _build_line_groups(ordered_items, items_key, prefix_guard)
return _order_line_groups(
line_groups,
items_key,
read_prefixes_as_columns,
prefix_column_indexes,
fallback_key,
)
def count_empty_words_in_non_empty_boxes(
predicted_rows: list[PredictedRow],
annotation_boxes: list[AnnotationBox],
) -> int:
non_empty_annotation_boxes = [
annotation_box
for annotation_box in annotation_boxes
if annotation_box.has_transcription and normalize_whitespace(annotation_box.text)
]
count = 0
for predicted_row in predicted_rows:
for word in predicted_row.words:
if word.text.strip():
continue
if any(
annotation_box.contains_point(word.center[0], word.center[1])
for annotation_box in non_empty_annotation_boxes
):
count += 1
return count
def build_box_line_items(
annotation_box: AnnotationBox,
rows: list[dict[str, Any]],
predicted_rows_by_id: dict[str, PredictedRow],
split_line_groups_by_id: dict[str, dict[str, Any]],
excluded_annotation_boxes: list[AnnotationBox] | None = None,
) -> list[dict[str, Any]]:
_ = split_line_groups_by_id
def in_excluded_box(word: Word) -> bool:
if not excluded_annotation_boxes:
return False
cx, cy = word.center
return any(box.contains_point(cx, cy) for box in excluded_annotation_boxes)
def build_row_fragments(
row: dict[str, Any],
predicted_row: PredictedRow,
) -> list[dict[str, Any]]:
if (
row.get("use_full_row_for_assigned_box")
and row.get("assigned_box_id") == annotation_box.box_id
):
fragment_words = order_words_in_box_context(
predicted_row.words, annotation_box
)
else:
fragment_words = words_in_box(predicted_row, annotation_box)
if excluded_annotation_boxes:
fragment_words = [w for w in fragment_words if not in_excluded_box(w)]
word_items: list[dict[str, Any]] = []
for word in fragment_words:
if not word.text.strip():
continue
local_box = box_to_local_bounds(word.box, annotation_box)
local_center_x, local_center_y = word_local_center(word, annotation_box)
word_items.append(
{
"text": word.text,
"global_box": word.box,
"local_box": local_box,
"start_local_x": local_center_x,
"start_local_y": local_center_y,
}
)
if not word_items:
return []
fragments: list[dict[str, Any]] = []
current_words: list[dict[str, Any]] = [word_items[0]]
current_max_x = word_items[0]["local_box"].x_max
for item in word_items[1:]:
previous_local_box = current_words[-1]["local_box"]
tolerance = max(
8.0,
min(previous_local_box.height, item["local_box"].height) * 0.15,
)
if item["local_box"].x_min < current_max_x - tolerance:
fragments.append(
{
"row_id": row["row_id"],
"sequence_prefix": row_sequence_prefix(row["row_id"]),
"status": row["status"],
"text": normalize_whitespace(
" ".join(word["text"] for word in current_words)
),
"global_box": merge_boxes(
[word["global_box"] for word in current_words]
),
"local_box": merge_boxes(
[word["local_box"] for word in current_words]
),
"start_local_x": current_words[0]["start_local_x"],
"start_local_y": current_words[0]["start_local_y"],
}
)
current_words = [item]
current_max_x = item["local_box"].x_max
continue
current_words.append(item)
current_max_x = max(current_max_x, item["local_box"].x_max)
fragments.append(
{
"row_id": row["row_id"],
"sequence_prefix": row_sequence_prefix(row["row_id"]),
"status": row["status"],
"text": normalize_whitespace(
" ".join(word["text"] for word in current_words)
),
"global_box": merge_boxes(
[word["global_box"] for word in current_words]
),
"local_box": merge_boxes(
[word["local_box"] for word in current_words]
),
"start_local_x": current_words[0]["start_local_x"],
"start_local_y": current_words[0]["start_local_y"],
}
)
return fragments
fragment_items: list[dict[str, Any]] = []
for row in rows:
predicted_row = predicted_rows_by_id[row["row_id"]]
fragment_items.extend(build_row_fragments(row, predicted_row))
if not fragment_items:
return []
prefix_stats = build_sequence_prefix_stats(fragment_items)
read_prefixes_as_columns = sequence_prefixes_look_like_columns(prefix_stats)
prefix_column_indexes = sequence_prefix_column_indexes(prefix_stats)
ordered_fragment_items = sorted(
fragment_items,
key=lambda item: (
item["start_local_y"],
item["start_local_x"],
item["row_id"],
item["text"],
),
)
ordered_line_groups = _group_items_into_ordered_lines(
ordered_fragment_items,
"fragment_items",
"fragment",
prefix_stats,
read_prefixes_as_columns,
prefix_column_indexes,
)
line_items: list[dict[str, Any]] = []
from spatial import local_box_to_list # avoid re-listing at top level
for line_index, line_group in enumerate(ordered_line_groups):
ordered_fragment_items_in_line = sorted(
line_group["fragment_items"],
key=lambda item: (
item["start_local_x"],
item["start_local_y"],
item["local_box"].x_max,
item["row_id"],
item["text"],
),
)
row_ids: list[str] = []
row_statuses: list[str] = []
for item in ordered_fragment_items_in_line:
if item["row_id"] not in row_ids:
row_ids.append(item["row_id"])
row_statuses.append(item["status"])
global_line_box = merge_boxes(
[item["global_box"] for item in ordered_fragment_items_in_line]
)
local_line_box = merge_boxes(
[item["local_box"] for item in ordered_fragment_items_in_line]
)
line_items.append(
{
"line_id": f"{annotation_box.box_id}:line_{line_index}",
"row_ids": row_ids,
"row_statuses": row_statuses,
"line_text": normalize_whitespace(
" ".join(
item["text"] for item in ordered_fragment_items_in_line
)
),
"box": rounded_box(global_line_box),
"local_box": local_box_to_list(local_line_box),
}
)
return line_items
def build_region_predicted_text(
region_rows: list[dict[str, Any]],
predicted_rows_by_id: dict[str, PredictedRow],
ordered_boxes: list[AnnotationBox],
excluded_annotation_boxes: list[AnnotationBox] | None = None,
) -> tuple[str, int, list[str], Box | None, frozenset[int]]:
if not region_rows:
return ("", 0, [], None, frozenset())
def filtered_row_text(row: dict[str, Any]) -> str:
if not excluded_annotation_boxes:
return normalize_whitespace(row["row_text"])
predicted_row = predicted_rows_by_id[row["row_id"]]
words = [
w
for w in predicted_row.words
if w.text.strip()
and not any(
box.contains_point(*w.center) for box in excluded_annotation_boxes
)
]
return normalize_whitespace(" ".join(w.text for w in words))
if len(ordered_boxes) == 1:
annotation_box = ordered_boxes[0]
line_items = build_box_line_items(
annotation_box=annotation_box,
rows=region_rows,
predicted_rows_by_id=predicted_rows_by_id,
split_line_groups_by_id={},
excluded_annotation_boxes=excluded_annotation_boxes,
)
if line_items:
predicted_box = merge_boxes(
[
Box(
x_min=float(item["box"][0]),
y_min=float(item["box"][1]),
x_max=float(item["box"][2]),
y_max=float(item["box"][3]),
)
for item in line_items
]
)
assigned_row_ids: list[str] = []
for line_item in line_items:
for row_id in line_item["row_ids"]:
if row_id not in assigned_row_ids:
assigned_row_ids.append(row_id)
joined_text, join_word_indices = join_box_lines_with_hyphenation(
[item["line_text"] for item in line_items]
)
return (
joined_text,
len(line_items),
assigned_row_ids,
predicted_box,
join_word_indices,
)
if ordered_boxes:
ordered_box_id_to_index = {
annotation_box.box_id: index
for index, annotation_box in enumerate(ordered_boxes)
}
def ordering_box_for_row(row: dict[str, Any]) -> AnnotationBox | None:
touched_box_ids = [
box_id
for box_id in row.get("touched_box_ids", [])
if box_id in ordered_box_id_to_index
]
if touched_box_ids:
leftmost_box_id = min(
touched_box_ids,
key=lambda box_id: (
ordered_box_id_to_index[box_id],
ordered_boxes[ordered_box_id_to_index[box_id]].bounds.x_min,
ordered_boxes[ordered_box_id_to_index[box_id]].bounds.y_min,
),
)
return ordered_boxes[ordered_box_id_to_index[leftmost_box_id]]
assigned_box_id = row.get("assigned_box_id")
if assigned_box_id in ordered_box_id_to_index:
return ordered_boxes[ordered_box_id_to_index[assigned_box_id]]
dominant_box_id = row.get("dominant_box_id")
if dominant_box_id in ordered_box_id_to_index:
return ordered_boxes[ordered_box_id_to_index[dominant_box_id]]
return None
def relevant_words_in_box_context(
row: dict[str, Any],
annotation_box: AnnotationBox,
) -> list[Word]:
predicted_row = predicted_rows_by_id[row["row_id"]]
box_words = words_in_box(predicted_row, annotation_box)
if box_words:
return box_words
return order_words_in_box_context(
[word for word in predicted_row.words if word.text.strip()],
annotation_box,
)
def row_order_key_within_box(
row: dict[str, Any],
annotation_box: AnnotationBox,
) -> tuple[float, float, float, str]:
relevant_words = relevant_words_in_box_context(row, annotation_box)
if not relevant_words:
row_bounds = report_box(row["row_box"])
return (
row_bounds.y_min,
row_bounds.x_min,
row_bounds.x_max,
row["row_id"],
)
local_word_centers = [
word_local_center(word, annotation_box) for word in relevant_words
]
first_word_local_x, first_word_local_y = local_word_centers[0]
return (
first_word_local_y,
first_word_local_x,
statistics.median(
local_center_y for _, local_center_y in local_word_centers
),
row["row_id"],
)
grouped_rows: dict[str, list[dict[str, Any]]] = {}
for row in region_rows:
ordering_box = ordering_box_for_row(row)
if ordering_box is None:
continue
grouped_rows.setdefault(ordering_box.box_id, []).append(row)
line_texts: list[str] = []
assigned_row_ids_multi: list[str] = []
predicted_boxes: list[Box] = []
for annotation_box in ordered_boxes:
box_rows = grouped_rows.get(annotation_box.box_id, [])
if not box_rows:
continue
ordered_row_items = []
for row in sorted(
box_rows,
key=lambda item: row_order_key_within_box(item, annotation_box),
):
relevant_words = relevant_words_in_box_context(row, annotation_box)
if relevant_words:
relevant_box = merge_boxes([word.box for word in relevant_words])
start_local_x, start_local_y = word_local_center(
relevant_words[0], annotation_box
)
else:
relevant_box = report_box(row["row_box"])
local_relevant_box = box_to_local_bounds(
relevant_box, annotation_box
)
start_local_x = local_relevant_box.x_min
start_local_y = local_relevant_box.y_min
ordered_row_items.append(
{
"row_id": row["row_id"],
"sequence_prefix": row_sequence_prefix(row["row_id"]),
"status": row["status"],
"row_text": filtered_row_text(row),
"full_row_box": report_box(row["row_box"]),
"local_box": box_to_local_bounds(relevant_box, annotation_box),
"start_local_x": start_local_x,
"start_local_y": start_local_y,
}
)
prefix_stats = build_sequence_prefix_stats(ordered_row_items)
read_prefixes_as_columns = sequence_prefixes_look_like_columns(
prefix_stats
)
prefix_column_indexes = sequence_prefix_column_indexes(prefix_stats)
ordered_line_groups = _group_items_into_ordered_lines(
ordered_row_items,
"row_items",
"row",
prefix_stats,
read_prefixes_as_columns,
prefix_column_indexes,
)
for line_group in ordered_line_groups:
ordered_row_items_in_line = sorted(
line_group["row_items"],
key=lambda item: (
item["start_local_x"],
item["start_local_y"],
item["local_box"].x_max,
item["row_id"],
),
)
line_text = normalize_whitespace(
" ".join(
item["row_text"]
for item in ordered_row_items_in_line
if item["row_text"]
)
)
if line_text:
line_texts.append(line_text)
predicted_boxes.append(
merge_boxes(
[item["full_row_box"] for item in ordered_row_items_in_line]
)
)
for item in ordered_row_items_in_line:
if item["row_id"] not in assigned_row_ids_multi:
assigned_row_ids_multi.append(item["row_id"])
if line_texts:
predicted_box = merge_boxes(predicted_boxes) if predicted_boxes else None
return (
"\n".join(line_texts),
len(line_texts),
assigned_row_ids_multi,
predicted_box,
frozenset(),
)
def region_row_order_key(
row: dict[str, Any],
) -> tuple[float, float, float, str]:
predicted_row = predicted_rows_by_id[row["row_id"]]
if not predicted_row.words:
return (
row["row_box"][1],
row["row_box"][0],
row["row_box"][2],
row["row_id"],
)
word_center_ys = [word.center[1] for word in predicted_row.words]
word_center_xs = [word.center[0] for word in predicted_row.words]
return (
statistics.median(word_center_ys),
min(word_center_xs),
statistics.median(word_center_xs),
row["row_id"],
)
ordered_rows = sorted(region_rows, key=region_row_order_key)
line_texts_fallback: list[str] = []
assigned_row_ids_fallback: list[str] = []
predicted_boxes_fallback: list[Box] = []
for row in ordered_rows:
row_text = filtered_row_text(row)
if row_text:
line_texts_fallback.append(row_text)
assigned_row_ids_fallback.append(row["row_id"])
predicted_boxes_fallback.append(report_box(row["row_box"]))
predicted_box = (
merge_boxes(predicted_boxes_fallback) if predicted_boxes_fallback else None
)
return (
"\n".join(line_texts_fallback),
len(line_texts_fallback),
assigned_row_ids_fallback,
predicted_box,
frozenset(),
)