File size: 8,440 Bytes
551cc83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
from __future__ import annotations

from dataclasses import dataclass
from typing import Any

from geometry import (
    Box,
    polygon_area,
    polygon_intersection,
    point_in_convex_polygon,
)


REDUNDANT_BOX_MIN_OVERLAP_RATIO = 0.95
IMAGE_RELATED_LABELS = frozenset(
    {
        "Photo",
        "Graphics",
        "SealFigure",
        "FrontPicture",
    }
)
HEADER_TITLE_LIKE_LABELS = frozenset(
    {
        "Headline",
        "Kicker",
        "Banner",
        "Deck",
        "Subhead",
        "Nameplate",
        "Masthead",
        "FrontStory",
    }
)
IMAGE_HEADER_FILTER_LABELS = IMAGE_RELATED_LABELS | HEADER_TITLE_LIKE_LABELS


def _normalize_whitespace(text: str) -> str:
    """Local helper to avoid circular import with spatial.py."""
    return " ".join(text.split())


@dataclass(frozen=True)
class Word:
    box: Box
    text: str

    @property
    def center(self) -> tuple[float, float]:
        return (
            (self.box.x_min + self.box.x_max) / 2.0,
            (self.box.y_min + self.box.y_max) / 2.0,
        )


@dataclass(frozen=True)
class AnnotationBox:
    box_id: str
    rect: Box
    text: str
    has_transcription: bool
    rotation: float
    polygon: tuple[tuple[float, float], ...]
    bounds: Box
    labels: tuple[str, ...] = ()
    letter_count: int = 0
    latin_or_cyrillic_letter_count: int = 0
    non_armenian_letter_ratio: float = 0.0
    excluded_as_non_armenian_text: bool = False
    parent_box_id: str | None = None
    reading_order: int | None = None

    def contains_point(self, x: float, y: float) -> bool:
        if not self.bounds.contains_point(x, y):
            return False
        return point_in_convex_polygon((x, y), self.polygon)

    def overlap_area_with_box(self, box: Box) -> float:
        if self.bounds.intersection(box) is None:
            return 0.0
        return polygon_area(polygon_intersection(box.to_polygon(), self.polygon))


@dataclass(frozen=True)
class PredictedRow:
    row_id: str
    words: list[Word]

    @property
    def text(self) -> str:
        return " ".join(word.text for word in self.words if word.text.strip())


def annotation_box_contains_annotation_box(container: AnnotationBox, inner: AnnotationBox) -> bool:
    if container.box_id == inner.box_id:
        return False
    if polygon_area(container.polygon) <= polygon_area(inner.polygon):
        return False
    if (
        inner.bounds.x_min < container.bounds.x_min - 1e-6
        or inner.bounds.y_min < container.bounds.y_min - 1e-6
        or inner.bounds.x_max > container.bounds.x_max + 1e-6
        or inner.bounds.y_max > container.bounds.y_max + 1e-6
    ):
        return False
    return all(container.contains_point(point[0], point[1]) for point in inner.polygon)


def annotation_box_overlap_ratio(container: AnnotationBox, inner: AnnotationBox) -> float:
    inner_area = polygon_area(inner.polygon)
    if inner_area <= 0:
        return 0.0
    overlap_area = polygon_area(polygon_intersection(inner.polygon, container.polygon))
    return overlap_area / inner_area


def annotation_boxes_have_compatible_text(container: AnnotationBox, inner: AnnotationBox) -> bool:
    container_text = _normalize_whitespace(container.text)
    inner_text = _normalize_whitespace(inner.text)
    if not container_text or not inner_text:
        return False
    return (
        container_text == inner_text
        or inner_text in container_text
        or container_text in inner_text
    )


def decomposable_container_box_ids(boxes: list[AnnotationBox]) -> frozenset[str]:
    """Return box_ids of containers whose text is exactly reproduced by
    concatenating (in reading order) two or more boxes it contains.

    Some annotations squeeze multiple side-by-side columns (e.g. a folioline
    with page number / title / date, or a paragraph split across two print
    columns) into one wide box, encoding the correct reading order only in
    the transcription's word order. When that box also has separately
    annotated children covering the same content, evaluating against the
    children directly sidesteps having to guess the column layout from
    geometry alone.
    """
    textful = [b for b in boxes if b.has_transcription and b.text.strip()]

    # `parent_id` is overloaded in this dataset: for text fragments of a
    # squeezed container it means "part of this box's text", but the same
    # field also links unrelated story components (headline, caption, ...)
    # to a page anchor box, so it can't be trusted as a children set on its
    # own — it must independently reconstruct the container's text, same as
    # the geometric candidates below.
    children_by_declared_parent: dict[str, list[AnnotationBox]] = {}
    for b in textful:
        if b.parent_box_id:
            children_by_declared_parent.setdefault(b.parent_box_id, []).append(b)

    def reconstructs(children: list[AnnotationBox], container_text: str) -> bool:
        if len(children) < 2:
            return False
        order_keys = [
            lambda b: (b.rect.y_min, b.rect.x_min),
            lambda b: (b.rect.x_min, b.rect.y_min),
        ]
        if all(b.reading_order is not None for b in children):
            order_keys.insert(0, lambda b: b.reading_order)
        for order_key in order_keys:
            ordered = sorted(children, key=order_key)
            reconstructed = _normalize_whitespace(" ".join(b.text for b in ordered))
            if reconstructed == container_text:
                return True
        return False

    decomposable: set[str] = set()
    for container in textful:
        container_text = _normalize_whitespace(container.text)
        if len(container_text) < 10:
            continue

        # Geometric containment catches most cases, but a fraction-of-a-degree
        # rotation mismatch between an annotated box and its (visually
        # identical) parent can make a rotated-polygon corner fall a hair
        # outside the parent, failing strict containment. `parent_id` is
        # immune to that, so it's tried as an independent candidate set
        # rather than merged with the geometric one (merging would pull in
        # unrelated same-parent siblings and break the exact-text check).
        declared_children = children_by_declared_parent.get(container.box_id, [])
        geometric_children = [
            b
            for b in textful
            if b.box_id != container.box_id
            and annotation_box_contains_annotation_box(container, b)
        ]

        if reconstructs(declared_children, container_text) or reconstructs(
            geometric_children, container_text
        ):
            decomposable.add(container.box_id)
    return frozenset(decomposable)


def filter_redundant_annotation_boxes(boxes: list[AnnotationBox]) -> list[AnnotationBox]:
    filtered_boxes: list[AnnotationBox] = []
    for candidate in boxes:
        is_redundant = False
        for other in boxes:
            if other.box_id == candidate.box_id:
                continue
            if polygon_area(other.polygon) <= polygon_area(candidate.polygon):
                continue
            if not annotation_boxes_have_compatible_text(other, candidate):
                continue
            if annotation_box_contains_annotation_box(other, candidate):
                is_redundant = True
                break
            if annotation_box_overlap_ratio(other, candidate) >= REDUNDANT_BOX_MIN_OVERLAP_RATIO:
                is_redundant = True
                break
        if not is_redundant:
            filtered_boxes.append(candidate)
    return filtered_boxes


def annotation_box_type(annotation_box: AnnotationBox) -> str | None:
    return annotation_box.labels[0] if annotation_box.labels else None


def annotation_box_metadata(annotation_box: AnnotationBox) -> dict[str, Any]:
    return {
        "box_id": annotation_box.box_id,
        "box_type": annotation_box_type(annotation_box),
        "labels": list(annotation_box.labels),
    }


def gt_box_report(annotation_box: AnnotationBox) -> dict[str, Any]:
    # Inline rounded_box to avoid circular import with spatial.py
    rounded = [round(v, 3) for v in [
        annotation_box.bounds.x_min,
        annotation_box.bounds.y_min,
        annotation_box.bounds.x_max,
        annotation_box.bounds.y_max,
    ]]
    return {
        **annotation_box_metadata(annotation_box),
        "box": rounded,
    }