Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

44.0 KB
Raw Blame
# Copyright (c) Opendatalab. All rights reserved.
"""表格方向检测、Medium 表格识别与 Flash OCR 文本投影。"""

from __future__ import annotations

import html
import math
from collections import Counter
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Literal

import numpy as np
from docvortex.analyzers.pdf import PDFTableRecoveryError, prepare_table_page, recover_table_region
from docvortex.analyzers.pdf import project_table_text as project_ocr_table_text
from docvortex.assets import encode_crop_as_jpeg_data_uri as _encode_page_crop_as_jpeg_data_uri
from docvortex.assets import image_size as _normalize_page_size
from docvortex.assets import rotate_image_to_upright as _rotate_visual_block_image_to_upright
from docvortex.document.pdf import PDFPage, PDFPageTextGeometry, PDFPageVectorGeometry, get_lines_from_chars
from docvortex.geometry import bbox_center as _table_bbox_center
from docvortex.geometry import bbox_to_quad as _medium_bbox_to_quad
from docvortex.geometry import calculate_overlap_area_in_bbox1_area_ratio, normalize_to_int_bbox
from docvortex.geometry import normalize_quarter_turn_angle as _normalize_visual_block_angle
from docvortex.geometry import rotate_bbox as _rotate_medium_table_bbox
from loguru import logger

from ....model.ocr.image import mask_formula_regions_for_ocr_det, rgb_to_bgr
from ....model.runtime.contracts import AtomicModelName
from ....types import RAW_ALGORITHM, RAW_FORMULA_NUMBER, RAW_PHONETIC, BBox, BlockType
from .snapshots import PageSnapshotCache, get_page_snapshot_entry
from .constants import (
    BATCH_RATIO,
    OCR_DET_BASE_BATCH_SIZE,
    TABLE_TEXT_LINE_OVERLAP_THRESHOLD,
    TABLE_TEXT_ORIENTATION_ANGLES,
    TABLE_TEXT_ORIENTATION_MIN_DOMINANCE_RATIO,
    TABLE_TEXT_ORIENTATION_MIN_VALID_LINES,
)
from .model_inputs import (
    _bbox_to_pixel_bbox,
    _get_medium_table_virtual_image_bbox,
    _normalize_medium_content,
    _sidecar_bbox_to_page_bbox,
)

if TYPE_CHECKING:
    from ....model.runtime.hybrid import HybridLocalModelContext


_NATIVE_TABLE_ALWAYS_COMPLEX_BLOCK_TYPES = {
    BlockType.IMAGE,
    BlockType.CHART,
    BlockType.CODE,
    RAW_ALGORITHM,
}
_NATIVE_TABLE_FORMULA_BLOCK_TYPES = {
    BlockType.EQUATION,
    RAW_FORMULA_NUMBER,
}
_NATIVE_TABLE_INTERNAL_TEXT_BLOCK_TYPES = {
    BlockType.TEXT,
    BlockType.DOC_TITLE,
    BlockType.PARAGRAPH_TITLE,
    BlockType.ASIDE_TEXT,
    BlockType.REF_TEXT,
    BlockType.LIST,
    BlockType.INDEX,
    RAW_PHONETIC,
}
_NATIVE_TABLE_FORMULA_LAYOUT_LABELS = {"inline_formula", "display_formula", "formula_number"}
_NATIVE_TABLE_INTERNAL_BLOCK_COVERAGE = 0.9
_NATIVE_TABLE_OVERLAP_FALLBACK_COVERAGE = 0.8
_NATIVE_HIGH_SOURCE_ORDER_KEY = "_native_table_source_order"


@dataclass(frozen=True)
class _NativeTablePrioritySummary:
    """记录单个窗口内原生表格优先解析的稳定统计。"""

    total: int = 0
    accepted: int = 0
    complex_fallbacks: int = 0
    rejected: int = 0
    errors: int = 0
    removed_internal_text: int = 0
    removed_formula_blocks: int = 0
    removed_formula_layout_items: int = 0


def _has_non_empty_table_content(block: dict[str, Any]) -> bool:
    """判断表格块是否已经持有可直接输出的非空内容。"""

    content = block.get("content")
    return isinstance(content, str) and bool(content.strip())


def _mark_native_table_complex_entries(
    table_entries: list[dict[str, Any]],
    page_blocks: list[dict[str, Any]],
    page_size: tuple[int, int],
) -> None:
    """按现有归属几何标记含模型语义对象或重叠表格的候选。"""

    for block in page_blocks:
        block_type = block.get("type")
        if block_type not in _NATIVE_TABLE_ALWAYS_COMPLEX_BLOCK_TYPES:
            continue
        block_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)
        if block_bbox is None:
            continue
        owner = _select_table_owner(block_bbox, table_entries)
        if owner is not None:
            owner["complex_reasons"].add(str(block.get("type")))

    for entry_index, table_entry in enumerate(table_entries):
        table_bbox = table_entry["table_bbox"]
        for peer_entry in table_entries[entry_index + 1 :]:
            peer_bbox = peer_entry["table_bbox"]
            overlap_bbox = _table_bbox_intersection(table_bbox, peer_bbox)
            if overlap_bbox is None:
                continue
            overlap_area = float(overlap_bbox[2] - overlap_bbox[0]) * float(overlap_bbox[3] - overlap_bbox[1])
            table_area = float(table_bbox[2] - table_bbox[0]) * float(table_bbox[3] - table_bbox[1])
            peer_area = float(peer_bbox[2] - peer_bbox[0]) * float(peer_bbox[3] - peer_bbox[1])
            smaller_area = min(table_area, peer_area)
            if smaller_area <= 0 or overlap_area / smaller_area < _NATIVE_TABLE_OVERLAP_FALLBACK_COVERAGE:
                continue
            table_entry["complex_reasons"].add("overlapping_table")
            peer_entry["complex_reasons"].add("overlapping_table")


def _remove_native_table_internal_text_blocks(
    page_blocks: list[dict[str, Any]],
    accepted_entries: list[dict[str, Any]],
    page_size: tuple[int, int],
) -> int:
    """删除已被原生 HTML 完整吸收的重复正文块,并保留视觉注释。"""

    if not accepted_entries:
        return 0

    removed_count = 0
    retained_blocks: list[dict[str, Any]] = []
    for block in page_blocks:
        if block.get("type") not in _NATIVE_TABLE_INTERNAL_TEXT_BLOCK_TYPES:
            retained_blocks.append(block)
            continue
        block_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)
        if block_bbox is None:
            retained_blocks.append(block)
            continue
        owner = _select_table_owner(block_bbox, accepted_entries)
        if owner is None or calculate_overlap_area_in_bbox1_area_ratio(block_bbox, owner["table_bbox"]) < (
            _NATIVE_TABLE_INTERNAL_BLOCK_COVERAGE
        ):
            retained_blocks.append(block)
            continue
        removed_count += 1

    page_blocks[:] = retained_blocks
    return removed_count


def _remove_native_table_formula_items(
    page_blocks: list[dict[str, Any]],
    layout_res: list[dict[str, Any]],
    accepted_entries: list[dict[str, Any]],
    page_size: tuple[int, int],
) -> tuple[int, int]:
    """原子删除 Medium/High 原生命中表内的公式 block 与原始 layout 项。"""

    if not accepted_entries:
        return 0, 0

    removed_block_count = 0
    retained_blocks: list[dict[str, Any]] = []
    for block in page_blocks:
        if block.get("type") not in _NATIVE_TABLE_FORMULA_BLOCK_TYPES:
            retained_blocks.append(block)
            continue
        block_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)
        if block_bbox is None or _select_table_owner(block_bbox, accepted_entries) is None:
            retained_blocks.append(block)
            continue
        removed_block_count += 1
    page_blocks[:] = retained_blocks

    removed_layout_count = 0
    retained_layout_items: list[dict[str, Any]] = []
    for layout_item in layout_res:
        label = str(layout_item.get("label") or layout_item.get("type") or "")
        if label not in _NATIVE_TABLE_FORMULA_LAYOUT_LABELS:
            retained_layout_items.append(layout_item)
            continue
        formula_bbox = _bbox_to_pixel_bbox(layout_item.get("bbox"), page_size)
        if formula_bbox is None or _select_table_owner(formula_bbox, accepted_entries) is None:
            retained_layout_items.append(layout_item)
            continue
        removed_layout_count += 1
    layout_res[:] = retained_layout_items
    return removed_block_count, removed_layout_count


def _apply_native_txt_table_priority(
    model_list: list[list[dict[str, Any]]],
    images_layout_res: list[list[dict[str, Any]]],
    pdf_pages: list[PDFPage],
    images_list: list[dict[str, Any]],
    *,
    effort: Literal["medium", "high"],
    page_text_geometries: list[PDFPageTextGeometry | None] | None = None,
    page_vector_geometries: list[PDFPageVectorGeometry | None] | None = None,
    page_snapshots: PageSnapshotCache | None = None,
) -> _NativeTablePrioritySummary:
    """在 Medium/High TXT 模型表格识别前回填高置信原生 HTML。"""

    total = 0
    accepted = 0
    complex_fallbacks = 0
    rejected = 0
    errors = 0
    removed_internal_text = 0
    removed_formula_blocks = 0
    removed_formula_layout_items = 0

    for page_idx, (page_blocks, layout_res, pdf_page, image_dict) in enumerate(
        zip(model_list, images_layout_res, pdf_pages, images_list, strict=True)
    ):
        page_size = _normalize_page_size(image_dict["img_pil"])
        table_entries: list[dict[str, Any]] = []
        for block in page_blocks:
            if block.get("type") != BlockType.TABLE:
                continue
            total += 1
            table_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)
            if table_bbox is None:
                rejected += 1
                continue
            table_entries.append(
                {
                    "table_block": block,
                    "table_bbox": table_bbox,
                    "complex_reasons": set(),
                }
            )

        if not table_entries:
            continue

        _mark_native_table_complex_entries(
            table_entries,
            page_blocks,
            page_size,
        )
        for table_entry in table_entries:
            if table_entry["complex_reasons"]:
                logger.debug(
                    "Hybrid native table kept model fallback for complex content: "
                    f"page_idx={page_idx}, bbox={table_entry['table_block'].get('bbox')}, "
                    f"reasons={sorted(table_entry['complex_reasons'])}"
                )
        eligible_entries = [entry for entry in table_entries if not entry["complex_reasons"]]
        complex_fallbacks += len(table_entries) - len(eligible_entries)
        if not eligible_entries:
            continue

        try:
            page_text_geometry = page_text_geometries[page_idx] if page_text_geometries is not None else None
            vector_geometry = page_vector_geometries[page_idx] if page_vector_geometries is not None else None
            snapshot_entry = get_page_snapshot_entry(
                page_snapshots,
                page_idx,
                pdf_page,
                geometry=page_text_geometry,
                vector_geometry=vector_geometry,
            )
            if snapshot_entry is not None:
                # 表格恢复仍消费其真实可变 geometry,但不提前把该兼容副本放进窗口正文缓存。
                table_page = prepare_table_page(pdf_page, snapshot=snapshot_entry.get_full_snapshot(pdf_page))
            else:
                if vector_geometry is None:
                    vector_geometry = pdf_page.get_vector_geometry()
                table_page = prepare_table_page(pdf_page, geometry=page_text_geometry, vector_geometry=vector_geometry)
                page_text_geometry = table_page.geometry
                if page_text_geometries is not None:
                    page_text_geometries[page_idx] = page_text_geometry
                if page_vector_geometries is not None:
                    page_vector_geometries[page_idx] = vector_geometry
            native_page_size = table_page.page_size
            render_scale = float(image_dict.get("scale", 1.0) or 1.0)
        except Exception as exc:
            errors += len(eligible_entries)
            logger.warning(
                "Hybrid native table page primitives failed and kept model fallback: "
                f"page_idx={page_idx}, tables={len(eligible_entries)}, error={exc}"
            )
            continue

        accepted_entries: list[dict[str, Any]] = []
        for table_entry in eligible_entries:
            table_block = table_entry["table_block"]
            table_bbox = _sidecar_bbox_to_page_bbox(
                table_block.get("bbox"),
                native_page_size,
                render_scale,
            )
            if table_bbox is None:
                rejected += 1
                continue
            try:
                result = recover_table_region(
                    table_page, table_bbox, angle=_normalize_visual_block_angle(table_block.get("angle", 0))
                )
            except PDFTableRecoveryError as exc:
                errors += 1
                logger.warning(
                    "Hybrid native table recovery failed and kept model fallback: "
                    f"page_idx={page_idx}, bbox={table_block.get('bbox')}, error={exc}"
                )
                continue
            if result is None or not result.html.strip():
                rejected += 1
                logger.debug(
                    f"Hybrid native table rejected and kept model fallback: page_idx={page_idx}, bbox={table_block.get('bbox')}"
                )
                continue
            table_block["content"] = result.html
            accepted_entries.append(table_entry)
            accepted += 1
            logger.debug(
                "Hybrid native table accepted: "
                f"page_idx={page_idx}, bbox={table_block.get('bbox')}, "
                f"source={result.source}, confidence={result.confidence:.3f}"
            )

        page_removed_formula_blocks, page_removed_formula_layout_items = _remove_native_table_formula_items(
            page_blocks,
            layout_res,
            accepted_entries,
            page_size,
        )
        removed_formula_blocks += page_removed_formula_blocks
        removed_formula_layout_items += page_removed_formula_layout_items

        removed_internal_text += _remove_native_table_internal_text_blocks(
            page_blocks,
            accepted_entries,
            page_size,
        )

    return _NativeTablePrioritySummary(
        total=total,
        accepted=accepted,
        complex_fallbacks=complex_fallbacks,
        rejected=rejected,
        errors=errors,
        removed_internal_text=removed_internal_text,
        removed_formula_blocks=removed_formula_blocks,
        removed_formula_layout_items=removed_formula_layout_items,
    )


def _split_native_high_table_blocks(
    model_list: list[list[dict[str, Any]]],
) -> tuple[list[list[dict[str, Any]]], list[list[dict[str, Any]]]]:
    """从 High VLM 输入逐表移除原生命中项,并写入临时源顺序。"""

    vlm_blocks_list: list[list[dict[str, Any]]] = []
    accepted_tables_list: list[list[dict[str, Any]]] = []
    for page_blocks in model_list:
        accepted_tables = [
            block for block in page_blocks if block.get("type") == BlockType.TABLE and _has_non_empty_table_content(block)
        ]
        if not accepted_tables:
            vlm_blocks_list.append(page_blocks)
            accepted_tables_list.append([])
            continue

        accepted_ids = {id(block) for block in accepted_tables}
        vlm_blocks: list[dict[str, Any]] = []
        for source_order, block in enumerate(page_blocks):
            block[_NATIVE_HIGH_SOURCE_ORDER_KEY] = source_order
            if id(block) not in accepted_ids:
                vlm_blocks.append(block)
        vlm_blocks_list.append(vlm_blocks)
        accepted_tables_list.append(accepted_tables)
    return vlm_blocks_list, accepted_tables_list


def _restore_native_high_table_blocks(
    vlm_results: list[Any],
    accepted_tables_list: list[list[dict[str, Any]]],
) -> list[list[Any]]:
    """按临时源顺序把原生表格插回 High VLM 后处理结果。"""

    if len(vlm_results) != len(accepted_tables_list):
        raise ValueError("Hybrid high VLM result count does not match native table page count")

    restored_pages: list[list[Any]] = []
    for page_results, accepted_tables in zip(vlm_results, accepted_tables_list, strict=True):
        restored_blocks = list(page_results)
        for table_block in sorted(
            accepted_tables,
            key=lambda block: int(block[_NATIVE_HIGH_SOURCE_ORDER_KEY]),
        ):
            source_order = int(table_block[_NATIVE_HIGH_SOURCE_ORDER_KEY])
            insert_at = len(restored_blocks)
            for block_idx, block in enumerate(restored_blocks):
                block_order = block.get(_NATIVE_HIGH_SOURCE_ORDER_KEY) if isinstance(block, dict) else None
                if isinstance(block_order, int) and block_order > source_order:
                    insert_at = block_idx
                    break
            restored_blocks.insert(insert_at, table_block)
        restored_pages.append(restored_blocks)
    return restored_pages


def _apply_table_rotate_labels(
    table_items: list[dict[str, Any]],
    rotate_labels: list[str],
) -> None:
    """按分类输入顺序将表格旋转角写回原始 layout 检测项。"""
    if len(rotate_labels) != len(table_items):
        raise ValueError("Hybrid table orientation result count mismatch")
    for table_item, rotate_label in zip(table_items, rotate_labels):
        table_item["layout_item"]["angle"] = int(rotate_label or "0")


def _detect_table_angle_from_pdf_lines(
    pdf_lines: list[dict[str, Any]],
    table_bbox: BBox,
    *,
    page_rotation: int,
) -> int | None:
    """将原生文本角度转换到页面视觉坐标系,满足强众数门槛时返回表格角度。"""
    angle_counts: Counter[int] = Counter()
    for pdf_line in pdf_lines:
        try:
            raw_bbox = pdf_line.get("bbox")
            line_bbox = getattr(raw_bbox, "bbox", raw_bbox)
            if line_bbox is None or len(line_bbox) != 4:
                continue
            x0, y0, x1, y1 = [float(value) for value in line_bbox]
            if x1 <= x0 or y1 <= y0:
                continue

            line_text = "".join(str(pdf_span.get("text", "") or "") for pdf_span in pdf_line.get("spans", [])).strip()
            if not line_text:
                continue

            rotation = float(pdf_line.get("rotation", 0.0) or 0.0)
        except (AttributeError, TypeError, ValueError):
            continue

        if (
            calculate_overlap_area_in_bbox1_area_ratio(
                (x0, y0, x1, y1),
                table_bbox,
            )
            <= TABLE_TEXT_LINE_OVERLAP_THRESHOLD
        ):
            continue
        # 行框已应用页面 /Rotate,但 rotation 仍是原始文本角度;两者相加才是视觉方向。
        visual_angle = (math.degrees(rotation) + page_rotation) % 360
        if not math.isfinite(visual_angle):
            continue

        angle = int(round(visual_angle)) % 360
        if angle in TABLE_TEXT_ORIENTATION_ANGLES and abs((visual_angle - angle + 180) % 360 - 180) < 0.1:
            angle_counts[angle] += 1

    valid_line_count = sum(angle_counts.values())
    if valid_line_count < TABLE_TEXT_ORIENTATION_MIN_VALID_LINES:
        return None

    max_count = max(angle_counts.values())
    dominant_angles = [angle for angle, count in angle_counts.items() if count == max_count]
    if len(dominant_angles) != 1:
        return None
    if max_count / valid_line_count < TABLE_TEXT_ORIENTATION_MIN_DOMINANCE_RATIO:
        return None
    return dominant_angles[0]


def _resolve_txt_table_orientations(
    table_items: list[dict[str, Any]],
    pdf_pages: list[PDFPage],
    images_list: list[dict[str, Any]],
    page_text_geometries: list[PDFPageTextGeometry | None] | None = None,
    *,
    page_snapshots: PageSnapshotCache | None = None,
) -> list[dict[str, Any]]:
    """优先用原生 PDF 文本行写回表格角度,并返回需要视觉兜底的表格。"""
    fallback_table_items: list[dict[str, Any]] = []
    page_lines_cache: dict[int, list[dict[str, Any]] | None] = {}

    for table_item in table_items:
        page_idx = table_item.get("page_idx")
        if not isinstance(page_idx, int) or page_idx < 0 or page_idx >= len(pdf_pages) or page_idx >= len(images_list):
            fallback_table_items.append(table_item)
            continue

        try:
            pdf_page = pdf_pages[page_idx]
            page_rotation = pdf_page.rotation
            render_scale = float(images_list[page_idx].get("scale", 0) or 0)
            table_bbox = _sidecar_bbox_to_page_bbox(
                table_item["layout_item"].get("bbox"),
                tuple(float(value) for value in pdf_page.size),
                render_scale,
            )
        except Exception as exc:
            logger.warning(f"Hybrid txt table orientation falls back to visual model: page_idx={page_idx}, error={exc}")
            fallback_table_items.append(table_item)
            continue

        if table_bbox is None:
            fallback_table_items.append(table_item)
            continue

        if page_idx not in page_lines_cache:
            try:
                geometry = page_text_geometries[page_idx] if page_text_geometries is not None else None
                snapshot_entry = None
                geometry_failed = False
                try:
                    snapshot_entry = get_page_snapshot_entry(page_snapshots, page_idx, pdf_page, geometry=geometry)
                except Exception as exc:
                    geometry_failed = True
                    logger.debug(f"Hybrid table orientation uses plain chars after owned geometry failure: {exc}")
                if snapshot_entry is not None:
                    # 方向投票只需要粗行几何和文字,不物化整页 Char/font,也不读取路径或链接。
                    page_lines_cache[page_idx] = snapshot_entry.text_owner.get_line_summaries(0.7, 0.1)
                else:
                    if geometry is None and page_text_geometries is not None and not geometry_failed:
                        try:
                            geometry = pdf_page.get_chars_with_geometry()
                        except Exception as exc:
                            # 扩展几何失败不应让本来可成功的普通字符投票改走视觉模型。
                            logger.debug(f"Hybrid table orientation uses plain chars after geometry failure: {exc}")
                        else:
                            page_text_geometries[page_idx] = geometry
                    chars = geometry.chars if geometry is not None else pdf_page.get_chars()
                    page_lines_cache[page_idx] = get_lines_from_chars(chars)
            except Exception as exc:
                logger.warning(f"Hybrid txt table orientation falls back to visual model: page_idx={page_idx}, error={exc}")
                page_lines_cache[page_idx] = None

        pdf_lines = page_lines_cache[page_idx]
        if pdf_lines is None:
            fallback_table_items.append(table_item)
            continue

        table_angle = _detect_table_angle_from_pdf_lines(pdf_lines, table_bbox, page_rotation=page_rotation)
        if table_angle is None:
            fallback_table_items.append(table_item)
            continue
        table_item["layout_item"]["angle"] = table_angle

    return fallback_table_items


def _apply_table_orientations(
    table_items: list[dict[str, Any]],
    parse_mode: Literal["txt", "ocr"],
    pdf_pages: list[PDFPage],
    images_list: list[dict[str, Any]],
    hybrid_model: HybridLocalModelContext,
    page_text_geometries: list[PDFPageTextGeometry | None] | None = None,
    *,
    page_snapshots: PageSnapshotCache | None = None,
) -> None:
    """按解析模式写回表格角度,文本证据不足时批量调用视觉方向模型。"""
    if parse_mode == "txt":
        fallback_table_items = _resolve_txt_table_orientations(
            table_items,
            pdf_pages,
            images_list,
            page_text_geometries,
            **({"page_snapshots": page_snapshots} if page_snapshots is not None else {}),
        )
    elif parse_mode == "ocr":
        fallback_table_items = table_items
    else:
        raise ValueError(f"Unsupported parse mode: {parse_mode}")

    if not fallback_table_items:
        return

    rotate_labels = hybrid_model.table_orientation_cls_model.batch_predict(
        fallback_table_items,
        det_batch_size=BATCH_RATIO * OCR_DET_BASE_BATCH_SIZE,
        tqdm_enable=True,
    )
    _apply_table_rotate_labels(fallback_table_items, rotate_labels)


def _table_bbox_intersection(bbox1: BBox, bbox2: BBox) -> BBox | None:
    """计算两个 bbox 的有效交集,无重叠时返回 None。"""
    x0 = max(float(bbox1[0]), float(bbox2[0]))
    y0 = max(float(bbox1[1]), float(bbox2[1]))
    x1 = min(float(bbox1[2]), float(bbox2[2]))
    y1 = min(float(bbox1[3]), float(bbox2[3]))
    if x1 <= x0 or y1 <= y0:
        return None
    return (x0, y0, x1, y1)


def _select_table_owner(
    item_bbox: BBox,
    table_entries: list[dict[str, Any]],
) -> dict[str, Any] | None:
    """为本地 layout 对象匹配所属表格,多表命中时选择交叠面积最大的表格。"""
    center_x, center_y = _table_bbox_center(item_bbox)
    candidates: list[tuple[float, dict[str, Any]]] = []
    for table_entry in table_entries:
        table_bbox = table_entry["table_bbox"]
        if not (
            float(table_bbox[0]) <= center_x <= float(table_bbox[2])
            and float(table_bbox[1]) <= center_y <= float(table_bbox[3])
        ):
            continue
        overlap_bbox = _table_bbox_intersection(item_bbox, table_bbox)
        if overlap_bbox is None:
            continue
        overlap_area = float(overlap_bbox[2] - overlap_bbox[0]) * float(overlap_bbox[3] - overlap_bbox[1])
        candidates.append((overlap_area, table_entry))

    if not candidates:
        return None
    return max(candidates, key=lambda item: item[0])[1]


def _build_table_external_mfr_inputs(
    images_formula_list: list[list[dict[str, Any]]],
    model_list: list[list[dict[str, Any]]],
    page_sizes: list[tuple[int, int]],
) -> list[list[dict[str, Any]]]:
    """按最终版面筛选 High/Xhigh 表外行内公式,保留原始公式供 OCR 遮罩使用。"""
    mfr_inputs: list[list[dict[str, Any]]] = []
    for formulas, blocks, page_size in zip(images_formula_list, model_list, page_sizes, strict=True):
        table_entries = []
        for block in blocks:
            if block.get("type") != BlockType.TABLE:
                continue
            bbox = block.get("bbox")
            if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:
                continue
            try:
                coordinates = tuple(float(value) for value in bbox)
            except (TypeError, ValueError):
                continue
            if not all(math.isfinite(value) for value in coordinates):
                continue
            if coordinates[2] <= coordinates[0] or coordinates[3] <= coordinates[1]:
                continue
            table_bbox = _bbox_to_pixel_bbox(coordinates, page_size)
            if table_bbox is not None:
                table_entries.append({"table_bbox": table_bbox})

        page_inputs = []
        for formula in formulas:
            if formula.get("label") != "inline_formula":
                continue
            # MFD 框已经处于页面像素空间;表格 angle 不改变其页面上的归属范围。
            formula_bbox = formula.get("bbox")
            if formula_bbox is not None and _select_table_owner(formula_bbox, table_entries) is not None:
                continue
            page_inputs.append({**formula, "bbox": list(formula_bbox) if formula_bbox is not None else None})
        mfr_inputs.append(page_inputs)
    return mfr_inputs


def _collect_medium_table_tasks(
    model_list: list[list[dict[str, Any]]],
    inline_formula_list: list[list[dict[str, Any]]],
    np_images: list[np.ndarray],
) -> list[dict[str, Any]]:
    """从当前窗口 model_list 收集表格任务,并提前消费表内图片和行内公式。"""
    table_tasks: list[dict[str, Any]] = []
    for page_idx, (page_model_list, page_inline_formulas, np_image) in enumerate(
        zip(model_list, inline_formula_list, np_images)
    ):
        image_h, image_w = np_image.shape[:2]
        page_size = (image_w, image_h)
        table_entries: list[dict[str, Any]] = []
        for block in page_model_list:
            if block.get("type") != BlockType.TABLE or _has_non_empty_table_content(block):
                continue
            pixel_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)
            table_bbox = normalize_to_int_bbox(pixel_bbox, image_size=(image_h, image_w))
            if table_bbox is None:
                continue
            x0, y0, x1, y1 = table_bbox
            table_crop = np_image[y0:y1, x0:x1].copy()
            if table_crop.size == 0:
                continue
            table_entries.append(
                {
                    "table_block": block,
                    "table_bbox": table_bbox,
                    "table_crop": table_crop,
                    "angle": _normalize_visual_block_angle(block.get("angle", 0)),
                    "inline_objects": [],
                }
            )

        if not table_entries:
            continue

        consumed_image_ids: set[int] = set()
        consumed_formula_ids: set[int] = set()
        for block in page_model_list:
            if block.get("type") != BlockType.IMAGE:
                continue
            image_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)
            if image_bbox is None:
                continue
            owner = _select_table_owner(image_bbox, table_entries)
            if owner is None:
                continue
            owner["inline_objects"].append(
                {
                    "kind": "image",
                    "page_bbox": image_bbox,
                    "score": float(block.get("score", 1.0) or 0.0),
                }
            )
            consumed_image_ids.add(id(block))

        for formula in page_inline_formulas:
            latex = _normalize_medium_content(formula.get("latex", ""))
            formula_bbox = _bbox_to_pixel_bbox(formula.get("bbox"), page_size)
            if formula_bbox is None:
                continue
            owner = _select_table_owner(formula_bbox, table_entries)
            if owner is None:
                continue
            owner["inline_objects"].append(
                {
                    "kind": "formula",
                    "page_bbox": formula_bbox,
                    "latex": latex,
                    "score": float(formula.get("score", 1.0) or 0.0),
                }
            )
            consumed_formula_ids.add(id(formula))

        # 匹配完成后立即删除原始对象;后续 OCR 或结构识别失败均不回滚。
        page_model_list[:] = [block for block in page_model_list if id(block) not in consumed_image_ids]
        page_inline_formulas[:] = [formula for formula in page_inline_formulas if id(formula) not in consumed_formula_ids]

        for table_entry in table_entries:
            table_bbox = table_entry["table_bbox"]
            table_crop = table_entry["table_crop"]
            angle = table_entry["angle"]
            crop_h, crop_w = table_crop.shape[:2]
            rotated_crop = _rotate_visual_block_image_to_upright(table_crop, angle)
            rotated_h, rotated_w = rotated_crop.shape[:2]
            prepared_objects: list[dict[str, Any]] = []
            for inline_object in table_entry["inline_objects"]:
                overlap_bbox = _table_bbox_intersection(inline_object["page_bbox"], table_bbox)
                if overlap_bbox is None:
                    continue
                relative_bbox = (
                    float(overlap_bbox[0]) - float(table_bbox[0]),
                    float(overlap_bbox[1]) - float(table_bbox[1]),
                    float(overlap_bbox[2]) - float(table_bbox[0]),
                    float(overlap_bbox[3]) - float(table_bbox[1]),
                )
                rotated_bbox = _rotate_medium_table_bbox(relative_bbox, crop_w, crop_h, angle)
                if inline_object["kind"] == "formula":
                    latex = inline_object["latex"]
                    content = f"<eq>{html.escape(latex)}</eq>" if latex else ""
                    token_bbox = rotated_bbox
                else:
                    image_src = _encode_page_crop_as_jpeg_data_uri(np_image, inline_object["page_bbox"], angle)
                    content = f'<img src="{image_src}"/>' if image_src else ""
                    token_bbox = _get_medium_table_virtual_image_bbox(
                        rotated_bbox,
                        (rotated_w, rotated_h),
                    )
                prepared_objects.append(
                    {
                        **inline_object,
                        "mask_bbox": rotated_bbox,
                        "token_bbox": token_bbox,
                        "content": content,
                    }
                )

            table_tasks.append(
                {
                    "page_idx": page_idx,
                    "table_block": table_entry["table_block"],
                    "table_bbox": table_bbox,
                    "angle": angle,
                    "table_img": rotated_crop,
                    "wired_table_img": rotated_crop,
                    "ocr_result": [],
                    "atomic_token_indices": frozenset(),
                    "table_res": {},
                    "inline_objects": prepared_objects,
                }
            )
    return table_tasks


def _sort_medium_table_ocr_result(ocr_result: list[list[Any]], token_kinds: list[str]) -> frozenset[int]:
    """同步排序 OCR token 和对象类型,返回不可拆分对象在三元组列表中的索引。"""

    def sort_key(item: tuple[list[Any], str]) -> tuple[float, float]:
        """提取四点框的最小 y/x,兼容普通列表和 numpy 数组。"""
        box = np.asarray(item[0][0], dtype=np.float32).reshape(-1, 2)
        return float(np.min(box[:, 1])), float(np.min(box[:, 0]))

    sorted_items = sorted(zip(ocr_result, token_kinds, strict=True), key=sort_key)
    ocr_result[:] = [token for token, _ in sorted_items]
    return frozenset(index for index, (_, kind) in enumerate(sorted_items) if kind in {"image", "formula"})


def _prepare_medium_table_ocr_results(
    local_model_context: HybridLocalModelContext,
    table_tasks: list[dict[str, Any]],
) -> None:
    """遮盖表内图片和公式后逐表执行 OCR,并合并内联对象 token。"""
    from ....model.runtime.hybrid import run_ocr_inference

    table_ocr_model = None
    try:
        table_ocr_model = local_model_context.get_ocr_model(
            det_db_box_thresh=0.5,
            det_db_unclip_ratio=1.6,
            enable_merge_det_boxes=False,
        )
    except Exception as exc:
        logger.warning(f"Hybrid medium table OCR model initialization failed: {exc}")

    for table_task in table_tasks:
        ocr_result: list[list[Any]] = []
        token_kinds: list[str] = []
        bgr_image = rgb_to_bgr(table_task["table_img"])
        mask_boxes = [{"bbox": item["mask_bbox"]} for item in table_task["inline_objects"]]
        masked_image = mask_formula_regions_for_ocr_det(bgr_image, mask_boxes)

        if table_ocr_model is not None:
            try:
                page_ocr_results = run_ocr_inference(table_ocr_model.ocr, masked_image)
                raw_ocr_result = page_ocr_results[0] if page_ocr_results else None
                for raw_item in raw_ocr_result or []:
                    if not raw_item or len(raw_item) < 2:
                        continue
                    box, rec_result = raw_item[0], raw_item[1]
                    if not rec_result or len(rec_result) < 2:
                        continue
                    text, score = rec_result[0], rec_result[1]
                    normalized_text = _normalize_medium_content(text)
                    if not normalized_text:
                        continue
                    ocr_result.append(
                        [
                            np.asarray(box, dtype=np.float32),
                            html.escape(normalized_text),
                            float(score or 0.0),
                        ]
                    )
                    token_kinds.append("text")
            except Exception as exc:
                logger.warning(f"Hybrid medium table OCR failed: page_idx={table_task['page_idx']}, error={exc}")

        for inline_object in table_task["inline_objects"]:
            if not inline_object["content"]:
                continue
            ocr_result.append(
                [
                    _medium_bbox_to_quad(inline_object["token_bbox"]),
                    inline_object["content"],
                    inline_object["score"],
                ]
            )
            token_kinds.append(inline_object["kind"])
        table_task["atomic_token_indices"] = _sort_medium_table_ocr_result(ocr_result, token_kinds)
        table_task["ocr_result"] = ocr_result


def _trim_medium_table_html(html_code: Any) -> str:
    """从模型输出中截取核心 table HTML;未带外围标签时保留原字符串。"""
    if not isinstance(html_code, str):
        return ""
    stripped_html = html_code.strip()
    lower_html = stripped_html.lower()
    start_index = lower_html.find("<table")
    end_index = lower_html.rfind("</table>")
    if start_index >= 0 and end_index >= start_index:
        return stripped_html[start_index : end_index + len("</table>")]
    return stripped_html


def _apply_medium_table_recognition(
    local_model_context: HybridLocalModelContext,
    model_list: list[list[dict[str, Any]]],
    inline_formula_list: list[list[dict[str, Any]]],
    np_images: list[np.ndarray],
) -> None:
    """基于 model_list 执行 medium 表格解析,采用分类 batch、无线 batch、有线单表调度。"""
    table_tasks = _collect_medium_table_tasks(model_list, inline_formula_list, np_images)
    if not table_tasks:
        return

    _prepare_medium_table_ocr_results(local_model_context, table_tasks)

    try:
        local_model_context.table_cls_model.batch_predict(table_tasks)
    except Exception as exc:
        # 分类失败不阻断无线模型,未获得分类结果的表格按 wireless-only 处理。
        logger.warning(f"Hybrid medium table classification failed: {exc}")

    try:
        local_model_context.wireless_table_model.batch_predict(table_tasks)
    except Exception as exc:
        logger.warning(f"Hybrid medium wireless table recognition failed: {exc}")

    for table_task in table_tasks:
        cls_label = table_task["table_res"].get("cls_label")
        try:
            cls_score = float(table_task["table_res"].get("cls_score", 0.0) or 0.0)
        except (TypeError, ValueError):
            cls_score = 0.0
        use_wired_model = cls_label == AtomicModelName.WiredTable or (
            cls_label == AtomicModelName.WirelessTable and cls_score < 0.9
        )
        if use_wired_model:
            try:
                wireless_html = table_task["table_res"].get("html", "") or ""
                wired_html = local_model_context.wired_table_model.predict(
                    table_task["wired_table_img"],
                    table_task["ocr_result"],
                    wireless_html,
                    atomic_token_indices=table_task["atomic_token_indices"],
                )
                if wired_html is not None:
                    table_task["table_res"]["html"] = wired_html
            except Exception as exc:
                logger.warning(f"Hybrid medium wired table recognition failed: page_idx={table_task['page_idx']}, error={exc}")

        html_code = _trim_medium_table_html(table_task["table_res"].get("html", ""))
        if html_code:
            table_task["table_block"]["content"] = html_code


def _remove_flash_ocr_table_inner_blocks(
    images_list: list[dict[str, Any]],
    model_list: list[list[dict[str, Any]]],
) -> None:
    """按表格中心点归属规则移除 Flash OCR 表内图片、公式和公式编号块。"""
    inner_block_types = {
        BlockType.IMAGE,
        BlockType.EQUATION,
        RAW_FORMULA_NUMBER,
    }
    for image_dict, page_model_list in zip(images_list, model_list):
        page_size = _normalize_page_size(image_dict["img_pil"])
        table_entries = []
        for block in page_model_list:
            if block.get("type") != BlockType.TABLE:
                continue
            table_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)
            if table_bbox is not None:
                table_entries.append({"table_bbox": table_bbox})

        if not table_entries:
            continue

        retained_blocks = []
        for block in page_model_list:
            if block.get("type") not in inner_block_types:
                retained_blocks.append(block)
                continue
            block_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)
            if block_bbox is None or _select_table_owner(block_bbox, table_entries) is None:
                retained_blocks.append(block)
        page_model_list[:] = retained_blocks


def _fill_flash_ocr_table_contents(
    images_list: list[dict[str, Any]],
    model_list: list[list[dict[str, Any]]],
    local_model_context: HybridLocalModelContext,
) -> None:
    """为 Flash OCR 表格回填 OCR 空间投影文本。"""
    from ....model.runtime.hybrid import run_ocr_inference

    table_entries: list[dict[str, Any]] = []
    for page_idx, page_model_list in enumerate(model_list):
        table_idx = 0
        for block in page_model_list:
            if block.get("type") != BlockType.TABLE:
                continue
            block["content"] = ""
            table_entries.append(
                {
                    "page_idx": page_idx,
                    "table_idx": table_idx,
                    "block": block,
                }
            )
            table_idx += 1

    if not table_entries:
        return

    # 表格一旦认领内部对象便立即从 model_list 删除,后续文本回填失败也不恢复。
    _remove_flash_ocr_table_inner_blocks(images_list, model_list)

    try:
        table_ocr_model = local_model_context.get_ocr_model(
            det_db_box_thresh=0.5,
            det_db_unclip_ratio=1.6,
            enable_merge_det_boxes=False,
        )
    except Exception as exc:
        for table_entry in table_entries:
            logger.warning(
                "Flash OCR table text failed: "
                f"page_idx={table_entry['page_idx']}, "
                f"table_idx={table_entry['table_idx']}, "
                f"bbox={table_entry['block'].get('bbox')}, "
                f"error=OCR model initialization failed: {exc}"
            )
        return

    page_image_cache: dict[int, np.ndarray] = {}
    for table_entry in table_entries:
        page_idx = table_entry["page_idx"]
        table_idx = table_entry["table_idx"]
        table_block = table_entry["block"]
        try:
            if page_idx not in page_image_cache:
                page_image_cache[page_idx] = np.asarray(images_list[page_idx]["img_pil"]).copy()
            np_image = page_image_cache[page_idx]
            image_height, image_width = np_image.shape[:2]
            pixel_bbox = _bbox_to_pixel_bbox(
                table_block.get("bbox"),
                (image_width, image_height),
            )
            table_bbox = normalize_to_int_bbox(
                pixel_bbox,
                image_size=(image_height, image_width),
            )
            if table_bbox is None:
                raise ValueError("invalid table bbox")
            x0, y0, x1, y1 = table_bbox
            table_crop = np_image[y0:y1, x0:x1].copy()
            if table_crop.size == 0:
                raise ValueError("empty table crop")

            angle = _normalize_visual_block_angle(table_block.get("angle", 0))
            rotated_crop = _rotate_visual_block_image_to_upright(table_crop, angle)
            bgr_crop = rgb_to_bgr(rotated_crop)
            page_ocr_results = run_ocr_inference(table_ocr_model.ocr, bgr_crop)
            raw_ocr_result = page_ocr_results[0] if page_ocr_results else None
            rotated_height, rotated_width = rotated_crop.shape[:2]
            table_block["content"] = project_ocr_table_text(
                raw_ocr_result,
                (rotated_width, rotated_height),
            )
            if not table_block["content"]:
                logger.warning(
                    f"Flash OCR table text is empty: page_idx={page_idx}, table_idx={table_idx}, bbox={table_block.get('bbox')}"
                )
        except Exception as exc:
            logger.warning(
                "Flash OCR table text failed: "
                f"page_idx={page_idx}, "
                f"table_idx={table_idx}, bbox={table_block.get('bbox')}, error={exc}"
            )