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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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
"""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,
    }