Skip to content

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

27.1 KB
Raw Blame
# Copyright (c) Opendatalab. All rights reserved.
"""文本/公式 Span 构造、组行、post-OCR 与 block content 回填。"""

from __future__ import annotations


import math
from typing import TYPE_CHECKING, Any, Literal

import numpy as np
from docvortex.analyzers.pdf import PDF_NATIVE_SCRIPT_MARKUP_KEY, PDFTextEvidence, apply_text_evidence, prepare_text_evidence
from docvortex.content.text import merge_text_line_contents
from docvortex.document.pdf import PDFPage, PDFPageTextGeometry, PDFPageVectorGeometry, get_lines_from_chars
from PIL import Image

from ..snapshots import PageSnapshotCache, get_page_snapshot_entry

from .....model.ocr.image import rotate_vertical_crop_if_needed
from .....model.ocr.results import OcrConfidence
from .....types import BBox, BlockType, ContentType
from ..constants import (
    CODE_CONTENT_BLOCK_TYPES,
    LINE_METADATA_BLOCK_TYPES,
    TITLE_BLOCK_TYPES,
)
from ..model_inputs import _bbox_to_pixel_bbox, _sidecar_bbox_to_page_bbox
from .lines import group_spans_to_lines
from .models import _AnalyzeLine, _AnalyzeSpan
from .native import (
    MAX_NATIVE_TEXT_CHARS_PER_PAGE,
    SpanBlockMatcher,
    __replace_ligatures,
    __replace_unicode,
    _clear_post_ocr_fallback,
    _is_supported_rotation,
    _replace_private_use_chars,
    _restore_post_ocr_fallback,
    txt_spans_extract,
)

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


def _validate_text_formula_window_inputs(
    images_list: list[dict[str, Any]],
    pdf_pages: list[PDFPage],
    model_list: list[list[dict[str, Any]]],
    images_layout_res: list[list[dict[str, Any]]],
) -> None:
    """校验文本公式处理所需的窗口分页数据,避免 zip 静默截断。"""
    page_counts = {
        "images": len(images_list),
        "pdf_pages": len(pdf_pages),
        "model_list": len(model_list),
        "layout": len(images_layout_res),
    }
    if len(set(page_counts.values())) != 1:
        raise ValueError(f"Hybrid text/formula window page count mismatch: {page_counts}")

    for page_idx, image_dict in enumerate(images_list):
        if image_dict.get("img_pil") is None:
            raise ValueError(f"Hybrid text/formula window image is missing img_pil: page_idx={page_idx}")
        scale = float(image_dict.get("scale", 0) or 0)
        if scale <= 0:
            raise ValueError(f"Hybrid text/formula window image scale must be positive: page_idx={page_idx}")


def _build_pdf_text_line_spans(pdf_page: PDFPage) -> list[_AnalyzeSpan]:
    """将标准方向的 共享原生文本行 转为私有 span,并复用现有字符清洗规则。"""
    page_spans: list[_AnalyzeSpan] = []
    for pdf_line in get_lines_from_chars(pdf_page.get_chars()):
        try:
            rotation = float(pdf_line.get("rotation", 0.0) or 0.0)
        except (TypeError, ValueError):
            continue
        if not _is_supported_rotation(rotation):
            continue

        raw_bbox = pdf_line.get("bbox")
        bbox = getattr(raw_bbox, "bbox", raw_bbox)
        try:
            if bbox is None or len(bbox) != 4:
                continue
            x0, y0, x1, y1 = [float(value) for value in bbox]
        except (TypeError, ValueError):
            continue
        if x1 <= x0 or y1 <= y0:
            continue

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

        page_spans.append(
            _AnalyzeSpan(
                type=ContentType.TEXT,
                bbox=(x0, y0, x1, y1),
                content=content,
                score=1.0,
            )
        )
    return page_spans


def _build_page_text_formula_spans(
    page_inline_formula_list: list[dict[str, Any]],
    page_ocr_res_list: list[dict[str, Any]],
    page_size: tuple[float, float],
    render_scale: float,
) -> list[_AnalyzeSpan]:
    """将当前页行内公式和 OCR 结果转换为私有 span,供正文与公式共同组行。"""
    page_spans: list[_AnalyzeSpan] = []
    for formula in page_inline_formula_list:
        bbox = _sidecar_bbox_to_page_bbox(formula.get("bbox"), page_size, render_scale)
        if bbox is None:
            continue
        page_spans.append(
            _AnalyzeSpan(
                type=ContentType.INLINE_EQUATION,
                bbox=bbox,
                content=str(
                    formula.get("content", "")
                    if formula.get("content_format") == "text_with_inline_math"
                    else formula.get("latex", "") or ""
                ).strip(),
                score=float(formula.get("score", 0.0) or 0.0),
                content_format=(
                    "text_with_inline_math" if formula.get("content_format") == "text_with_inline_math" else "default"
                ),
            )
        )

    for ocr_res in page_ocr_res_list:
        bbox = _sidecar_bbox_to_page_bbox(ocr_res.get("bbox"), page_size, render_scale)
        if bbox is None:
            continue
        page_spans.append(
            _AnalyzeSpan(
                type=ContentType.TEXT,
                bbox=bbox,
                content=str(ocr_res.get("text", "") or ""),
                score=float(ocr_res.get("score", 0.0) or 0.0),
            )
        )
    return page_spans


def _get_page_inline_formula_regions(
    page_inline_formula_list: list[dict[str, Any]],
    page_size: tuple[float, float],
    render_scale: float,
) -> list[BBox]:
    """把当前页 layout/MFR 行内公式统一转换成页面 point bbox。"""

    return [
        bbox
        for formula in page_inline_formula_list
        if (bbox := _sidecar_bbox_to_page_bbox(formula.get("bbox"), page_size, render_scale)) is not None
    ]


def _get_page_table_regions(
    page_model_list: list[dict[str, Any]],
    page_size: tuple[float, float],
) -> list[BBox]:
    """把当前页模型表格 bbox 转成脚本行合并使用的页面 point 区域。"""

    page_width, page_height = page_size
    regions: list[BBox] = []
    for block in page_model_list:
        if block.get("type") != BlockType.TABLE:
            continue
        raw_bbox = block.get("bbox")
        if not isinstance(raw_bbox, (list, tuple)) or len(raw_bbox) != 4:
            continue
        try:
            bbox = tuple(float(value) for value in raw_bbox)
        except (TypeError, ValueError):
            continue
        if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
            continue
        if all(0.0 <= value <= 1.0 for value in bbox):
            bbox = (
                bbox[0] * page_width,
                bbox[1] * page_height,
                bbox[2] * page_width,
                bbox[3] * page_height,
            )
        regions.append(bbox)
    return regions


def _protect_code_span_spacing(spans: list[_AnalyzeSpan], blocks: list[dict[str, Any]], page_size: tuple[float, float]) -> None:
    """在整页虚拟文本块回填之前保留实际代码区域,避免新增词界改写代码。"""
    regions = [
        region
        for block in blocks
        if block.get("type") in CODE_CONTENT_BLOCK_TYPES
        and (region := _sidecar_bbox_to_page_bbox(block.get("bbox"), page_size, 1.0)) is not None
    ]
    if not regions:
        return
    for span in spans:
        cx = (span.bbox[0] + span.bbox[2]) / 2
        cy = (span.bbox[1] + span.bbox[3]) / 2
        if any(x0 <= cx <= x1 and y0 <= cy <= y1 for x0, y0, x1, y1 in regions):
            span.metadata["_native_tight_spacing"] = False


def _fill_native_pdf_text_spans(
    pdf_page: PDFPage,
    page_spans: list[_AnalyzeSpan],
    page_pil_image: Image.Image,
    render_scale: float,
    page_size: tuple[float, float],
    *,
    page_text_geometry: PDFPageTextGeometry | None = None,
    detect_scripts: bool = True,
    _native_text: Any = None,
) -> list[_AnalyzeSpan]:
    """复用原生 PDF 字符回填逻辑,并允许共享同页删除线检测读取的字符。"""
    page_width, page_height = page_size
    virtual_block = (0, 0, page_width, page_height, None, None, None, BlockType.TEXT)
    return txt_spans_extract(
        pdf_page,
        page_spans,
        page_pil_image,
        render_scale,
        [virtual_block],
        [],
        page_chars=page_text_geometry.chars if page_text_geometry is not None else None,
        tight_bboxes=page_text_geometry.tight_bboxes if page_text_geometry is not None else None,
        origins=page_text_geometry.origins if page_text_geometry is not None else None,
        detect_scripts=detect_scripts,
        **({"_native_text": _native_text} if _native_text is not None else {}),
    )


def _group_page_spans_by_block(
    page_model_list: list[dict[str, Any]],
    page_spans: list[_AnalyzeSpan],
    page_size: tuple[float, float],
    target_block_types: set[str],
) -> dict[int, list[_AnalyzeLine]]:
    """按 block 原始顺序消费 span,并使用现有文本修复逻辑形成真实行。"""
    span_matcher = SpanBlockMatcher(page_spans)
    block_lines: dict[int, list[_AnalyzeLine]] = {}
    for block_idx, block_item in enumerate(page_model_list):
        block_type = str(block_item.get("type") or block_item.get("label") or "")
        if block_type not in target_block_types:
            continue
        block_bbox = _bbox_to_pixel_bbox(block_item.get("bbox"), page_size)
        if block_bbox is None:
            block_lines[block_idx] = []
            continue

        block_lines[block_idx] = group_spans_to_lines(span_matcher.collect_for_block(block_bbox))
    return block_lines


def _recover_native_drop_caps(
    page_model_list: list[dict[str, Any]],
    block_lines: dict[int, list[_AnalyzeLine]],
    page_size: tuple[float, float],
    geometry: PDFPageTextGeometry | None,
    excluded_regions: list[BBox],
) -> None:
    """仅补回正文首行紧邻且未被认领的大号首字,组行完成后更新几何避免串行。"""
    if geometry is None:
        return
    claimed: set[int] = set()
    all_spans = [span for lines in block_lines.values() for line in lines for span in line.spans]
    # 先按实际字形高度筛选少量候选,普通页面不为每个正文块重扫全部字符。
    candidate_positions: dict[str, list[int]] = {}
    for position in range(1, len(geometry.chars)):
        cap, following = geometry.chars[position - 1 : position + 1]
        cap_box = geometry.tight_bboxes.get(cap.get("char_idx"))
        next_box = geometry.tight_bboxes.get(following.get("char_idx"))
        if cap_box is not None and next_box is not None and next_box[3] > next_box[1]:
            if cap_box[3] - cap_box[1] >= 1.8 * (next_box[3] - next_box[1]):
                candidate_positions.setdefault(str(following.get("char", "")), []).append(position)
    for block_index, lines in block_lines.items():
        if not lines or page_model_list[block_index].get("type") != BlockType.TEXT:
            continue
        first_line = lines[0]
        if not first_line.spans or first_line.spans[0].type != ContentType.TEXT:
            continue
        first_span = first_line.spans[0]
        if not first_span.content or first_span.image is not None or not first_span.metadata.get("_native_tight_spacing", True):
            continue
        block_bbox = _bbox_to_pixel_bbox(page_model_list[block_index].get("bbox"), page_size)
        if block_bbox is None:
            continue
        for position in candidate_positions.get(first_span.content[0], []):
            following = geometry.chars[position]
            cap = geometry.chars[position - 1]
            cap_text = str(cap.get("char", ""))
            cap_index, next_index = cap.get("char_idx"), following.get("char_idx")
            if (
                len(cap_text) != 1
                or not cap_text.isascii()
                or not cap_text.isalpha()
                or cap_index is None
                or next_index != cap_index + 1
                or cap_index in claimed
                or cap.get("visible") is False
                or cap.get("text_render_mode") == 3
            ):
                continue
            cap_bbox = geometry.tight_bboxes.get(cap_index)
            next_bbox = geometry.tight_bboxes.get(next_index)
            if cap_bbox is None or next_bbox is None or not all(math.isfinite(value) for value in (*cap_bbox, *next_bbox)):
                continue
            angles = (float(cap.get("writing_angle", 0)), float(following.get("writing_angle", 0)))
            if any(not math.isfinite(angle) or abs(math.degrees(angle)) > 0.1 for angle in angles):
                continue
            height = next_bbox[3] - next_bbox[1]
            if (
                height <= 0
                or cap_bbox[3] - cap_bbox[1] < 1.8 * height
                or abs(cap_bbox[1] - next_bbox[1]) > 0.25 * height
                or not 0 <= next_bbox[0] - cap_bbox[2] <= 0.5 * height
                or not 0 <= next_bbox[0] - first_span.bbox[0] <= 0.5 * height
                or not first_span.bbox[1] <= (next_bbox[1] + next_bbox[3]) / 2 <= first_span.bbox[3]
                or not (
                    block_bbox[0] <= cap_bbox[0] < cap_bbox[2] <= block_bbox[2]
                    and block_bbox[1] <= cap_bbox[1] < cap_bbox[3] <= block_bbox[3]
                )
            ):
                continue
            center_x, center_y = (cap_bbox[0] + cap_bbox[2]) / 2, (cap_bbox[1] + cap_bbox[3]) / 2
            if any(box[0] <= center_x <= box[2] and box[1] <= center_y <= box[3] for box in excluded_regions):
                continue
            # 已由其他行、公式或相邻栏框完整覆盖的首字不能再补入当前正文。
            if any(span.bbox[0] <= center_x <= span.bbox[2] and span.bbox[1] <= center_y <= span.bbox[3] for span in all_spans):
                continue
            first_span.content = cap_text + first_span.content
            first_span.bbox = (
                min(first_span.bbox[0], cap_bbox[0]),
                min(first_span.bbox[1], cap_bbox[1]),
                max(first_span.bbox[2], cap_bbox[2]),
                max(first_span.bbox[3], cap_bbox[3]),
            )
            first_line.bbox = (
                min(first_line.bbox[0], cap_bbox[0]),
                min(first_line.bbox[1], cap_bbox[1]),
                max(first_line.bbox[2], cap_bbox[2]),
                max(first_line.bbox[3], cap_bbox[3]),
            )
            claimed.add(cap_index)
            break


def _apply_window_post_ocr(
    local_model_context: HybridLocalModelContext,
    page_block_lines_list: list[dict[int, list[_AnalyzeLine]]],
) -> None:
    """在当前窗口内识别原生字符不足的 span,保持 finalize 后置 OCR 的回退语义。"""
    from .....model.runtime.hybrid import run_ocr_inference

    need_ocr_spans: list[_AnalyzeSpan] = []
    img_crop_list: list[np.ndarray] = []
    for block_lines in page_block_lines_list:
        for lines in block_lines.values():
            for line in lines:
                for span in line.spans:
                    if span.image is None:
                        continue
                    need_ocr_spans.append(span)
                    img_crop_list.append(rotate_vertical_crop_if_needed(span.image))
                    span.image = None

    if not img_crop_list:
        return
    ocr_res_list = run_ocr_inference(
        local_model_context.ocr_model.ocr,
        img_crop_list,
        det=False,
        tqdm_enable=True,
    )[0]
    if len(ocr_res_list) != len(need_ocr_spans):
        raise ValueError(
            f"Hybrid post-OCR result count mismatch: ocr_res_list={len(ocr_res_list)}, need_ocr_spans={len(need_ocr_spans)}"
        )

    for span, ocr_res in zip(need_ocr_spans, ocr_res_list):
        ocr_text, ocr_score = ocr_res
        if ocr_score > OcrConfidence.min_confidence:
            span.content = ocr_text
            span.score = float(f"{ocr_score:.3f}")
            _clear_post_ocr_fallback(span)
        elif _restore_post_ocr_fallback(span):
            continue
        else:
            span.content = ""
            span.score = 0.0


def _line_content_parts(line: _AnalyzeLine) -> list[tuple[str, str]]:
    """提取一行内可输出的文本与行内公式,公式统一包装为反斜杠圆括号格式。"""
    parts: list[tuple[str, str]] = []
    for span in line.spans:
        if span.type == ContentType.TEXT:
            content = str(span.content or "").strip()
        elif span.type == ContentType.INLINE_EQUATION:
            latex = str(span.content or "").strip()
            content = latex if span.content_format == "text_with_inline_math" else (f"\\({latex}\\)" if latex else "")
        else:
            continue
        if content:
            parts.append((span.type, content))
    return parts


def _replace_residual_private_use_text(block_lines: dict[int, list[_AnalyzeLine]]) -> None:
    """后置 OCR 及失败恢复完成后清理正文 PUA,避免提前替换影响检测或紧排。"""
    for lines in block_lines.values():
        for line in lines:
            for span in line.spans:
                if span.type == ContentType.TEXT:
                    span.content = _replace_private_use_chars(span.content)


def _lines_to_block_content(lines: list[_AnalyzeLine], block_type: str) -> str:
    """将真实行折叠为统一 block content,保留目录/代码换行并处理自然语言跨行连接。"""
    content_lines = [parts for line in lines if (parts := _line_content_parts(line))]
    if not content_lines:
        return ""

    rendered_lines = [" ".join(content for _, content in parts) for parts in content_lines]
    if block_type == BlockType.INDEX or block_type in CODE_CONTENT_BLOCK_TYPES:
        return "\n".join(rendered_lines).strip()

    return merge_text_line_contents(rendered_lines)


def _lines_have_native_script_markup(lines: list[_AnalyzeLine]) -> bool:
    """判断组行结果是否实际包含 detector-owned 上下标标签。"""
    return any(
        span.metadata.get(PDF_NATIVE_SCRIPT_MARKUP_KEY) is True and ("<sup>" in span.content or "<sub>" in span.content)
        for line in lines
        for span in line.spans
    )


def _build_ocr_det_line_items(lines: list[_AnalyzeLine], page_size: tuple[float, float]) -> list[dict[str, Any]]:
    """将 Analyze 私有行转换为归一化行框。"""
    line_items = []
    for line in lines:
        normalized_bbox = _page_bbox_to_unit_bbox(line.bbox, page_size)
        if normalized_bbox is not None:
            line_items.append({"bbox": normalized_bbox})
    return line_items


def _apply_block_content_and_line_metadata(
    page_model_list: list[dict[str, Any]],
    block_lines: dict[int, list[_AnalyzeLine]],
    page_size: tuple[float, float],
) -> None:
    """将组行结果回填到 block,并为正文、视觉标题和视觉脚注保存行框。"""
    for block_item in page_model_list:
        block_type = str(block_item.get("type") or block_item.get("label") or "")
        if block_type in LINE_METADATA_BLOCK_TYPES:
            block_item["lines"] = []
        else:
            block_item.pop("lines", None)

    for block_idx, lines in block_lines.items():
        block_item = page_model_list[block_idx]
        block_type = str(block_item.get("type") or block_item.get("label") or "")
        block_content = block_item.get("content")
        has_nonempty_content = bool(block_content.strip()) if isinstance(block_content, str) else bool(block_content)
        if not has_nonempty_content:
            block_item["content"] = _lines_to_block_content(lines, block_type)
            if _lines_have_native_script_markup(lines):
                block_item[PDF_NATIVE_SCRIPT_MARKUP_KEY] = True

        if block_type in LINE_METADATA_BLOCK_TYPES:
            block_item["lines"] = _build_ocr_det_line_items(lines, page_size)


def _fill_window_block_content_and_lines(
    images_list: list[dict[str, Any]],
    pdf_pages: list[PDFPage],
    model_list: list[list[dict[str, Any]]],
    inline_formula_list: list[list[dict[str, Any]]],
    ocr_res_list: list[list[dict[str, Any]]],
    parse_mode: Literal["txt", "ocr"],
    effort: Literal["flash", "medium", "high", "xhigh"],
    ocr_det_type: set[str],
    local_model_context: HybridLocalModelContext,
    page_text_geometries: list[PDFPageTextGeometry | None] | None = None,
    *,
    page_vector_geometries: list[PDFPageVectorGeometry | None] | None = None,
    page_snapshots: PageSnapshotCache | None = None,
) -> list[list[dict[str, Any]]]:
    """按页完成 span 回填与行级元数据构造,返回不含页面级 sidecar 的 model list。"""
    page_counts = {
        "images": len(images_list),
        "pdf_pages": len(pdf_pages),
        "model_list": len(model_list),
        "inline_formulas": len(inline_formula_list),
        "ocr_results": len(ocr_res_list),
    }
    if page_text_geometries is not None:
        page_counts["text_geometries"] = len(page_text_geometries)
    if page_vector_geometries is not None:
        page_counts["vector_geometries"] = len(page_vector_geometries)
    if page_snapshots is not None:
        page_counts["snapshots"] = len(page_snapshots)
    if len(set(page_counts.values())) != 1:
        raise ValueError(f"Hybrid block content page count mismatch: {page_counts}")

    use_shared_script_sidecar = parse_mode == "txt" and effort in {"medium", "high", "xhigh"}
    target_block_types = set(ocr_det_type) | TITLE_BLOCK_TYPES | {BlockType.TEXT}
    page_block_line_results: list[
        tuple[
            list[dict[str, Any]],
            dict[int, list[_AnalyzeLine]],
            tuple[float, float],
            PDFTextEvidence,
        ]
    ] = []
    for page_idx, (image_dict, pdf_page, page_model_list, page_inline_formula_list, page_ocr_res_list) in enumerate(
        zip(
            images_list,
            pdf_pages,
            model_list,
            inline_formula_list,
            ocr_res_list,
            strict=True,
        )
    ):
        page_pil_image = image_dict["img_pil"]
        render_scale = float(image_dict["scale"])
        page_size = (float(pdf_page.size[0]), float(pdf_page.size[1]))
        page_spans = _build_page_text_formula_spans(
            page_inline_formula_list,
            page_ocr_res_list,
            page_size,
            render_scale,
        )
        inline_math_regions = _get_page_inline_formula_regions(
            page_inline_formula_list,
            page_size,
            render_scale,
        )
        table_regions = _get_page_table_regions(
            page_model_list,
            page_size,
        )
        evidence = PDFTextEvidence(page_size)
        if parse_mode == "txt":
            _protect_code_span_spacing(page_spans, page_model_list, page_size)
            native_text_owner = None
            page_text_geometry = page_text_geometries[page_idx] if page_text_geometries is not None else None
            try:
                page_char_count = pdf_page.get_char_count()
            except Exception:
                page_char_count = None
            if (
                not isinstance(page_char_count, int)
                or isinstance(page_char_count, bool)
                or page_char_count <= MAX_NATIVE_TEXT_CHARS_PER_PAGE
            ):
                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:
                    if callable(getattr(snapshot_entry.text_owner, "assign_spans", None)) and callable(
                        getattr(snapshot_entry.text_owner, "supports_span_matching", None)
                    ):
                        native_text_owner = snapshot_entry.text_owner
                    evidence = prepare_text_evidence(
                        pdf_page,
                        snapshot=snapshot_entry.get_full_snapshot(pdf_page),
                        excluded_script_regions=inline_math_regions,
                        table_regions=table_regions,
                    )
                else:
                    evidence = prepare_text_evidence(
                        pdf_page,
                        geometry=page_text_geometry,
                        vector_geometry=vector_geometry,
                        excluded_script_regions=inline_math_regions,
                        table_regions=table_regions,
                    )
                page_text_geometry = evidence.geometry
                if page_text_geometries is not None:
                    page_text_geometries[page_idx] = page_text_geometry
            page_spans = _fill_native_pdf_text_spans(
                pdf_page,
                page_spans,
                page_pil_image,
                render_scale,
                page_size,
                page_text_geometry=page_text_geometry,
                detect_scripts=not use_shared_script_sidecar,
                **({"_native_text": native_text_owner} if native_text_owner is not None else {}),
            )
            # 后续只消费已物化证据;逐页释放 Rust owner,避免与窗口 Python 几何长期双份驻留。
            if page_snapshots is not None:
                entry = page_snapshots[page_idx]
                if entry is not None:
                    entry.close()
                page_snapshots[page_idx] = None

        block_lines = _group_page_spans_by_block(
            page_model_list,
            page_spans,
            page_size,
            target_block_types,
        )
        if parse_mode == "txt":
            _recover_native_drop_caps(
                page_model_list, block_lines, page_size, evidence.geometry, inline_math_regions + table_regions
            )
        page_block_line_results.append(
            (
                page_model_list,
                block_lines,
                page_size,
                evidence,
            )
        )

    if parse_mode == "txt":
        _apply_window_post_ocr(
            local_model_context,
            [block_lines for _, block_lines, _, _evidence in page_block_line_results],
        )

    for (
        page_model_list,
        block_lines,
        page_size,
        evidence,
    ) in page_block_line_results:
        if parse_mode == "txt":
            _replace_residual_private_use_text(block_lines)
        _apply_block_content_and_line_metadata(
            page_model_list,
            block_lines,
            page_size,
        )
        apply_text_evidence(page_model_list, evidence)
    return model_list


def _page_bbox_to_unit_bbox(bbox: BBox, page_size: tuple[float, float]) -> list[float] | None:
    """将 PDF point bbox 转为页面级 0-1 坐标,并统一保留三位小数。"""
    page_width, page_height = page_size
    if page_width <= 0 or page_height <= 0 or len(bbox) != 4:
        return None
    x0, y0, x1, y1 = [float(value) for value in bbox]
    if x1 <= x0 or y1 <= y0:
        return None
    normalized_bbox = [
        round(max(0.0, min(1.0, x0 / page_width)), 3),
        round(max(0.0, min(1.0, y0 / page_height)), 3),
        round(max(0.0, min(1.0, x1 / page_width)), 3),
        round(max(0.0, min(1.0, y1 / page_height)), 3),
    ]
    if normalized_bbox[2] <= normalized_bbox[0] or normalized_bbox[3] <= normalized_bbox[1]:
        return None
    return normalized_bbox