Skip to content

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

feat: enhance PDF text analysis with formula candidate detection and inline math region handling

myhlolib07554ea5a36
diff --git a/mineru/backend/analysis/pdf/text/native.py b/mineru/backend/analysis/pdf/text/native.py
index 240e7097..159dd388 100644
--- a/mineru/backend/analysis/pdf/text/native.py
+++ b/mineru/backend/analysis/pdf/text/native.py
@@ -8,8 +8,7 @@ import math
import re
import statistics
import unicodedata
-from dataclasses import dataclass
-from typing import Any, Callable, Literal, cast
+from typing import Any, Callable, cast
import cv2
import numpy as np
@@ -17,11 +16,12 @@ from loguru import logger
from pdftext.schema import Char
from .....types import BBox, BlockType, ContentType
-from .....utils.image import calculate_contrast
from .....model.flash.pdf.document import PDFPage, get_lines_from_chars
+from .....model.flash.pdf.script_geometry import ScriptRole, classify_char_script_roles
from .....model.flash.pdf.text_styles import PDF_NATIVE_SCRIPT_MARKUP_KEY
-from ..images import get_crop_img
from .....utils.geometry import calculate_overlap_area_in_bbox1_area_ratio
+from .....utils.image import calculate_contrast
+from ..images import get_crop_img
from .models import _AnalyzeSpan
MAX_NATIVE_TEXT_CHARS_PER_PAGE = 65535
@@ -609,85 +609,9 @@ LINE_START_FLAG = (
)
Span_Height_Ratio = 0.33 # 字符的中轴和span的中轴高度差不能超过1/3span高度
-SCRIPT_BODY_COMPARABLE_HEIGHT_RATIO = 0.9
-SCRIPT_BASELINE_ABSOLUTE_TOLERANCE = 0.35
-SCRIPT_BASELINE_LOOSE_HEIGHT_RATIO = 0.04
-SCRIPT_ORIGIN_MIN_SHIFT_ABSOLUTE = 0.5
-SCRIPT_ORIGIN_MIN_SHIFT_RATIO = 0.12
-SCRIPT_TIGHT_HEIGHT_RATIO = 0.9
-SCRIPT_STRONG_SHIFT_RATIO = 0.3
-SCRIPT_STRONG_MAX_HEIGHT_RATIO = 1.1
-SCRIPT_CONSENSUS_TIGHT_HEIGHT_RATIO = 0.88
-SCRIPT_CONSENSUS_ORIGIN_SHIFT_RATIO = 0.22
-SCRIPT_CONSENSUS_TIGHT_CENTER_SHIFT_RATIO = 0.3
-SCRIPT_CONSENSUS_LOOSE_CENTER_SHIFT_RATIO = 0.15
-SCRIPT_LOOSE_HEIGHT_ANOMALY_RATIO = 1.35
-SCRIPT_COMPONENT_FORWARD_GAP_RATIO = 1.5
-SCRIPT_COMPONENT_X_BACKTRACK_RATIO = 0.5
-SCRIPT_COMPONENT_SEED_GAP_RATIO = 0.5
-SCRIPT_COMPONENT_SEED_MAX_POSITION_DISTANCE = 4
-SCRIPT_COMPONENT_MIN_OFFSET_RATIO = 0.08
-SCRIPT_COMPONENT_MAX_HEIGHT_RATIO = 1.1
SPAN_FILL_LOCAL_ROTATION_MAX_DEGREES = 30.0
CONTROL_LINE_BREAK_CHARS = {"\r", "\n"}
-
-_ScriptRole = Literal["body", "sup", "sub"]
-_ScriptMarkRole = Literal["sup", "sub"]
-
-
-@dataclass(frozen=True, slots=True)
-class _ScriptCharFeature:
- """保存单个字符参与纯几何上下标判定所需的只读特征。"""
-
- index: int
- text: str
- loose_bbox: BBox
- tight_bbox: BBox | None
- origin: tuple[float, float] | None
- is_valid: bool
- is_body_anchor: bool
-
- @property
- def loose_height(self) -> float:
- """返回 loose bbox 高度。"""
- return self.loose_bbox[3] - self.loose_bbox[1]
-
- @property
- def loose_center_y(self) -> float:
- """返回 loose bbox 中心 y。"""
- return (self.loose_bbox[1] + self.loose_bbox[3]) / 2
-
- @property
- def tight_height(self) -> float:
- """返回 tight bbox 高度,无有效框时返回零。"""
- if self.tight_bbox is None:
- return 0.0
- return self.tight_bbox[3] - self.tight_bbox[1]
-
- @property
- def tight_center_y(self) -> float | None:
- """返回 tight bbox 中心 y。"""
- if self.tight_bbox is None:
- return None
- return (self.tight_bbox[1] + self.tight_bbox[3]) / 2
-
-
-@dataclass(frozen=True, slots=True)
-class _ScriptBodyBand:
- """表示当前视觉组件的正文 origin 基线与双 bbox 参考高度。"""
-
- baseline: float
- tight_height: float
- loose_height: float
- member_indices: frozenset[int]
-
-
-@dataclass(frozen=True, slots=True)
-class _ScriptBaselineCluster:
- """表示共享近似字符 origin 的正文或角标基线簇。"""
-
- baseline: float
- member_indices: tuple[int, ...]
+_ScriptRole = ScriptRole
def _is_private_use_char(char: str) -> bool:
@@ -813,467 +737,6 @@ def _get_char_bbox_metrics_list(chars: list[Char]) -> list[dict[str, float]]:
return [_get_char_bbox_metrics(char) for char in chars]
-def _get_script_role(offset: float) -> _ScriptMarkRole:
- """把相对正文 origin 基线的纵向偏移转换为上下标角色。"""
- return "sub" if offset > 0 else "sup"
-
-
-def _build_script_features(
- chars: list[Char],
- tight_bboxes: dict[int, BBox],
- origins: dict[int, tuple[float, float]],
- protected_body_indices: set[int],
-) -> list[_ScriptCharFeature]:
- """一次性构造 loose/tight/origin 三类字符几何特征。"""
- features = []
- for index, char in enumerate(chars):
- text = str(char.get("char", ""))
- char_idx = _char_geometry_key(char)
- loose_bbox = _coerce_finite_bbox(char.get("bbox")) or (0.0, 0.0, 0.0, 0.0)
- tight_bbox = _coerce_finite_bbox(tight_bboxes.get(char_idx)) if char_idx is not None else None
- raw_origin = origins.get(char_idx) if char_idx is not None else None
- origin = None
- if raw_origin is not None:
- try:
- candidate_origin = (float(raw_origin[0]), float(raw_origin[1]))
- except (IndexError, TypeError, ValueError):
- candidate_origin = None
- if candidate_origin is not None and all(math.isfinite(value) for value in candidate_origin):
- origin = candidate_origin
- is_valid = text not in CONTROL_LINE_BREAK_CHARS and not text.isspace() and tight_bbox is not None and origin is not None
- features.append(
- _ScriptCharFeature(
- index=index,
- text=text,
- loose_bbox=loose_bbox,
- tight_bbox=tight_bbox,
- origin=origin,
- is_valid=is_valid,
- is_body_anchor=is_valid and text.isalnum() and index not in protected_body_indices,
- )
- )
- return features
-
-
-def _script_quantile(values: list[float], fraction: float) -> float:
- """返回适合小样本基线簇的稳定分位数。"""
- if not values:
- return 0.0
- ordered = sorted(values)
- index = min(len(ordered) - 1, max(0, round((len(ordered) - 1) * fraction)))
- return ordered[index]
-
-
-def _split_script_visual_components(features: list[_ScriptCharFeature]) -> list[list[int]]:
- """按换行、x 回退和大间隙切分独立视觉组件。"""
- valid_heights = [feature.loose_height for feature in features if feature.loose_height > 0]
- scale = statistics.median(valid_heights) if valid_heights else 1.0
- components: list[list[int]] = []
- current: list[int] = []
- previous_visible: _ScriptCharFeature | None = None
-
- for feature in features:
- if feature.text in CONTROL_LINE_BREAK_CHARS:
- if current:
- components.append(current)
- current = []
- previous_visible = None
- continue
- if feature.text.isspace():
- if current:
- components.append(current)
- current = []
- previous_visible = None
- continue
-
- if feature.is_valid and previous_visible is not None:
- x_backtrack = previous_visible.loose_bbox[0] - feature.loose_bbox[0]
- forward_gap = feature.loose_bbox[0] - previous_visible.loose_bbox[2]
- if (
- x_backtrack > scale * SCRIPT_COMPONENT_X_BACKTRACK_RATIO
- or forward_gap > scale * SCRIPT_COMPONENT_FORWARD_GAP_RATIO
- ):
- if current:
- components.append(current)
- current = []
- previous_visible = None
-
- current.append(feature.index)
- if feature.is_valid:
- previous_visible = feature
-
- if current:
- components.append(current)
- return components
-
-
-def _cluster_script_baselines(
- features: list[_ScriptCharFeature],
- component_indices: list[int],
-) -> tuple[list[_ScriptBaselineCluster], float]:
- """按字符 origin y 聚类当前组件的字母数字基线。"""
- anchors = [features[index] for index in component_indices if features[index].is_body_anchor]
- if not anchors:
- return [], 0.0
- median_loose_height = statistics.median(feature.loose_height for feature in anchors)
- tolerance = max(
- SCRIPT_BASELINE_ABSOLUTE_TOLERANCE,
- median_loose_height * SCRIPT_BASELINE_LOOSE_HEIGHT_RATIO,
- )
- groups: list[list[int]] = []
- for feature in sorted(anchors, key=lambda item: item.origin[1] if item.origin is not None else 0.0):
- baseline = feature.origin[1] if feature.origin is not None else 0.0
- if not groups:
- groups.append([feature.index])
- continue
- previous_baseline = statistics.median(
- features[index].origin[1] for index in groups[-1] if features[index].origin is not None
- )
- if abs(baseline - previous_baseline) <= tolerance:
- groups[-1].append(feature.index)
- else:
- groups.append([feature.index])
- return (
- [
- _ScriptBaselineCluster(
- baseline=statistics.median(features[index].origin[1] for index in group if features[index].origin is not None),
- member_indices=tuple(group),
- )
- for group in groups
- ],
- tolerance,
- )
-
-
-def _cluster_tight_height(features: list[_ScriptCharFeature], cluster: _ScriptBaselineCluster) -> float:
- """返回基线簇的高分位 tight 高度。"""
- return _script_quantile(
- [features[index].tight_height for index in cluster.member_indices if features[index].tight_height > 0],
- 0.9,
- )
-
-
-def _cluster_loose_height(features: list[_ScriptCharFeature], cluster: _ScriptBaselineCluster) -> float:
- """返回基线簇的高分位 loose 高度。"""
- return _script_quantile(
- [features[index].loose_height for index in cluster.member_indices if features[index].loose_height > 0],
- 0.9,
- )
-
-
-def _cluster_tight_center(features: list[_ScriptCharFeature], cluster: _ScriptBaselineCluster) -> float:
- """返回基线簇的 tight bbox 中心中位数。"""
- return statistics.median(
- features[index].tight_center_y for index in cluster.member_indices if features[index].tight_center_y is not None
- )
-
-
-def _cluster_loose_center(features: list[_ScriptCharFeature], cluster: _ScriptBaselineCluster) -> float:
- """返回基线簇的 loose bbox 中心中位数。"""
- return statistics.median(features[index].loose_center_y for index in cluster.member_indices)
-
-
-def _script_cluster_has_consistent_displacement(
- features: list[_ScriptCharFeature],
- cluster: _ScriptBaselineCluster,
- body_cluster: _ScriptBaselineCluster,
- body_band: _ScriptBodyBand,
-) -> bool:
- """要求 origin 与双 bbox 至少两项同向,并排除普通混合字体的弱中心偏移。"""
- origin_shift = cluster.baseline - body_band.baseline
- tight_center_shift = _cluster_tight_center(features, cluster) - _cluster_tight_center(features, body_cluster)
- loose_center_shift = _cluster_loose_center(features, cluster) - _cluster_loose_center(features, body_cluster)
- shifts = (origin_shift, tight_center_shift, loose_center_shift)
- expected_positive = origin_shift > 0
- same_direction_votes = sum(value > 0.05 if expected_positive else value < -0.05 for value in shifts)
- if same_direction_votes < 2:
- return False
-
- origin_ratio = abs(origin_shift) / max(body_band.tight_height, 1e-6)
- tight_center_ratio = abs(tight_center_shift) / max(body_band.tight_height, 1e-6)
- loose_center_ratio = abs(loose_center_shift) / max(body_band.loose_height, 1e-6)
- return origin_ratio >= SCRIPT_CONSENSUS_ORIGIN_SHIFT_RATIO or (
- tight_center_ratio >= SCRIPT_CONSENSUS_TIGHT_CENTER_SHIFT_RATIO
- and loose_center_ratio >= SCRIPT_CONSENSUS_LOOSE_CENTER_SHIFT_RATIO
- )
-
-
-def _choose_script_body_band(
- features: list[_ScriptCharFeature],
- clusters: list[_ScriptBaselineCluster],
-) -> tuple[_ScriptBodyBand, _ScriptBaselineCluster] | None:
- """在接近最高字形的基线簇中按字符数选择正文基线。"""
- if not clusters:
- return None
- maximum_height = max(_cluster_tight_height(features, cluster) for cluster in clusters)
- comparable = [
- cluster
- for cluster in clusters
- if _cluster_tight_height(features, cluster) >= maximum_height * SCRIPT_BODY_COMPARABLE_HEIGHT_RATIO
- ]
- body_cluster = max(
- comparable,
- key=lambda cluster: (
- len(cluster.member_indices),
- _cluster_tight_height(features, cluster),
- _cluster_loose_height(features, cluster),
- ),
- )
- body_band = _ScriptBodyBand(
- baseline=body_cluster.baseline,
- tight_height=_cluster_tight_height(features, body_cluster),
- loose_height=_cluster_loose_height(features, body_cluster),
- member_indices=frozenset(body_cluster.member_indices),
- )
- return body_band, body_cluster
-
-
-def _nearest_script_cluster(
- feature: _ScriptCharFeature,
- clusters: list[_ScriptBaselineCluster],
- tolerance: float,
-) -> _ScriptBaselineCluster | None:
- """把非字母数字字符附着到最近 origin 基线簇。"""
- if feature.origin is None or not clusters:
- return None
- nearest = min(clusters, key=lambda cluster: abs(feature.origin[1] - cluster.baseline))
- if abs(feature.origin[1] - nearest.baseline) > tolerance:
- return None
- return nearest
-
-
-def _script_horizontal_gap(first: BBox, second: BBox) -> float:
- """返回两个字符 tight bbox 的水平间隙。"""
- return max(0.0, first[0] - second[2], second[0] - first[2])
-
-
-def _drop_unseeded_script_punctuation(
- features: list[_ScriptCharFeature],
- component_indices: list[int],
- roles: list[_ScriptRole],
- body_height: float,
-) -> None:
- """移除未邻近同类字母数字种子的标点,避免跨 run 基线串联。"""
- seeded = [
- features[index]
- for index in component_indices
- if roles[index] != "body" and features[index].text.isalnum() and features[index].tight_bbox is not None
- ]
- for index in component_indices:
- feature = features[index]
- role = roles[index]
- if role == "body" or feature.text.isalnum() or feature.tight_bbox is None:
- continue
- nearby_seed = any(
- roles[seed.index] == role
- and _script_horizontal_gap(feature.tight_bbox, seed.tight_bbox)
- <= max(
- 2.0,
- body_height * SCRIPT_COMPONENT_SEED_GAP_RATIO,
- )
- and abs(feature.index - seed.index) <= SCRIPT_COMPONENT_SEED_MAX_POSITION_DISTANCE
- for seed in seeded
- )
- if not nearby_seed:
- roles[index] = "body"
-
-
-def _apply_script_consensus_candidates(
- features: list[_ScriptCharFeature],
- component_indices: list[int],
- body_band: _ScriptBodyBand,
- roles: list[_ScriptRole],
-) -> None:
- """用 origin/tight/loose 三证据一致性补充孤立边界字符。"""
- body_members = [
- features[index]
- for index in body_band.member_indices
- if features[index].tight_bbox is not None
- and features[index].tight_center_y is not None
- and features[index].origin is not None
- ]
- for index in component_indices:
- feature = features[index]
- if (
- roles[index] != "body"
- or index in body_band.member_indices
- or not feature.is_valid
- or feature.tight_bbox is None
- or feature.tight_center_y is None
- or feature.origin is None
- or not body_members
- ):
- continue
- reference = min(
- body_members,
- key=lambda member: (
- _script_horizontal_gap(feature.tight_bbox, member.tight_bbox),
- abs(feature.index - member.index),
- ),
- )
- gap = _script_horizontal_gap(feature.tight_bbox, reference.tight_bbox)
- if gap > max(2.5, reference.tight_height * 1.2):
- continue
- tight_ratio = feature.tight_height / max(reference.tight_height, 1e-6)
- if tight_ratio > SCRIPT_CONSENSUS_TIGHT_HEIGHT_RATIO:
- continue
-
- shifts = (
- feature.origin[1] - reference.origin[1],
- feature.tight_center_y - reference.tight_center_y,
- feature.loose_center_y - reference.loose_center_y,
- )
- positive_votes = sum(value > 0.05 for value in shifts)
- negative_votes = sum(value < -0.05 for value in shifts)
- if max(positive_votes, negative_votes) < 2:
- continue
- role = "sub" if positive_votes > negative_votes else "sup"
- if _get_script_role(shifts[0]) != role:
- continue
- origin_ratio = abs(shifts[0]) / max(reference.tight_height, 1e-6)
- tight_center_ratio = abs(shifts[1]) / max(reference.tight_height, 1e-6)
- loose_center_ratio = abs(shifts[2]) / max(reference.loose_height, 1e-6)
- if not feature.text.isalnum():
- expected_positive = role == "sub"
- if not all(value > 0.05 if expected_positive else value < -0.05 for value in shifts) or not (
- origin_ratio >= SCRIPT_STRONG_SHIFT_RATIO
- and tight_center_ratio >= SCRIPT_CONSENSUS_TIGHT_CENTER_SHIFT_RATIO
- and loose_center_ratio >= SCRIPT_CONSENSUS_LOOSE_CENTER_SHIFT_RATIO
- ):
- continue
- if not (
- origin_ratio >= SCRIPT_CONSENSUS_ORIGIN_SHIFT_RATIO
- or (
- tight_center_ratio >= SCRIPT_CONSENSUS_TIGHT_CENTER_SHIFT_RATIO
- and loose_center_ratio >= SCRIPT_CONSENSUS_LOOSE_CENTER_SHIFT_RATIO
- )
- ):
- continue
- roles[index] = role
-
-
-def _expand_script_component_neighbors(
- features: list[_ScriptCharFeature],
- component_indices: list[int],
- body_band: _ScriptBodyBand,
- protected_body_indices: set[int],
- roles: list[_ScriptRole],
-) -> None:
- """把同侧连续字符并入已有角标 run,不依赖字符类别或文本内容。"""
- component_set = set(component_indices)
- changed = True
- while changed:
- changed = False
- for index in component_indices:
- feature = features[index]
- if (
- roles[index] != "body"
- or index in protected_body_indices
- or not feature.is_valid
- or feature.origin is None
- or feature.text.isspace()
- or feature.tight_height > body_band.tight_height * SCRIPT_COMPONENT_MAX_HEIGHT_RATIO
- ):
- continue
- neighbor_roles = {
- roles[neighbor]
- for neighbor in (index - 1, index + 1)
- if neighbor in component_set and roles[neighbor] != "body"
- }
- if len(neighbor_roles) != 1:
- continue
- role = next(iter(neighbor_roles))
- shift = feature.origin[1] - body_band.baseline
- if abs(shift) < body_band.tight_height * SCRIPT_COMPONENT_MIN_OFFSET_RATIO:
- continue
- if _get_script_role(shift) != role:
- continue
- roles[index] = role
- changed = True
-
-
-def _assign_script_components(
- features: list[_ScriptCharFeature],
- component_indices: list[int],
- protected_body_indices: set[int],
- roles: list[_ScriptRole],
-) -> None:
- """在单个视觉组件内按 origin 基线簇和双 bbox 一致性分配角色。"""
- clusters, tolerance = _cluster_script_baselines(features, component_indices)
- body_result = _choose_script_body_band(features, clusters)
- if body_result is None:
- return
- body_band, body_cluster = body_result
- if body_band.tight_height <= 0 or body_band.loose_height <= 0:
- return
-
- cluster_roles: dict[_ScriptBaselineCluster, _ScriptRole] = {body_cluster: "body"}
- for cluster in clusters:
- if cluster is body_cluster:
- continue
- shift = cluster.baseline - body_band.baseline
- tight_ratio = _cluster_tight_height(features, cluster) / body_band.tight_height
- loose_ratio = _cluster_loose_height(features, cluster) / body_band.loose_height
- minimum_shift = max(
- SCRIPT_ORIGIN_MIN_SHIFT_ABSOLUTE,
- body_band.tight_height * SCRIPT_ORIGIN_MIN_SHIFT_RATIO,
- )
- strong_shift = abs(shift) >= body_band.tight_height * SCRIPT_STRONG_SHIFT_RATIO
- if (
- abs(shift) < minimum_shift
- or (
- tight_ratio > SCRIPT_TIGHT_HEIGHT_RATIO and not (strong_shift and tight_ratio <= SCRIPT_STRONG_MAX_HEIGHT_RATIO)
- )
- or (
- loose_ratio > SCRIPT_LOOSE_HEIGHT_ANOMALY_RATIO
- and not _script_cluster_has_consistent_displacement(
- features,
- cluster,
- body_cluster,
- body_band,
- )
- )
- ):
- cluster_roles[cluster] = "body"
- continue
- cluster_roles[cluster] = _get_script_role(shift)
-
- for index in component_indices:
- feature = features[index]
- if (
- index in protected_body_indices
- or feature.origin is None
- or feature.text.isspace()
- or feature.text in CONTROL_LINE_BREAK_CHARS
- ):
- continue
- cluster = _nearest_script_cluster(feature, clusters, tolerance)
- if cluster is not None:
- roles[index] = cluster_roles.get(cluster, "body")
-
- _drop_unseeded_script_punctuation(
- features,
- component_indices,
- roles,
- body_band.tight_height,
- )
- _apply_script_consensus_candidates(
- features,
- component_indices,
- body_band,
- roles,
- )
- _expand_script_component_neighbors(
- features,
- component_indices,
- body_band,
- protected_body_indices,
- roles,
- )
- for index in protected_body_indices.intersection(component_indices):
- roles[index] = "body"
-
-
def _classify_char_script_roles(
chars: list[Char],
*,
@@ -1281,23 +744,13 @@ def _classify_char_script_roles(
origins: dict[int, tuple[float, float]],
protected_body_indices: set[int] | None = None,
) -> list[_ScriptRole]:
- """按视觉组件、origin 基线簇和双 bbox 一致性识别上下标。"""
- protected_body_indices = protected_body_indices or set()
- features = _build_script_features(
+ """调用共享几何分类器识别上下标,并保留旧私有入口。"""
+ return classify_char_script_roles(
chars,
- tight_bboxes,
- origins,
- protected_body_indices,
+ tight_bboxes=tight_bboxes,
+ origins=origins,
+ protected_body_indices=protected_body_indices,
)
- roles: list[_ScriptRole] = ["body"] * len(features)
- for component_indices in _split_script_visual_components(features):
- _assign_script_components(
- features,
- component_indices,
- protected_body_indices,
- roles,
- )
- return roles
def _append_script_wrapped_text(parts: list[str], role: str | None, text: str) -> None:
diff --git a/mineru/model/flash/pdf/formulas.py b/mineru/model/flash/pdf/formulas.py
index 6c03d908..9f64972b 100644
--- a/mineru/model/flash/pdf/formulas.py
+++ b/mineru/model/flash/pdf/formulas.py
@@ -44,9 +44,7 @@ from .line_layout import (
from .line_merging import _join_formula_visual_row
-_FORMULA_NUMBER_SUFFIX_RE = re.compile(
- r"^(?P<prefix>.*?)(?P<marker>[((﹙][^()()﹙﹚\r\n]+[))﹚])\s*$"
-)
+_FORMULA_NUMBER_SUFFIX_RE = re.compile(r"^(?P<prefix>.*?)(?P<marker>[((﹙][^()()﹙﹚\r\n]+[))﹚])\s*$")
_FORMULA_PAGE_MARGIN_RATIO = 0.05
@@ -84,11 +82,7 @@ def _build_vector_formula_blocks(
) -> tuple[list[dict[str, Any]], set[int]]:
"""从根层填充 Path 构建空内容公式,并唯一认领可提取的公式编号。"""
- available_lines = [
- line
- for line in source.lines
- if line.angle == 0 and line.source_index not in claimed_line_indices
- ]
+ available_lines = [line for line in source.lines if line.angle == 0 and line.source_index not in claimed_line_indices]
if len(available_lines) < 3 or not source.path_infos:
return [], set()
@@ -110,11 +104,7 @@ def _build_vector_formula_blocks(
lanes,
median_height,
)
- container_bboxes = [
- bbox
- for block in container_blocks
- if (bbox := _coerce_bbox(block.get("bbox"))) is not None
- ]
+ container_bboxes = [bbox for block in container_blocks if (bbox := _coerce_bbox(block.get("bbox"))) is not None]
candidates = [
_VectorFormulaCandidate(
lane_index=component.lane_index,
@@ -176,11 +166,7 @@ def _build_vector_path_components(
members_by_lane: dict[int, list[PDFPathInfo]] = {}
for path_info in path_infos:
- if (
- path_info.form_depth != 0
- or not path_info.fill_visible
- or path_info.stroke_visible
- ):
+ if path_info.form_depth != 0 or not path_info.fill_visible or path_info.stroke_visible:
continue
lane_index = _assign_vector_path_lane(path_info.bbox, lanes, median_height)
if lane_index is None:
@@ -317,10 +303,7 @@ def _is_vector_formula_core(
"""按复杂度、尺寸、正文碰撞和容器优先级校验公式主体组件。"""
path_count = len(component.path_infos)
- complex_count = sum(
- item.segment_count >= _VECTOR_FORMULA_COMPLEX_SEGMENTS
- for item in component.path_infos
- )
+ complex_count = sum(item.segment_count >= _VECTOR_FORMULA_COMPLEX_SEGMENTS for item in component.path_infos)
if (
path_count < _VECTOR_FORMULA_MIN_PATHS
or complex_count < _VECTOR_FORMULA_MIN_COMPLEX_PATHS
@@ -331,23 +314,13 @@ def _is_vector_formula_core(
bbox = component.bbox
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]
- if not (
- width >= 2.5 * median_height
- and 0.9 * median_height <= height <= 8.0 * median_height
- and width >= 1.4 * height
- ):
+ if not (width >= 2.5 * median_height and 0.9 * median_height <= height <= 8.0 * median_height and width >= 1.4 * height):
return False
if _is_formula_component_in_page_margin(bbox, page_size[1]):
return False
- if any(
- _bbox_overlap_in_smaller(bbox, container_bbox) >= 0.5
- for container_bbox in container_bboxes
- ):
+ if any(_bbox_overlap_in_smaller(bbox, container_bbox) >= 0.5 for container_bbox in container_bboxes):
return False
- return not any(
- _vector_formula_collides_with_text(bbox, line, line_bbox, median_height)
- for line, line_bbox in lane.lines
- )
+ return not any(_vector_formula_collides_with_text(bbox, line, line_bbox, median_height) for line, line_bbox in lane.lines)
def _is_formula_component_in_page_margin(bbox: BBox, page_height: float) -> bool:
@@ -374,10 +347,7 @@ def _vector_formula_collides_with_text(
line_bbox[0] - formula_bbox[2],
0.0,
)
- return (
- _bbox_axis_overlap_ratio(formula_bbox, line_bbox, axis="y") >= 0.5
- and horizontal_gap <= median_height
- )
+ return _bbox_axis_overlap_ratio(formula_bbox, line_bbox, axis="y") >= 0.5 and horizontal_gap <= median_height
def _attach_vector_formula_rules(
@@ -387,16 +357,11 @@ def _attach_vector_formula_rules(
) -> None:
"""把靠近公式主体且横向覆盖充分的孤立细横线唯一并入主体。"""
- used_sources = {
- source_index
- for candidate in candidates
- for source_index in candidate.path_source_indices
- }
+ used_sources = {source_index for candidate in candidates for source_index in candidate.path_source_indices}
for component in components:
component_sources = {item.source_index for item in component.path_infos}
if component_sources & used_sources or not all(
- item.bbox[3] - item.bbox[1] <= 0.2 * median_height
- for item in component.path_infos
+ item.bbox[3] - item.bbox[1] <= 0.2 * median_height for item in component.path_infos
):
continue
matches = [
@@ -426,11 +391,7 @@ def _attach_vector_formula_path_numbers(
) -> None:
"""把栏右缘的小型复杂 Path 组件作为公式编号并入唯一主体。"""
- used_sources = {
- source_index
- for candidate in candidates
- for source_index in candidate.path_source_indices
- }
+ used_sources = {source_index for candidate in candidates for source_index in candidate.path_source_indices}
for component in components:
component_sources = {item.source_index for item in component.path_infos}
if component_sources & used_sources or not _is_vector_formula_number_component(
@@ -466,13 +427,8 @@ def _is_vector_formula_number_component(
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]
return (
- _VECTOR_FORMULA_NUMBER_MIN_PATHS
- <= path_count
- <= _VECTOR_FORMULA_NUMBER_MAX_PATHS
- and all(
- item.segment_count >= _VECTOR_FORMULA_COMPLEX_SEGMENTS
- for item in component.path_infos
- )
+ _VECTOR_FORMULA_NUMBER_MIN_PATHS <= path_count <= _VECTOR_FORMULA_NUMBER_MAX_PATHS
+ and all(item.segment_count >= _VECTOR_FORMULA_COMPLEX_SEGMENTS for item in component.path_infos)
and 0.5 * median_height <= width <= 2.0 * median_height
and 0.6 * median_height <= height <= 1.4 * median_height
and abs(lane.right - bbox[2]) <= 1.5 * median_height
@@ -492,16 +448,11 @@ def _vector_formula_number_matches(
if candidate.has_number or candidate.lane_index != lane_index:
continue
vertical_overlap = _bbox_axis_overlap_ratio(candidate.bbox, number_bbox, axis="y")
- if (
- number_bbox[0] < candidate.bbox[2]
- or vertical_overlap < 0.6
- ):
+ if number_bbox[0] < candidate.bbox[2] or vertical_overlap < 0.6:
continue
center_distance = abs(_bbox_center_y(candidate.bbox) - _bbox_center_y(number_bbox))
horizontal_gap = max(0.0, number_bbox[0] - candidate.bbox[2])
- matches.append(
- (-vertical_overlap, center_distance, horizontal_gap / max(0.1, median_height), candidate_index)
- )
+ matches.append((-vertical_overlap, center_distance, horizontal_gap / max(0.1, median_height), candidate_index))
return matches
@@ -567,8 +518,7 @@ def _build_formula_like_blocks(
angle_geometry = [
(line, _rotate_bbox_to_upright(line.bbox, page_size, angle))
for line in lines
- if line.angle == angle
- and line.source_index not in claimed_source_indices
+ if line.angle == angle and line.source_index not in claimed_source_indices
]
if len(angle_geometry) < 2:
continue
@@ -607,9 +557,9 @@ def _build_formula_like_blocks(
dominant_body_font,
)
) and not _is_formula_component_in_page_margin(
- bbox,
- local_page_height,
- ):
+ bbox,
+ local_page_height,
+ ):
content = _sanitize_pdf_control_text(
line.text,
preserve_newlines=False,
@@ -625,11 +575,7 @@ def _build_formula_like_blocks(
}
)
claimed_source_indices.add(line.source_index)
- lane.lines = [
- item
- for item in lane.lines
- if item[0].source_index not in claimed_source_indices
- ]
+ lane.lines = [item for item in lane.lines if item[0].source_index not in claimed_source_indices]
if len(lane.lines) < 2:
continue
anchors = _find_formula_spatial_anchors(
@@ -670,15 +616,17 @@ def _build_formula_like_blocks(
)
if len(members) < 2:
continue
- if len(members) == 2 and _bbox_axis_overlap_ratio(
- members[0][1],
- members[1][1],
- axis="y",
- ) < 0.2:
+ if (
+ len(members) == 2
+ and _bbox_axis_overlap_ratio(
+ members[0][1],
+ members[1][1],
+ axis="y",
+ )
+ < 0.2
+ ):
continue
- component_bbox = _bbox_union_many(
- [member_bbox for _member_line, member_bbox in members]
- )
+ component_bbox = _bbox_union_many([member_bbox for _member_line, member_bbox in members])
if _is_formula_component_in_page_margin(
component_bbox,
local_page_height,
@@ -695,7 +643,9 @@ def _build_formula_like_blocks(
blocks.append(block)
claimed_source_indices.update(line.source_index for line, _bbox in members)
- remaining_lines = [line for line in lines if line.source_index not in claimed_source_indices]
+ remaining_lines = [
+ line for line in lines if line.source_index not in claimed_source_indices and not line.formula_candidate_only
+ ]
return blocks, remaining_lines
@@ -717,19 +667,11 @@ def _build_split_visual_row_formula_blocks(
for (angle, _row_id), members in row_groups.items():
if len(members) < 3:
continue
- markers = [
- member
- for member in members
- if _standalone_formula_number_marker(member.text) is not None
- ]
+ markers = [member for member in members if _standalone_formula_number_marker(member.text) is not None]
if len(markers) != 1:
continue
marker = markers[0]
- if any(
- _bbox_intersects(member.bbox, table_bbox)
- for member in members
- for table_bbox in table_bboxes
- ):
+ if any(_bbox_intersects(member.bbox, table_bbox) for member in members for table_bbox in table_bboxes):
continue
local_members = [
(
@@ -742,52 +684,21 @@ def _build_split_visual_row_formula_blocks(
)
for member in members
]
- marker_bbox = next(
- bbox
- for member, bbox in local_members
- if member is marker
- )
- body_members = [
- (member, bbox)
- for member, bbox in local_members
- if member is not marker
- ]
- if not body_members or marker_bbox[0] <= max(
- _bbox_center_x(bbox)
- for _member, bbox in body_members
- ):
+ marker_bbox = next(bbox for member, bbox in local_members if member is marker)
+ body_members = [(member, bbox) for member, bbox in local_members if member is not marker]
+ if not body_members or marker_bbox[0] <= max(_bbox_center_x(bbox) for _member, bbox in body_members):
continue
- median_height = statistics.median(
- _line_effective_height(member, bbox)
- for member, bbox in local_members
- )
- row_center = statistics.median(
- _bbox_center_y(bbox)
- for _member, bbox in local_members
- )
- if any(
- abs(_bbox_center_y(bbox) - row_center) > 0.75 * median_height
- for _member, bbox in local_members
- ):
+ median_height = statistics.median(_line_effective_height(member, bbox) for member, bbox in local_members)
+ row_center = statistics.median(_bbox_center_y(bbox) for _member, bbox in local_members)
+ if any(abs(_bbox_center_y(bbox) - row_center) > 0.75 * median_height for _member, bbox in local_members):
continue
- body_fonts = {
- member.font_signature
- for member, _bbox in body_members
- if member.font_signature is not None
- }
- has_math_typography = (
- len(body_fonts) >= 2
- or any(
- member.compact_formula_cluster
- or member.font_coverage < 0.8
- for member, _bbox in body_members
- )
+ body_fonts = {member.font_signature for member, _bbox in body_members if member.font_signature is not None}
+ has_math_typography = len(body_fonts) >= 2 or any(
+ member.compact_formula_cluster or member.font_coverage < 0.8 for member, _bbox in body_members
)
if not has_math_typography:
continue
- body_bbox = _bbox_union_many(
- [bbox for _member, bbox in body_members]
- )
+ body_bbox = _bbox_union_many([bbox for _member, bbox in body_members])
body_width = max(0.1, body_bbox[2] - body_bbox[0])
# 同行成员可能只是分式尾部;窄尾部不能压低外部公式片段的宽度容差,
# 否则会提前认领分母、右括号和编号,使左侧公式主体落回普通文本。
@@ -807,16 +718,14 @@ def _build_split_visual_row_formula_blocks(
)
vertical_gap = max(
0.0,
- max(other_bbox[1], body_bbox[1])
- - min(other_bbox[3], body_bbox[3]),
+ max(other_bbox[1], body_bbox[1]) - min(other_bbox[3], body_bbox[3]),
)
if (
vertical_gap <= 0.75 * median_height
and other_bbox[2] - other_bbox[0] <= nearby_fragment_width_limit
and max(
0.0,
- max(other_bbox[0], body_bbox[0])
- - min(other_bbox[2], body_bbox[2]),
+ max(other_bbox[0], body_bbox[0]) - min(other_bbox[2], body_bbox[2]),
)
<= median_height
):
@@ -832,14 +741,8 @@ def _build_split_visual_row_formula_blocks(
)
if block is None:
continue
- local_bbox = _bbox_union_many(
- [bbox for _member, bbox in local_members]
- )
- local_page_height = (
- page_size[0]
- if angle in {90, 270}
- else page_size[1]
- )
+ local_bbox = _bbox_union_many([bbox for _member, bbox in local_members])
+ local_page_height = page_size[0] if angle in {90, 270} else page_size[1]
if _is_formula_component_in_page_margin(
local_bbox,
local_page_height,
@@ -865,16 +768,11 @@ def _is_isolated_compact_formula_cluster(
return False
if bbox[3] - bbox[1] > 3.0 * median_height:
return False
- center_delta_ratio = abs(
- _bbox_center_x(bbox) - 0.5 * (lane.left + lane.right)
- ) / lane_width
+ center_delta_ratio = abs(_bbox_center_x(bbox) - 0.5 * (lane.left + lane.right)) / lane_width
left_indent_ratio = (bbox[0] - lane.left) / lane_width
right_blank_ratio = (lane.right - bbox[2]) / lane_width
# 部分期刊把独立公式按固定左缩进排版;同时要求右侧大留白,排除贴栏正文。
- deliberately_left_indented = (
- 0.03 <= left_indent_ratio <= 0.25
- and right_blank_ratio >= 0.35
- )
+ deliberately_left_indented = 0.03 <= left_indent_ratio <= 0.25 and right_blank_ratio >= 0.35
if center_delta_ratio > 0.2 and not deliberately_left_indented:
return False
@@ -884,28 +782,17 @@ def _is_isolated_compact_formula_cluster(
for item in lane.lines
if item[0].source_index != line.source_index
and item[1][2] - item[1][0] >= 0.45 * lane_width
- and 0.8 * median_height
- <= _line_effective_height(*item)
- <= 1.25 * median_height
- ]
- rows_above = [
- item
- for item in body_rows
- if _bbox_center_y(item[1]) < candidate_center
- ]
- rows_below = [
- item
- for item in body_rows
- if _bbox_center_y(item[1]) > candidate_center
+ and 0.8 * median_height <= _line_effective_height(*item) <= 1.25 * median_height
]
+ rows_above = [item for item in body_rows if _bbox_center_y(item[1]) < candidate_center]
+ rows_below = [item for item in body_rows if _bbox_center_y(item[1]) > candidate_center]
if not rows_above or not rows_below:
return False
previous = max(rows_above, key=lambda item: _bbox_center_y(item[1]))
following = min(rows_below, key=lambda item: _bbox_center_y(item[1]))
return (
candidate_center - _bbox_center_y(previous[1]) <= 8.0 * median_height
- and _bbox_center_y(following[1]) - candidate_center
- <= 8.0 * median_height
+ and _bbox_center_y(following[1]) - candidate_center <= 8.0 * median_height
)
@@ -921,8 +808,7 @@ def _compact_cluster_has_nearby_number_anchor(
other_line.source_index != line.source_index
and _standalone_formula_number_marker(other_line.text) is not None
and other_bbox[0] > _bbox_center_x(bbox)
- and abs(_bbox_center_y(other_bbox) - _bbox_center_y(bbox))
- <= 2.5 * median_height
+ and abs(_bbox_center_y(other_bbox) - _bbox_center_y(bbox)) <= 2.5 * median_height
for other_line, other_bbox in lane.lines
)
@@ -948,10 +834,7 @@ def _is_isolated_unnumbered_formula_line(
line_width = bbox[2] - bbox[0]
if not 0.15 * lane_width <= line_width <= 0.8 * lane_width:
return False
- if (
- abs(_bbox_center_x(bbox) - 0.5 * (lane.left + lane.right))
- > 0.08 * lane_width
- ):
+ if abs(_bbox_center_x(bbox) - 0.5 * (lane.left + lane.right)) > 0.08 * lane_width:
return False
if bbox[3] - bbox[1] > 1.8 * median_height:
return False
@@ -961,8 +844,7 @@ def _is_isolated_unnumbered_formula_line(
if any(
other_line.source_index != line.source_index
and _standalone_formula_number_marker(other_line.text) is not None
- and abs(_bbox_center_y(other_bbox) - candidate_center)
- <= 4.0 * median_height
+ and abs(_bbox_center_y(other_bbox) - candidate_center) <= 4.0 * median_height
for other_line, other_bbox in lane.lines
) or _has_nearby_punctuated_formula_number_anchor(
candidate,
@@ -977,28 +859,17 @@ def _is_isolated_unnumbered_formula_line(
and item[0].font_signature == dominant_body_font
and item[0].font_coverage >= 0.75
and item[1][2] - item[1][0] >= 0.45 * lane_width
- and 0.8 * median_height
- <= _line_effective_height(*item)
- <= 1.25 * median_height
- ]
- rows_above = [
- item
- for item in body_rows
- if _bbox_center_y(item[1]) < candidate_center
- ]
- rows_below = [
- item
- for item in body_rows
- if _bbox_center_y(item[1]) > candidate_center
+ and 0.8 * median_height <= _line_effective_height(*item) <= 1.25 * median_height
]
+ rows_above = [item for item in body_rows if _bbox_center_y(item[1]) < candidate_center]
+ rows_below = [item for item in body_rows if _bbox_center_y(item[1]) > candidate_center]
if not rows_above or not rows_below:
return False
previous = max(rows_above, key=lambda item: _bbox_center_y(item[1]))
following = min(rows_below, key=lambda item: _bbox_center_y(item[1]))
return (
candidate_center - _bbox_center_y(previous[1]) <= 4.0 * median_height
- and _bbox_center_y(following[1]) - candidate_center
- <= 4.0 * median_height
+ and _bbox_center_y(following[1]) - candidate_center <= 4.0 * median_height
)
@@ -1014,16 +885,10 @@ def _is_hanging_indent_tail_line(
return False
candidate_center = _bbox_center_y(bbox)
rows_above = [
- item
- for item in lane.lines
- if item[0].source_index != line.source_index
- and _bbox_center_y(item[1]) < candidate_center
+ item for item in lane.lines if item[0].source_index != line.source_index and _bbox_center_y(item[1]) < candidate_center
]
rows_below = [
- item
- for item in lane.lines
- if item[0].source_index != line.source_index
- and _bbox_center_y(item[1]) > candidate_center
+ item for item in lane.lines if item[0].source_index != line.source_index and _bbox_center_y(item[1]) > candidate_center
]
if not rows_above or not rows_below:
return False
@@ -1063,11 +928,7 @@ def _has_nearby_punctuated_formula_number_anchor(
continue
prefix, _marker = parts
compact_prefix = prefix.strip()
- if (
- not compact_prefix
- or len(compact_prefix) > 3
- or any(character.isalnum() for character in compact_prefix)
- ):
+ if not compact_prefix or len(compact_prefix) > 3 or any(character.isalnum() for character in compact_prefix):
continue
vertical_gap = max(
0.0,
@@ -1083,6 +944,61 @@ def _has_nearby_punctuated_formula_number_anchor(
return False
+def _find_repeated_formula_number_anchors(
+ lane: _TextLane,
+ median_height: float,
+ body_interval: tuple[float, float] | None,
+) -> list[_FormulaAnchor]:
+ """用栏右缘重复编号恢复正文区间之外的行间公式锚点。"""
+ lane_width = max(0.1, lane.right - lane.left)
+ markers = [
+ (line, bbox)
+ for line, bbox in lane.lines
+ if (parts := _split_trailing_formula_number(line.text)) is not None
+ and not parts[0]
+ and abs(lane.right - bbox[2]) <= max(3.0, 0.02 * lane_width)
+ ]
+ output: list[_FormulaAnchor] = []
+ for line, bbox in markers:
+ if not any(
+ other_line.source_index != line.source_index
+ and abs(_bbox_center_y(other_bbox) - _bbox_center_y(bbox)) <= 6.0 * median_height
+ for other_line, other_bbox in markers
+ ):
+ continue
+ line_height = _line_effective_height(line, bbox)
+ left_peers = [
+ (other_line, other_bbox)
+ for other_line, other_bbox in lane.lines
+ if other_line.source_index != line.source_index
+ and _bbox_center_x(other_bbox) < bbox[0]
+ and _formula_detached_seed_vertical_match(
+ bbox,
+ line_height,
+ other_bbox,
+ _line_effective_height(other_line, other_bbox),
+ )
+ ]
+ if len(left_peers) < 2 or not any(
+ peer.formula_candidate_only or peer.compact_formula_cluster or peer.font_coverage < 0.75
+ for peer, _peer_bbox in left_peers
+ ):
+ continue
+ center_y = _bbox_center_y(bbox)
+ detached_above = body_interval is None or center_y < body_interval[0]
+ detached_below = body_interval is not None and center_y > body_interval[1]
+ output.append(
+ _FormulaAnchor(
+ line=line,
+ bbox=bbox,
+ detached_below_body=detached_below,
+ detached_above_body=detached_above,
+ repeated_number_band=True,
+ )
+ )
+ return output
+
+
def _find_formula_spatial_anchors(
lane: _TextLane,
median_height: float,
@@ -1092,11 +1008,19 @@ def _find_formula_spatial_anchors(
lane_width = max(0.1, lane.right - lane.left)
body_interval = _formula_lane_body_interval(lane, median_height)
+ repeated_anchors = _find_repeated_formula_number_anchors(
+ lane,
+ median_height,
+ body_interval,
+ )
if body_interval is None:
- return []
+ return _deduplicate_formula_anchors(repeated_anchors, median_height)
body_top, body_bottom = body_interval
- anchors: list[_FormulaAnchor] = []
+ anchors: list[_FormulaAnchor] = list(repeated_anchors)
+ repeated_sources = {anchor.line.source_index for anchor in repeated_anchors}
for line, bbox in lane.lines:
+ if line.source_index in repeated_sources:
+ continue
line_height = _line_effective_height(line, bbox)
line_width = bbox[2] - bbox[0]
is_short_right_anchor = line_width <= max(4.0 * line_height, 0.12 * lane_width)
@@ -1105,10 +1029,7 @@ def _find_formula_spatial_anchors(
has_formula_number_suffix
and line_width <= 0.75 * lane_width
and dominant_body_font is not None
- and (
- line.font_signature != dominant_body_font
- or line.font_coverage < 0.75
- )
+ and (line.font_signature != dominant_body_font or line.font_coverage < 0.75)
)
if not is_short_right_anchor and not is_wide_numbered_anchor:
continue
@@ -1121,10 +1042,7 @@ def _find_formula_spatial_anchors(
]
if len(same_row_fragments) >= 3 and not any(
other_line.font_coverage < 0.75
- or (
- dominant_body_font is not None
- and other_line.font_signature != dominant_body_font
- )
+ or (dominant_body_font is not None and other_line.font_signature != dominant_body_font)
for other_line in same_row_fragments
if other_line.source_index != line.source_index
):
@@ -1142,11 +1060,7 @@ def _find_formula_spatial_anchors(
center_y = _bbox_center_y(bbox)
detached_below_body = body_bottom < center_y <= body_bottom + 6.0 * median_height
detached_above_body = body_top - 6.0 * median_height <= center_y < body_top
- if (
- not body_top <= center_y <= body_bottom
- and not detached_below_body
- and not detached_above_body
- ):
+ if not body_top <= center_y <= body_bottom and not detached_below_body and not detached_above_body:
continue
left_peers = [
(other_line, other_bbox)
@@ -1172,16 +1086,10 @@ def _find_formula_spatial_anchors(
]
if is_short_right_anchor and not has_formula_number_suffix:
# 非编号短锚点必须与左侧主体真正分离;分母字符与正文横向重叠时不能扩张成公式。
- if any(
- _bbox_axis_overlap_ratio(bbox, other_bbox, axis="x") >= 0.5
- for _other_line, other_bbox in left_peers
- ):
+ if any(_bbox_axis_overlap_ratio(bbox, other_bbox, axis="x") >= 0.5 for _other_line, other_bbox in left_peers):
continue
minimum_gap = max(0.5, 0.1 * line_height)
- if not any(
- bbox[0] - other_bbox[2] >= minimum_gap
- for _other_line, other_bbox in left_peers
- ):
+ if not any(bbox[0] - other_bbox[2] >= minimum_gap for _other_line, other_bbox in left_peers):
continue
if left_peers:
anchors.append(
@@ -1205,38 +1113,25 @@ def _split_visual_row_has_prose_continuation(
if len(same_row_fragments) < 3 or anchor_line.visual_row_id is None:
return False
- fragment_sources = {
- line.source_index
- for line in same_row_fragments
- }
- fragment_geometry = [
- (line, bbox)
- for line, bbox in lane.lines
- if line.source_index in fragment_sources
- ]
+ fragment_sources = {line.source_index for line in same_row_fragments}
+ fragment_geometry = [(line, bbox) for line, bbox in lane.lines if line.source_index in fragment_sources]
if len(fragment_geometry) < 3:
return False
lane_width = max(0.1, lane.right - lane.left)
row_bbox = _bbox_union_many([bbox for _line, bbox in fragment_geometry])
if row_bbox[2] - row_bbox[0] < 0.75 * lane_width:
return False
- row_center = statistics.median(
- _bbox_center_y(bbox)
- for _line, bbox in fragment_geometry
- )
+ row_center = statistics.median(_bbox_center_y(bbox) for _line, bbox in fragment_geometry)
if any(
abs(_bbox_center_y(bbox) - row_center) > 0.25 * median_height
- or not 0.7 * median_height
- <= _line_effective_height(line, bbox)
- <= 1.3 * median_height
+ or not 0.7 * median_height <= _line_effective_height(line, bbox) <= 1.3 * median_height
for line, bbox in fragment_geometry
):
return False
following_rows = [
(line, bbox)
for line, bbox in lane.lines
- if line.source_index not in fragment_sources
- and _bbox_center_y(bbox) > row_center + 0.5 * median_height
+ if line.source_index not in fragment_sources and _bbox_center_y(bbox) > row_center + 0.5 * median_height
]
if not following_rows:
return False
@@ -1286,12 +1181,7 @@ def _formula_lane_body_interval(
lane_width = max(0.1, lane.right - lane.left)
body_lines = sorted(
- (
- item
- for item in lane.lines
- if item[1][2] - item[1][0]
- >= max(4.0 * _line_effective_height(*item), 0.35 * lane_width)
- ),
+ (item for item in lane.lines if item[1][2] - item[1][0] >= max(4.0 * _line_effective_height(*item), 0.35 * lane_width)),
key=lambda item: (item[1][1], item[1][0]),
)
if len(body_lines) < 3:
@@ -1299,10 +1189,7 @@ def _formula_lane_body_interval(
dense_lines: list[tuple[_LineItem, BBox]] = []
for index, item in enumerate(body_lines):
has_close_previous = index > 0 and item[1][1] - body_lines[index - 1][1][3] <= 1.5 * median_height
- has_close_next = (
- index + 1 < len(body_lines)
- and body_lines[index + 1][1][1] - item[1][3] <= 1.5 * median_height
- )
+ has_close_next = index + 1 < len(body_lines) and body_lines[index + 1][1][1] - item[1][3] <= 1.5 * median_height
if has_close_previous or has_close_next:
dense_lines.append(item)
if len(dense_lines) < 3:
@@ -1371,6 +1258,7 @@ def _grow_formula_spatial_component(
anchor_geometry,
dominant_body_font,
median_height,
+ minimum_font_coverage=0.5 if anchor.repeated_number_band else 0.75,
)
]
seeds = [
@@ -1473,6 +1361,8 @@ def _is_formula_body_prefix(
anchor: tuple[_LineItem, BBox],
dominant_body_font: tuple[str, int] | None,
median_height: float,
+ *,
+ minimum_font_coverage: float = 0.75,
) -> bool:
"""识别锚点上方左对齐的常规正文行,防止公式空间扩张越界认领。"""
@@ -1480,6 +1370,8 @@ def _is_formula_body_prefix(
return False
line, bbox = candidate
anchor_line, anchor_bbox = anchor
+ if line.formula_candidate_only:
+ return False
line_height = _line_effective_height(line, bbox)
anchor_height = _line_effective_height(anchor_line, anchor_bbox)
if _bbox_center_y(bbox) > _bbox_center_y(anchor_bbox) - 0.2 * max(line_height, anchor_height):
@@ -1488,7 +1380,7 @@ def _is_formula_body_prefix(
return False
return (
line.font_signature == dominant_body_font
- and line.font_coverage >= 0.75
+ and line.font_coverage >= minimum_font_coverage
and 0.8 * median_height <= line_height <= 1.25 * median_height
)
@@ -1552,11 +1444,7 @@ def _is_detached_formula_sidecar(
"""仅依据 bbox 判断右侧锚点是否为与公式主体分离的窄幅 sidecar。"""
anchor_line, anchor_bbox = anchor
- body_bboxes = [
- bbox
- for line, bbox in members
- if line.source_index != anchor_line.source_index
- ]
+ body_bboxes = [bbox for line, bbox in members if line.source_index != anchor_line.source_index]
if not body_bboxes:
return False
@@ -1599,11 +1487,7 @@ def _formula_members_to_block(
(line for line, _bbox in members if line.source_index == anchor_source_index),
None,
)
- anchor_formula_number_parts = (
- _split_trailing_formula_number(anchor_line.text)
- if anchor_line is not None
- else None
- )
+ anchor_formula_number_parts = _split_trailing_formula_number(anchor_line.text) if anchor_line is not None else None
heights = [_line_effective_height(line, bbox) for line, bbox in members]
median_height = statistics.median(heights) if heights else 1.0
row_tolerance = max(1.5, 0.35 * median_height)
@@ -1641,9 +1525,7 @@ def _formula_members_to_block(
]
trailing_sidecar_content = marker
elif _is_detached_formula_sidecar(anchor_member, members, median_height):
- rows[row_index] = [
- member for member in row if member[0].source_index != anchor_source_index
- ]
+ rows[row_index] = [member for member in row if member[0].source_index != anchor_source_index]
trailing_sidecar_content = anchor_member[0].text.strip()
break
diff --git a/mineru/model/flash/pdf/line_merging.py b/mineru/model/flash/pdf/line_merging.py
index 5447501e..a1b32c8b 100644
--- a/mineru/model/flash/pdf/line_merging.py
+++ b/mineru/model/flash/pdf/line_merging.py
@@ -206,6 +206,8 @@ def _overlapping_inline_cluster_pair_is_connected(
second_line, second_bbox = second
if first_line.angle != second_line.angle:
return False
+ if first_line.formula_candidate_only != second_line.formula_candidate_only:
+ return False
if first_line.semantic_type != second_line.semantic_type:
return False
if _connection_crosses_table(
@@ -316,6 +318,11 @@ def _merge_overlapping_inline_cluster(
key=lambda line: line.source_index,
)
host = _select_overlapping_inline_cluster_host(members, median_height)
+ detected_regions = (
+ [line.bbox for line in ordered_members]
+ if compact_formula_cluster
+ else [line.bbox for line in ordered_members if line is not host]
+ )
merged = _LineItem(
text=" ".join(text for line in ordered_members if (text := line.text.strip())),
bbox=_bbox_union_many([line.bbox for line in ordered_members]),
@@ -331,17 +338,21 @@ def _merge_overlapping_inline_cluster(
median_glyph_width=host.median_glyph_width,
leading_emphasis_width=ordered_members[0].leading_emphasis_width,
split_from_row=any(line.split_from_row for line in ordered_members),
- preserve_split_boundary=any(
- line.preserve_split_boundary for line in ordered_members
- ),
+ preserve_split_boundary=any(line.preserve_split_boundary for line in ordered_members),
semantic_type=host.semantic_type,
restored_inline_cluster=True,
compact_formula_cluster=compact_formula_cluster,
+ formula_candidate_only=all(line.formula_candidate_only for line in ordered_members),
+ inline_math_regions=[
+ *(region for line in ordered_members for region in line.inline_math_regions),
+ *detected_regions,
+ ],
)
if merged.chars:
_fill_native_typography(merged, page_size)
return merged
+
def _merge_post_semantic_text_runs(
lines: list[_LineItem],
page_size: tuple[float, float],
@@ -351,10 +362,7 @@ def _merge_post_semantic_text_runs(
if len(lines) < 2:
return list(lines)
- local_bboxes = [
- _rotate_bbox_to_upright(line.bbox, page_size, line.angle)
- for line in lines
- ]
+ local_bboxes = [_rotate_bbox_to_upright(line.bbox, page_size, line.angle) for line in lines]
parents = list(range(len(lines)))
def find(index: int) -> int:
@@ -382,6 +390,8 @@ def _merge_post_semantic_text_runs(
second_line = lines[second_index]
if second_line.semantic_type is not None or first_line.angle != second_line.angle:
continue
+ if first_line.formula_candidate_only != second_line.formula_candidate_only:
+ continue
if _connection_crosses_table(
first_line.bbox,
second_line.bbox,
@@ -441,10 +451,15 @@ def _post_semantic_same_baseline_geometry(
"""放宽上下标字号差异,仅合并水平紧贴且垂直充分交叠的普通 run。"""
pair_height = max(first_height, second_height)
- if min(first_height, second_height) <= 0 or pair_height / min(
- first_height,
- second_height,
- ) > 1.6:
+ if (
+ min(first_height, second_height) <= 0
+ or pair_height
+ / min(
+ first_height,
+ second_height,
+ )
+ > 1.6
+ ):
return False
y_overlap = max(
0.0,
@@ -472,11 +487,11 @@ def _can_merge_same_baseline_pair(
if first.angle != second.angle:
return False
+ if first.formula_candidate_only != second.formula_candidate_only:
+ return False
if first.semantic_type != second.semantic_type:
return False
- if first.visual_row_id == second.visual_row_id and (
- first.split_from_row or second.split_from_row
- ):
+ if first.visual_row_id == second.visual_row_id and (first.split_from_row or second.split_from_row):
return False
if _connection_crosses_table(first.bbox, second.bbox, table_bboxes):
return False
@@ -593,31 +608,23 @@ def _merge_same_baseline_group(
font_signature=members[0].font_signature,
font_coverage=min(member.font_coverage for member in members),
dominant_font_weight=statistics.median(
- member.dominant_font_weight
- for member in members
- if member.dominant_font_weight is not None
+ member.dominant_font_weight for member in members if member.dominant_font_weight is not None
)
if any(member.dominant_font_weight is not None for member in members)
else None,
median_glyph_width=statistics.median(
- member.median_glyph_width
- for member in members
- if member.median_glyph_width is not None
+ member.median_glyph_width for member in members if member.median_glyph_width is not None
)
if any(member.median_glyph_width is not None for member in members)
else None,
leading_emphasis_width=members[0].leading_emphasis_width,
split_from_row=any(member.split_from_row for member in members),
- preserve_split_boundary=any(
- member.preserve_split_boundary for member in members
- ),
+ preserve_split_boundary=any(member.preserve_split_boundary for member in members),
semantic_type=members[0].semantic_type,
- restored_inline_cluster=any(
- member.restored_inline_cluster for member in members
- ),
- compact_formula_cluster=any(
- member.compact_formula_cluster for member in members
- ),
+ restored_inline_cluster=any(member.restored_inline_cluster for member in members),
+ compact_formula_cluster=any(member.compact_formula_cluster for member in members),
+ formula_candidate_only=all(member.formula_candidate_only for member in members),
+ inline_math_regions=[region for member in members for region in member.inline_math_regions],
)
if merged.chars:
_fill_native_typography(merged, page_size)
@@ -667,11 +674,7 @@ def _restore_dense_split_visual_rows(
return list(lines)
lane_keys: dict[int, tuple[int, int]] = {}
for angle in sorted({line.angle for line in lines}):
- line_geometry = [
- (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))
- for line in lines
- if line.angle == angle
- ]
+ line_geometry = [(line, _rotate_bbox_to_upright(line.bbox, page_size, angle)) for line in lines if line.angle == angle]
if not line_geometry:
continue
median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in line_geometry)
@@ -744,8 +747,7 @@ def _merge_title_resolved_visual_rows(
page_size,
)
if semantic_type != "paragraph_title" and not (
- semantic_type is None
- and (len(font_signatures) > 1 or dense_same_font_text)
+ semantic_type is None and (len(font_signatures) > 1 or dense_same_font_text)
):
continue
local_geometry = [
@@ -774,9 +776,7 @@ def _merge_title_resolved_visual_rows(
merged_rows.append(_merge_dense_split_visual_row(members, page_size))
consumed_source_indices.update(member.source_index for member in members)
- output = [
- line for line in lines if line.source_index not in consumed_source_indices
- ]
+ output = [line for line in lines if line.source_index not in consumed_source_indices]
output.extend(merged_rows)
output.sort(
key=lambda line: (
@@ -817,9 +817,7 @@ def _is_dense_same_font_two_run_row(
)
for member in ordered
]
- local_geometry.sort(
- key=lambda item: (item[1][0], item[1][1], item[0].source_index)
- )
+ local_geometry.sort(key=lambda item: (item[1][0], item[1][1], item[0].source_index))
first, second = local_geometry
pair_height = max(
_line_effective_height(*first),
@@ -835,9 +833,7 @@ def _is_dense_same_font_two_run_row(
return False
union_bbox = _bbox_union_many([bbox for _member, bbox in local_geometry])
- occupied_width = sum(
- bbox[2] - bbox[0] for _member, bbox in local_geometry
- )
+ occupied_width = sum(bbox[2] - bbox[0] for _member, bbox in local_geometry)
return occupied_width / max(0.1, union_bbox[2] - union_bbox[0]) >= 0.85
@@ -857,6 +853,8 @@ def _can_restore_dense_split_visual_row(
return False
if len({member.semantic_type for member in members}) != 1:
return False
+ if len({member.formula_candidate_only for member in members}) != 1:
+ return False
ordered = sorted(members, key=lambda member: member.run_index)
if [member.run_index for member in ordered] != list(range(len(ordered))):
return False
@@ -865,11 +863,7 @@ def _can_restore_dense_split_visual_row(
font_signatures = {member.font_signature for member in ordered}
if len(font_signatures) != 1:
return False
- if any(
- _bbox_intersects(member.bbox, table_bbox)
- for member in ordered
- for table_bbox in table_bboxes
- ):
+ if any(_bbox_intersects(member.bbox, table_bbox) for member in ordered for table_bbox in table_bboxes):
return False
local_geometry = [
@@ -881,10 +875,7 @@ def _can_restore_dense_split_visual_row(
]
local_geometry.sort(key=lambda item: (item[1][0], item[1][1], item[0].source_index))
if not same_inferred_lane:
- member_widths = [
- bbox[2] - bbox[0]
- for _member, bbox in local_geometry
- ]
+ member_widths = [bbox[2] - bbox[0] for _member, bbox in local_geometry]
if len(members) == 2 and min(member_widths) > 0.35 * max(member_widths):
return False
if 3 <= len(members) <= 6:
@@ -892,9 +883,7 @@ def _can_restore_dense_split_visual_row(
heights = [_line_effective_height(member, bbox) for member, bbox in local_geometry]
median_height = statistics.median(heights)
glyph_widths = [
- width
- for member, _bbox in local_geometry
- if (width := _median_native_glyph_width(member, page_size)) is not None
+ width for member, _bbox in local_geometry if (width := _median_native_glyph_width(member, page_size)) is not None
]
median_glyph_width = statistics.median(glyph_widths) if glyph_widths else 0.0
gap_limit = (
@@ -923,10 +912,7 @@ def _can_restore_dense_split_visual_row(
if not same_inferred_lane
else 0.65
)
- return (
- occupied_width / max(0.1, union_bbox[2] - union_bbox[0])
- >= minimum_occupancy
- )
+ return occupied_width / max(0.1, union_bbox[2] - union_bbox[0]) >= minimum_occupancy
def _merge_dense_split_visual_row(
@@ -959,38 +945,27 @@ def _merge_dense_split_visual_row(
chars=[char for member in ordered_members for char in member.chars],
visual_row_id=ordered_members[0].visual_row_id,
run_index=0,
- effective_height=statistics.median(
- _line_effective_height(member, bbox)
- for member, bbox in ordered_geometry
- ),
+ effective_height=statistics.median(_line_effective_height(member, bbox) for member, bbox in ordered_geometry),
font_signature=ordered_members[0].font_signature,
font_coverage=min(member.font_coverage for member in ordered_members),
dominant_font_weight=statistics.median(
- member.dominant_font_weight
- for member in ordered_members
- if member.dominant_font_weight is not None
+ member.dominant_font_weight for member in ordered_members if member.dominant_font_weight is not None
)
if any(member.dominant_font_weight is not None for member in ordered_members)
else None,
median_glyph_width=statistics.median(
- member.median_glyph_width
- for member in ordered_members
- if member.median_glyph_width is not None
+ member.median_glyph_width for member in ordered_members if member.median_glyph_width is not None
)
if any(member.median_glyph_width is not None for member in ordered_members)
else None,
leading_emphasis_width=ordered_members[0].leading_emphasis_width,
split_from_row=False,
- preserve_split_boundary=any(
- member.preserve_split_boundary for member in ordered_members
- ),
+ preserve_split_boundary=any(member.preserve_split_boundary for member in ordered_members),
semantic_type=ordered_members[0].semantic_type,
- restored_inline_cluster=any(
- member.restored_inline_cluster for member in ordered_members
- ),
- compact_formula_cluster=any(
- member.compact_formula_cluster for member in ordered_members
- ),
+ restored_inline_cluster=any(member.restored_inline_cluster for member in ordered_members),
+ compact_formula_cluster=any(member.compact_formula_cluster for member in ordered_members),
+ formula_candidate_only=all(member.formula_candidate_only for member in ordered_members),
+ inline_math_regions=[region for member in ordered_members for region in member.inline_math_regions],
)
if merged.chars:
_fill_native_typography(merged, page_size)
diff --git a/mineru/model/flash/pdf/models.py b/mineru/model/flash/pdf/models.py
index 28c51f71..b148e4cd 100644
--- a/mineru/model/flash/pdf/models.py
+++ b/mineru/model/flash/pdf/models.py
@@ -5,13 +5,16 @@
from __future__ import annotations
from dataclasses import dataclass, field
-from typing import Any, Literal
+from typing import TYPE_CHECKING, Any, Literal
from pdftext.schema import Char
from ....types import BBox
from .document import PDFPathInfo
+if TYPE_CHECKING:
+ from .text_styles import PDFTextScriptLine
+
@dataclass(slots=True)
class _LineItem:
@@ -35,6 +38,8 @@ class _LineItem:
semantic_type: str | None = None
restored_inline_cluster: bool = False
compact_formula_cluster: bool = False
+ formula_candidate_only: bool = False
+ inline_math_regions: list[BBox] = field(default_factory=list)
@dataclass(slots=True)
@@ -137,6 +142,7 @@ class _FormulaAnchor:
bbox: BBox
detached_below_body: bool = False
detached_above_body: bool = False
+ repeated_number_band: bool = False
@dataclass(slots=True)
@@ -163,6 +169,8 @@ class _PreparedPage:
drawing_lines: list[_AxisLine]
fixed_blocks: list[dict[str, Any]]
page_footnote_groups: list[set[int]] = field(default_factory=list)
+ script_lines: list[PDFTextScriptLine] = field(default_factory=list)
+ formula_candidate_lines: list[_LineItem] = field(default_factory=list)
@dataclass(slots=True)
diff --git a/mineru/model/flash/pdf/native_text.py b/mineru/model/flash/pdf/native_text.py
index 004629e4..1efb0621 100644
--- a/mineru/model/flash/pdf/native_text.py
+++ b/mineru/model/flash/pdf/native_text.py
@@ -30,14 +30,9 @@ from .geometry import (
_PDF_CONTROL_CHAR_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]")
-_PDF_LINE_END_SOFT_HYPHEN_RE = re.compile(
- r"(?<=[A-Za-z])[\x02\u00ad](?=[\t ]*(?:\n|$))"
-)
+_PDF_LINE_END_SOFT_HYPHEN_RE = re.compile(r"(?<=[A-Za-z])[\x02\u00ad](?=[\t ]*(?:\n|$))")
# Unicode Zs 空格在 model_list 中只承担分词作用,统一成可互操作的 ASCII 空格。
-_PDF_SEPARATOR_SPACE_CHARS = (
- "\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006"
- "\u2007\u2008\u2009\u200a\u202f\u205f\u3000"
-)
+_PDF_SEPARATOR_SPACE_CHARS = "\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000"
_PDF_UNICODE_TEXT_TRANSLATION = str.maketrans(
{
**dict.fromkeys(_PDF_SEPARATOR_SPACE_CHARS, " "),
@@ -55,6 +50,7 @@ _SUPPORTED_PDFTEXT_LINE_ANGLES = (0.0, 90.0, 270.0)
_PDFTEXT_SHEARED_HORIZONTAL_MAX_ANGLE_DEGREES = 30.0
_PDFTEXT_HORIZONTAL_BASELINE_MAX_ANGLE_DEGREES = 2.0
_PDFTEXT_HORIZONTAL_BASELINE_MAX_DISPERSION_RATIO = 0.75
+_PDFTEXT_FORMULA_OPERATOR_CHARS = frozenset("=∑∫√±×÷")
def _build_native_line_items(
@@ -66,21 +62,27 @@ def _build_native_line_items(
) -> list[_LineItem]:
"""按指定视觉方向将 pdftext 粗行精修成字符间隙分隔的视觉 run。"""
- items: list[_LineItem] = []
- supported_lines = [
- (child_line, visual_angle)
- for pdf_line in pdf_lines
- for child_line in _split_pdftext_line_by_rotation(pdf_line)
- if (
- visual_angle := _resolve_pdftext_line_angle(
+ normal_items: list[_LineItem] = []
+ formula_items: list[_LineItem] = []
+ supported_lines: list[tuple[dict[str, Any], int, bool]] = []
+ for pdf_line in pdf_lines:
+ for child_line in _split_pdftext_line_by_rotation(pdf_line):
+ visual_angle = _resolve_pdftext_line_angle(
child_line,
page_rotation=page_rotation,
supported_angles=supported_angles,
)
- )
- is not None
- ]
- for visual_row_id, (pdf_line, visual_angle) in enumerate(supported_lines):
+ formula_candidate_only = False
+ if visual_angle is None:
+ visual_angle = _resolve_pdftext_formula_candidate_angle(
+ child_line,
+ page_rotation=page_rotation,
+ supported_angles=supported_angles,
+ )
+ formula_candidate_only = visual_angle is not None
+ if visual_angle is not None:
+ supported_lines.append((child_line, visual_angle, formula_candidate_only))
+ for visual_row_id, (pdf_line, visual_angle, formula_candidate_only) in enumerate(supported_lines):
bbox = _clip_bbox(_coerce_bbox(pdf_line.get("bbox")), page_size)
if bbox is None:
continue
@@ -93,14 +95,23 @@ def _build_native_line_items(
source_index=-1,
chars=chars,
visual_row_id=visual_row_id,
+ formula_candidate_only=formula_candidate_only,
)
- items.extend(_split_native_visual_runs(coarse_item, page_size))
+ target = formula_items if formula_candidate_only else normal_items
+ target.extend(_split_native_visual_runs(coarse_item, page_size))
- merged_items = _merge_native_inline_scripts(items, page_size)
- for source_index, item in enumerate(merged_items):
+ stable_items = _merge_native_inline_scripts(normal_items, page_size)
+ for source_index, item in enumerate(stable_items):
# source_index 必须在页内唯一,表格投影和失败回滚都依赖该精确成员标识。
item.source_index = source_index
- return merged_items
+ formula_items = _merge_native_inline_scripts(formula_items, page_size)
+ next_source_index = len(stable_items)
+ for item in formula_items:
+ item.source_index = next_source_index
+ next_source_index += 1
+ output = [*stable_items, *formula_items]
+ output.sort(key=lambda item: (item.visual_row_id if item.visual_row_id is not None else math.inf, item.run_index))
+ return output
def _pdftext_angle_degrees(value: Any) -> float:
@@ -124,10 +135,7 @@ def _circular_angle_distance(first: float, second: float) -> float:
def _span_has_visible_text(span: dict[str, Any]) -> bool:
"""判断 span 是否包含可见的非空白字符,换行与占位空格不参与方向拆分。"""
- return any(
- char.isprintable() and not char.isspace()
- for char in str(span.get("text") or "")
- )
+ return any(char.isprintable() and not char.isspace() for char in str(span.get("text") or ""))
def _build_pdftext_child_line(
@@ -137,11 +145,7 @@ def _build_pdftext_child_line(
) -> dict[str, Any]:
"""使用同方向 span 重建子行,并收缩原粗行被异向内容扩大的 bbox。"""
- span_bboxes = [
- bbox
- for span in spans
- if (bbox := _coerce_bbox(span.get("bbox"))) is not None
- ]
+ span_bboxes = [bbox for span in spans if (bbox := _coerce_bbox(span.get("bbox"))) is not None]
child_line = dict(pdf_line)
child_line["spans"] = spans
child_line["bbox"] = _bbox_union_many(span_bboxes) if span_bboxes else pdf_line.get("bbox")
@@ -164,8 +168,7 @@ def _split_pdftext_line_by_rotation(pdf_line: dict[str, Any]) -> list[dict[str,
if (
current_spans
and _span_has_visible_text(span)
- and _circular_angle_distance(span_angle, current_angle)
- >= _PDFTEXT_ROTATION_SPLIT_THRESHOLD_DEGREES
+ and _circular_angle_distance(span_angle, current_angle) >= _PDFTEXT_ROTATION_SPLIT_THRESHOLD_DEGREES
):
output.append(_build_pdftext_child_line(pdf_line, current_spans, current_angle))
current_spans = []
@@ -187,8 +190,7 @@ def _is_supported_pdftext_line_rotation(
visual_angle = (_pdftext_angle_degrees(value) + int(page_rotation or 0)) % 360.0
return any(
- _circular_angle_distance(visual_angle, supported_angle)
- <= _PDFTEXT_LINE_ANGLE_TOLERANCE_DEGREES
+ _circular_angle_distance(visual_angle, supported_angle) <= _PDFTEXT_LINE_ANGLE_TOLERANCE_DEGREES
for supported_angle in supported_angles
)
@@ -201,31 +203,51 @@ def _resolve_pdftext_line_angle(
) -> int | None:
"""解析视觉文字方向,并用字符基线纠正字体 shear 造成的伪斜向行。"""
- visual_angle = (
- _pdftext_angle_degrees(pdf_line.get("rotation"))
- + int(page_rotation or 0)
- ) % 360.0
+ visual_angle = (_pdftext_angle_degrees(pdf_line.get("rotation")) + int(page_rotation or 0)) % 360.0
for supported_angle in supported_angles:
- if (
- _circular_angle_distance(visual_angle, supported_angle)
- <= _PDFTEXT_LINE_ANGLE_TOLERANCE_DEGREES
- ):
+ if _circular_angle_distance(visual_angle, supported_angle) <= _PDFTEXT_LINE_ANGLE_TOLERANCE_DEGREES:
return int(supported_angle)
supports_horizontal = any(
- _circular_angle_distance(0.0, supported_angle)
- <= _PDFTEXT_LINE_ANGLE_TOLERANCE_DEGREES
+ _circular_angle_distance(0.0, supported_angle) <= _PDFTEXT_LINE_ANGLE_TOLERANCE_DEGREES
for supported_angle in supported_angles
)
if (
supports_horizontal
- and _circular_angle_distance(visual_angle, 0.0)
- <= _PDFTEXT_SHEARED_HORIZONTAL_MAX_ANGLE_DEGREES
+ and _circular_angle_distance(visual_angle, 0.0) <= _PDFTEXT_SHEARED_HORIZONTAL_MAX_ANGLE_DEGREES
and _pdftext_line_has_horizontal_char_baseline(pdf_line)
):
return 0
return None
+def _resolve_pdftext_formula_candidate_angle(
+ pdf_line: dict[str, Any],
+ *,
+ page_rotation: int,
+ supported_angles: Sequence[float],
+) -> int | None:
+ """保留小角度字体矩阵下的公式专用粗行,未被公式认领时不回流正文。"""
+ visual_angle = (_pdftext_angle_degrees(pdf_line.get("rotation")) + int(page_rotation or 0)) % 360.0
+ nearest = min(supported_angles, key=lambda angle: _circular_angle_distance(visual_angle, angle))
+ if _circular_angle_distance(visual_angle, nearest) > _PDFTEXT_SHEARED_HORIZONTAL_MAX_ANGLE_DEGREES:
+ return None
+ spans = [span for span in (pdf_line.get("spans") or []) if isinstance(span, dict)]
+ compact_text = "".join(str(span.get("text") or "") for span in spans)
+ compact_text = "".join(char for char in compact_text if char.isprintable() and not char.isspace())
+ if not compact_text:
+ return None
+ has_script_flag = any(span.get("superscript") is True or span.get("subscript") is True for span in spans)
+ has_math_operator = any(char in _PDFTEXT_FORMULA_OPERATOR_CHARS for char in compact_text)
+ font_sizes = [
+ float(size)
+ for span in spans
+ if isinstance(span.get("font"), dict) and isinstance((size := span["font"].get("size")), (int, float)) and size > 0
+ ]
+ has_mixed_sizes = bool(font_sizes) and max(font_sizes) >= 1.35 * min(font_sizes)
+ is_compact_identifier = len(compact_text) <= 3 and all(char.isalnum() for char in compact_text)
+ return int(nearest) if has_script_flag or has_math_operator or has_mixed_sizes or is_compact_identifier else None
+
+
def _pdftext_line_has_horizontal_char_baseline(
pdf_line: dict[str, Any],
) -> bool:
@@ -240,11 +262,7 @@ def _pdftext_line_has_horizontal_char_baseline(
continue
raw_char = str(char.get("char") or "")
bbox = _coerce_bbox(char.get("bbox"))
- if (
- bbox is not None
- and raw_char.isprintable()
- and not raw_char.isspace()
- ):
+ if bbox is not None and raw_char.isprintable() and not raw_char.isspace():
visible_bboxes.append(bbox)
if len(visible_bboxes) < 4:
return False
@@ -254,11 +272,7 @@ def _pdftext_line_has_horizontal_char_baseline(
line_height = line_bbox[3] - line_bbox[1]
glyph_heights = [bbox[3] - bbox[1] for bbox in visible_bboxes]
median_height = statistics.median(glyph_heights)
- if (
- line_height <= 0
- or median_height <= 0
- or line_width / line_height < 3.0
- ):
+ if line_height <= 0 or median_height <= 0 or line_width / line_height < 3.0:
return False
ordered = sorted(
@@ -276,16 +290,11 @@ def _pdftext_line_has_horizontal_char_baseline(
baseline_width = last_center[0] - first_center[0]
if baseline_width <= 0:
return False
- baseline_angle = abs(
- math.degrees(
- math.atan2(last_center[1] - first_center[1], baseline_width)
- )
- )
+ baseline_angle = abs(math.degrees(math.atan2(last_center[1] - first_center[1], baseline_width)))
centers_y = [(bbox[1] + bbox[3]) / 2.0 for bbox in ordered]
return (
baseline_angle <= _PDFTEXT_HORIZONTAL_BASELINE_MAX_ANGLE_DEGREES
- and max(centers_y) - min(centers_y)
- <= _PDFTEXT_HORIZONTAL_BASELINE_MAX_DISPERSION_RATIO * median_height
+ and max(centers_y) - min(centers_y) <= _PDFTEXT_HORIZONTAL_BASELINE_MAX_DISPERSION_RATIO * median_height
)
@@ -366,9 +375,7 @@ def _split_native_visual_runs(
run_tokens = tokens[start:end]
run_text = _normalize_native_run_text("".join(token[1] for token in run_tokens))
run_bboxes = [
- token[2]
- for token in run_tokens
- if token[2] is not None and token[1].isprintable() and not token[1].isspace()
+ token[2] for token in run_tokens if token[2] is not None and token[1].isprintable() and not token[1].isspace()
]
if not run_text or not run_bboxes:
continue
@@ -382,6 +389,7 @@ def _split_native_visual_runs(
visual_row_id=line.visual_row_id,
run_index=run_index,
split_from_row=len(ranges) > 1,
+ formula_candidate_only=line.formula_candidate_only,
)
_fill_native_typography(run_item, page_size)
output.append(run_item)
@@ -438,10 +446,7 @@ def _detect_leading_emphasis_width(
return None
prefix_weight = statistics.median(prefix_weights)
body_weight = statistics.median(body_weights)
- if (
- prefix_weight - body_weight < 100.0
- or prefix_weight < 1.15 * max(1.0, body_weight)
- ):
+ if prefix_weight - body_weight < 100.0 or prefix_weight < 1.15 * max(1.0, body_weight):
return None
prefix_bbox = _bbox_union_many([bbox for bbox, _signature, _weight in prefix])
@@ -628,6 +633,16 @@ def _merge_native_inline_scripts(
for child_index in positions.values():
merge_children(child_index, visiting)
base = lines[base_index]
+ stable_source_indices = [
+ source_index
+ for source_index in [base.source_index, *(lines[child_index].source_index for child_index in positions.values())]
+ if source_index >= 0
+ ]
+ if stable_source_indices:
+ base.source_index = min(stable_source_indices)
+ formula_candidate_only = base.formula_candidate_only and all(
+ lines[child_index].formula_candidate_only for child_index in positions.values()
+ )
merged_bbox = base.bbox
merged_chars = list(base.chars)
if "prefix" in positions:
@@ -637,6 +652,7 @@ def _merge_native_inline_scripts(
merged_bbox = _bbox_union(merged_bbox, prefix.bbox)
merged_chars = [*prefix.chars, *merged_chars]
base.split_from_row = base.split_from_row or prefix.split_from_row
+ base.inline_math_regions.extend(prefix.inline_math_regions)
if "suffix" in positions:
suffix_index = positions["suffix"]
suffix = lines[suffix_index]
@@ -644,14 +660,15 @@ def _merge_native_inline_scripts(
merged_bbox = _bbox_union(merged_bbox, suffix.bbox)
merged_chars.extend(suffix.chars)
base.split_from_row = base.split_from_row or suffix.split_from_row
+ base.inline_math_regions.extend(suffix.inline_math_regions)
base.bbox = merged_bbox
base.chars = merged_chars
# 只有低重叠外置候选才需要按完整二维 bbox 计算后继行距;普通上下标保持原有基线行为。
base.restored_inline_cluster = base.restored_inline_cluster or any(
- lines[child_index].restored_inline_cluster
- or (child_index, base_index, position) in detached_candidate_pairs
+ lines[child_index].restored_inline_cluster or (child_index, base_index, position) in detached_candidate_pairs
for position, child_index in positions.items()
)
+ base.formula_candidate_only = formula_candidate_only
_fill_native_typography(base, page_size)
visiting.remove(base_index)
merged_base_indices.add(base_index)
diff --git a/mineru/model/flash/pdf/pipeline.py b/mineru/model/flash/pdf/pipeline.py
index 8eb5c081..3440f2e5 100644
--- a/mineru/model/flash/pdf/pipeline.py
+++ b/mineru/model/flash/pdf/pipeline.py
@@ -7,14 +7,16 @@ from __future__ import annotations
from dataclasses import replace
from typing import Any
-
+from ....types import BBox
from .._shared.xycut import sort_entries
from .document import PDFDocument, PDFImageInfo, get_lines_from_chars
from .text_styles import (
PDFTextLinkLine,
PDFTextStyleLine,
apply_pdf_text_links,
+ apply_pdf_text_scripts,
apply_pdf_text_styles,
+ detect_pdf_text_script_lines,
detect_pdf_text_link_lines,
detect_pdf_text_style_lines,
materialize_pdf_inline_spans,
@@ -179,7 +181,11 @@ def _filter_repeated_raster_watermark_bboxes(
]
-def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]:
+def _analyze_native_document(
+ pdf_doc: PDFDocument,
+ *,
+ script_diagnostics: list[dict[str, Any]] | None = None,
+) -> list[list[dict[str, Any]]]:
"""逐页读取数字 PDF,并在轻量页面上完成跨页文本类型判定。"""
page_sizes = [pdf_doc.page_size(page_idx) for page_idx in range(pdf_doc.page_count)]
@@ -191,11 +197,13 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
)
page_sources: list[_PageSource] = []
+ page_text_geometries = []
page_style_lines: list[list[PDFTextStyleLine]] = []
page_link_lines: list[list[PDFTextLinkLine]] = []
for page_idx in range(pdf_doc.page_count):
page_size = page_sizes[page_idx]
- chars = pdf_doc.get_page_chars(page_idx)
+ text_geometry = pdf_doc.get_page_chars_with_geometry(page_idx)
+ chars = text_geometry.chars
lines = _build_native_line_items(
get_lines_from_chars(chars),
page_size,
@@ -224,9 +232,35 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
path_infos=pdf_doc.get_page_path_infos(page_idx),
)
page_sources.append(source)
+ page_text_geometries.append(text_geometry)
_classify_raw_page_marginals(page_sources)
- prepared_pages = [_prepare_page_source(source) for source in page_sources]
+ prepared_pages = [
+ _prepare_page_source(
+ source,
+ tight_bboxes=geometry.tight_bboxes,
+ origins=geometry.origins,
+ )
+ for source, geometry in zip(page_sources, page_text_geometries, strict=True)
+ ]
+ if script_diagnostics is not None:
+ script_diagnostics.extend(
+ {
+ "page_index": page_index,
+ "page_size": prepared.page_size,
+ "script_lines": list(prepared.script_lines),
+ "lines": [
+ {
+ "source_index": line.source_index,
+ "text": line.text,
+ "bbox": line.bbox,
+ "angle": line.angle,
+ }
+ for line in prepared.remaining_lines
+ ],
+ }
+ for page_index, prepared in enumerate(prepared_pages)
+ )
_classify_repeated_visual_headers(prepared_pages)
_classify_repeated_page_marginals(prepared_pages)
@@ -256,20 +290,38 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
)
for page_index, prepared in enumerate(prepared_pages)
]
- for page_blocks, style_lines, link_lines, page_size in zip(
- finalized_pages,
- page_style_lines,
- page_link_lines,
- page_sizes,
- strict=True,
+ for page_index, (page_blocks, prepared, style_lines, link_lines, page_size) in enumerate(
+ zip(
+ finalized_pages,
+ prepared_pages,
+ page_style_lines,
+ page_link_lines,
+ page_sizes,
+ strict=True,
+ )
):
apply_pdf_text_links(page_blocks, link_lines, page_size)
apply_pdf_text_styles(page_blocks, style_lines, page_size)
+ materialized_diagnostics = None
+ if script_diagnostics is not None:
+ materialized_diagnostics = []
+ script_diagnostics[page_index]["materialized_ranges"] = materialized_diagnostics
+ apply_pdf_text_scripts(
+ page_blocks,
+ prepared.script_lines,
+ page_size,
+ materialized_diagnostics=materialized_diagnostics,
+ )
materialize_pdf_inline_spans(page_blocks)
return finalized_pages
-def _prepare_page_source(source: _PageSource) -> _PreparedPage:
+def _prepare_page_source(
+ source: _PageSource,
+ *,
+ tight_bboxes: dict[int, BBox] | None = None,
+ origins: dict[int, tuple[float, float]] | None = None,
+) -> _PreparedPage:
"""先认领视觉容器,再标注辅助文本并留下可跨页比较的轻量文本行。"""
protected_line_indices = {line.source_index for line in source.lines if line.semantic_type is not None}
@@ -374,7 +426,18 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:
source.page_size,
table_bboxes,
)
+ formula_candidate_lines = [line for line in remaining_lines if line.formula_candidate_only]
+ remaining_lines = [line for line in remaining_lines if not line.formula_candidate_only]
+ script_lines = detect_pdf_text_script_lines(
+ remaining_lines,
+ source.page_size,
+ tight_bboxes or {},
+ origins or {},
+ all_chars=source.chars,
+ drawing_lines=source.drawing_lines,
+ )
_compact_prepared_lines(remaining_lines, source.page_size)
+ _compact_prepared_lines(formula_candidate_lines, source.page_size)
prepared = _PreparedPage(
page_size=source.page_size,
remaining_lines=remaining_lines,
@@ -390,6 +453,8 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:
+ raster_image_blocks
+ vector_formula_blocks
),
+ script_lines=script_lines,
+ formula_candidate_lines=formula_candidate_lines,
)
_classify_page_auxiliary_text(prepared)
return prepared
@@ -426,7 +491,10 @@ def _finalize_prepared_page(
require_heading=True,
)
semantic_lines.extend(line for line in unresolved_lines if line.semantic_type is not None)
- formula_input = [line for line in unresolved_lines if line.semantic_type is None]
+ formula_input = [
+ *(line for line in unresolved_lines if line.semantic_type is None),
+ *prepared.formula_candidate_lines,
+ ]
formula_input = _restore_dense_split_visual_rows(
formula_input,
prepared.page_size,
@@ -852,6 +920,16 @@ def _normalize_output_block(
"angle": 0 if normalized_type == "image" else int(block.get("angle", 0) or 0) % 360,
"content": content,
}
+ inline_math_regions = []
+ for value in block.get("_inline_math_regions", []):
+ raw_region = _coerce_bbox(value)
+ if raw_region is None:
+ continue
+ region = _clip_bbox(raw_region, page_size)
+ if region is not None:
+ inline_math_regions.append(_normalize_bbox_to_thousandths(region, page_size))
+ if inline_math_regions:
+ output_block["_inline_math_regions"] = inline_math_regions
if normalized_type in _LINE_METADATA_OUTPUT_TYPES:
output_block["lines"] = _normalize_output_line_items(block, page_size)
return output_block
diff --git a/mineru/model/flash/pdf/script_geometry.py b/mineru/model/flash/pdf/script_geometry.py
new file mode 100644
index 00000000..eaf5d1c3
--- /dev/null
+++ b/mineru/model/flash/pdf/script_geometry.py
@@ -0,0 +1,542 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""提供 PDF 字符 loose/tight/origin 驱动的通用上下标几何分类。"""
+
+from __future__ import annotations
+
+import math
+import statistics
+from dataclasses import dataclass
+from typing import Any, Literal
+
+from pdftext.schema import Char
+
+from ....types import BBox
+
+
+SCRIPT_BODY_COMPARABLE_HEIGHT_RATIO = 0.9
+SCRIPT_BASELINE_ABSOLUTE_TOLERANCE = 0.35
+SCRIPT_BASELINE_LOOSE_HEIGHT_RATIO = 0.04
+SCRIPT_ORIGIN_MIN_SHIFT_ABSOLUTE = 0.5
+SCRIPT_ORIGIN_MIN_SHIFT_RATIO = 0.12
+SCRIPT_TIGHT_HEIGHT_RATIO = 0.9
+SCRIPT_STRONG_SHIFT_RATIO = 0.3
+SCRIPT_STRONG_MAX_HEIGHT_RATIO = 1.1
+SCRIPT_CONSENSUS_TIGHT_HEIGHT_RATIO = 0.88
+SCRIPT_CONSENSUS_ORIGIN_SHIFT_RATIO = 0.22
+SCRIPT_CONSENSUS_TIGHT_CENTER_SHIFT_RATIO = 0.3
+SCRIPT_CONSENSUS_LOOSE_CENTER_SHIFT_RATIO = 0.15
+SCRIPT_LOOSE_HEIGHT_ANOMALY_RATIO = 1.35
+SCRIPT_COMPONENT_FORWARD_GAP_RATIO = 1.5
+SCRIPT_COMPONENT_X_BACKTRACK_RATIO = 0.5
+SCRIPT_COMPONENT_SEED_GAP_RATIO = 0.5
+SCRIPT_COMPONENT_SEED_MAX_POSITION_DISTANCE = 4
+SCRIPT_COMPONENT_MIN_OFFSET_RATIO = 0.08
+SCRIPT_COMPONENT_MAX_HEIGHT_RATIO = 1.1
+CONTROL_LINE_BREAK_CHARS = {"\r", "\n"}
+
+ScriptRole = Literal["body", "sup", "sub"]
+ScriptMarkRole = Literal["sup", "sub"]
+
+
+@dataclass(frozen=True, slots=True)
+class ScriptCharFeature:
+ """保存单个字符参与纯几何上下标判定所需的只读特征。"""
+
+ index: int
+ text: str
+ loose_bbox: BBox
+ tight_bbox: BBox | None
+ origin: tuple[float, float] | None
+ is_valid: bool
+ is_body_anchor: bool
+
+ @property
+ def loose_height(self) -> float:
+ """返回 loose bbox 高度。"""
+ return self.loose_bbox[3] - self.loose_bbox[1]
+
+ @property
+ def loose_center_y(self) -> float:
+ """返回 loose bbox 中心 y。"""
+ return (self.loose_bbox[1] + self.loose_bbox[3]) / 2
+
+ @property
+ def tight_height(self) -> float:
+ """返回 tight bbox 高度,无有效框时返回零。"""
+ if self.tight_bbox is None:
+ return 0.0
+ return self.tight_bbox[3] - self.tight_bbox[1]
+
+ @property
+ def tight_center_y(self) -> float | None:
+ """返回 tight bbox 中心 y。"""
+ if self.tight_bbox is None:
+ return None
+ return (self.tight_bbox[1] + self.tight_bbox[3]) / 2
+
+
+@dataclass(frozen=True, slots=True)
+class ScriptBodyBand:
+ """表示当前视觉组件的正文 origin 基线与双 bbox 参考高度。"""
+
+ baseline: float
+ tight_height: float
+ loose_height: float
+ member_indices: frozenset[int]
+
+
+@dataclass(frozen=True, slots=True)
+class ScriptBaselineCluster:
+ """表示共享近似字符 origin 的正文或角标基线簇。"""
+
+ baseline: float
+ member_indices: tuple[int, ...]
+
+
+def _coerce_finite_bbox(value: Any) -> BBox | None:
+ """把可迭代四元组收敛为合法有限 bbox。"""
+ try:
+ raw_bbox = getattr(value, "bbox", value)
+ if raw_bbox is None or len(raw_bbox) != 4:
+ return None
+ bbox = tuple(float(item) for item in raw_bbox)
+ except (TypeError, ValueError):
+ return None
+ if not all(math.isfinite(item) for item in bbox) or bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
+ return None
+ return bbox # type: ignore[return-value]
+
+
+def _char_geometry_key(char: Char) -> int | None:
+ """返回可用于 side-map 查询的合法 PDFium char_idx。"""
+ char_idx = char.get("char_idx")
+ if isinstance(char_idx, bool) or not isinstance(char_idx, int):
+ return None
+ return char_idx
+
+
+def _script_role(offset: float) -> ScriptMarkRole:
+ """把相对正文 origin 基线的纵向偏移转换为上下标角色。"""
+ return "sub" if offset > 0 else "sup"
+
+
+def build_script_features(
+ chars: list[Char],
+ tight_bboxes: dict[int, BBox],
+ origins: dict[int, tuple[float, float]],
+ protected_body_indices: set[int],
+) -> list[ScriptCharFeature]:
+ """一次性构造 loose/tight/origin 三类字符几何特征。"""
+ features = []
+ for index, char in enumerate(chars):
+ text = str(char.get("char", ""))
+ char_idx = _char_geometry_key(char)
+ loose_bbox = _coerce_finite_bbox(char.get("bbox")) or (0.0, 0.0, 0.0, 0.0)
+ tight_bbox = _coerce_finite_bbox(tight_bboxes.get(char_idx)) if char_idx is not None else None
+ raw_origin = origins.get(char_idx) if char_idx is not None else None
+ origin = None
+ if raw_origin is not None:
+ try:
+ candidate_origin = (float(raw_origin[0]), float(raw_origin[1]))
+ except (IndexError, TypeError, ValueError):
+ candidate_origin = None
+ if candidate_origin is not None and all(math.isfinite(value) for value in candidate_origin):
+ origin = candidate_origin
+ is_valid = text not in CONTROL_LINE_BREAK_CHARS and not text.isspace() and tight_bbox is not None and origin is not None
+ features.append(
+ ScriptCharFeature(
+ index=index,
+ text=text,
+ loose_bbox=loose_bbox,
+ tight_bbox=tight_bbox,
+ origin=origin,
+ is_valid=is_valid,
+ is_body_anchor=is_valid and text.isalnum() and index not in protected_body_indices,
+ )
+ )
+ return features
+
+
+def split_script_visual_components(features: list[ScriptCharFeature]) -> list[list[int]]:
+ """按换行、x 回退和大间隙切分独立视觉组件。"""
+ valid_heights = [feature.loose_height for feature in features if feature.loose_height > 0]
+ scale = statistics.median(valid_heights) if valid_heights else 1.0
+ components: list[list[int]] = []
+ current: list[int] = []
+ previous_visible: ScriptCharFeature | None = None
+ for feature in features:
+ if feature.text in CONTROL_LINE_BREAK_CHARS or feature.text.isspace():
+ if current:
+ components.append(current)
+ current = []
+ previous_visible = None
+ continue
+ if feature.is_valid and previous_visible is not None:
+ x_backtrack = previous_visible.loose_bbox[0] - feature.loose_bbox[0]
+ forward_gap = feature.loose_bbox[0] - previous_visible.loose_bbox[2]
+ if (
+ x_backtrack > scale * SCRIPT_COMPONENT_X_BACKTRACK_RATIO
+ or forward_gap > scale * SCRIPT_COMPONENT_FORWARD_GAP_RATIO
+ ):
+ if current:
+ components.append(current)
+ current = []
+ previous_visible = None
+ current.append(feature.index)
+ if feature.is_valid:
+ previous_visible = feature
+ if current:
+ components.append(current)
+ return components
+
+
+def _quantile(values: list[float], fraction: float) -> float:
+ """返回适合小样本基线簇的稳定分位数。"""
+ if not values:
+ return 0.0
+ ordered = sorted(values)
+ index = min(len(ordered) - 1, max(0, round((len(ordered) - 1) * fraction)))
+ return ordered[index]
+
+
+def _cluster_baselines(
+ features: list[ScriptCharFeature],
+ component_indices: list[int],
+) -> tuple[list[ScriptBaselineCluster], float]:
+ """按字符 origin y 聚类当前组件的字母数字基线。"""
+ anchors = [features[index] for index in component_indices if features[index].is_body_anchor]
+ if not anchors:
+ return [], 0.0
+ median_loose_height = statistics.median(feature.loose_height for feature in anchors)
+ tolerance = max(SCRIPT_BASELINE_ABSOLUTE_TOLERANCE, median_loose_height * SCRIPT_BASELINE_LOOSE_HEIGHT_RATIO)
+ groups: list[list[int]] = []
+ for feature in sorted(anchors, key=lambda item: item.origin[1] if item.origin is not None else 0.0):
+ baseline = feature.origin[1] if feature.origin is not None else 0.0
+ if not groups:
+ groups.append([feature.index])
+ continue
+ previous_baseline = statistics.median(
+ features[index].origin[1] for index in groups[-1] if features[index].origin is not None
+ )
+ if abs(baseline - previous_baseline) <= tolerance:
+ groups[-1].append(feature.index)
+ else:
+ groups.append([feature.index])
+ return (
+ [
+ ScriptBaselineCluster(
+ baseline=statistics.median(features[index].origin[1] for index in group if features[index].origin is not None),
+ member_indices=tuple(group),
+ )
+ for group in groups
+ ],
+ tolerance,
+ )
+
+
+def _cluster_tight_height(features: list[ScriptCharFeature], cluster: ScriptBaselineCluster) -> float:
+ """返回基线簇的高分位 tight 高度。"""
+ return _quantile(
+ [features[index].tight_height for index in cluster.member_indices if features[index].tight_height > 0], 0.9
+ )
+
+
+def _cluster_loose_height(features: list[ScriptCharFeature], cluster: ScriptBaselineCluster) -> float:
+ """返回基线簇的高分位 loose 高度。"""
+ return _quantile(
+ [features[index].loose_height for index in cluster.member_indices if features[index].loose_height > 0], 0.9
+ )
+
+
+def _cluster_tight_center(features: list[ScriptCharFeature], cluster: ScriptBaselineCluster) -> float:
+ """返回基线簇的 tight bbox 中心中位数。"""
+ return statistics.median(
+ features[index].tight_center_y for index in cluster.member_indices if features[index].tight_center_y is not None
+ )
+
+
+def _cluster_loose_center(features: list[ScriptCharFeature], cluster: ScriptBaselineCluster) -> float:
+ """返回基线簇的 loose bbox 中心中位数。"""
+ return statistics.median(features[index].loose_center_y for index in cluster.member_indices)
+
+
+def _cluster_has_consistent_displacement(
+ features: list[ScriptCharFeature],
+ cluster: ScriptBaselineCluster,
+ body_cluster: ScriptBaselineCluster,
+ body_band: ScriptBodyBand,
+) -> bool:
+ """要求 origin 与双 bbox 至少两项同向,并排除普通混合字体的弱中心偏移。"""
+ origin_shift = cluster.baseline - body_band.baseline
+ tight_shift = _cluster_tight_center(features, cluster) - _cluster_tight_center(features, body_cluster)
+ loose_shift = _cluster_loose_center(features, cluster) - _cluster_loose_center(features, body_cluster)
+ shifts = (origin_shift, tight_shift, loose_shift)
+ expected_positive = origin_shift > 0
+ if sum(value > 0.05 if expected_positive else value < -0.05 for value in shifts) < 2:
+ return False
+ origin_ratio = abs(origin_shift) / max(body_band.tight_height, 1e-6)
+ tight_ratio = abs(tight_shift) / max(body_band.tight_height, 1e-6)
+ loose_ratio = abs(loose_shift) / max(body_band.loose_height, 1e-6)
+ return origin_ratio >= SCRIPT_CONSENSUS_ORIGIN_SHIFT_RATIO or (
+ tight_ratio >= SCRIPT_CONSENSUS_TIGHT_CENTER_SHIFT_RATIO and loose_ratio >= SCRIPT_CONSENSUS_LOOSE_CENTER_SHIFT_RATIO
+ )
+
+
+def _choose_body_band(
+ features: list[ScriptCharFeature],
+ clusters: list[ScriptBaselineCluster],
+) -> tuple[ScriptBodyBand, ScriptBaselineCluster] | None:
+ """在接近最高字形的基线簇中按字符数选择正文基线。"""
+ if not clusters:
+ return None
+ maximum_height = max(_cluster_tight_height(features, cluster) for cluster in clusters)
+ comparable = [
+ cluster
+ for cluster in clusters
+ if _cluster_tight_height(features, cluster) >= maximum_height * SCRIPT_BODY_COMPARABLE_HEIGHT_RATIO
+ ]
+ body_cluster = max(
+ comparable,
+ key=lambda cluster: (
+ len(cluster.member_indices),
+ _cluster_tight_height(features, cluster),
+ _cluster_loose_height(features, cluster),
+ ),
+ )
+ return (
+ ScriptBodyBand(
+ baseline=body_cluster.baseline,
+ tight_height=_cluster_tight_height(features, body_cluster),
+ loose_height=_cluster_loose_height(features, body_cluster),
+ member_indices=frozenset(body_cluster.member_indices),
+ ),
+ body_cluster,
+ )
+
+
+def _nearest_cluster(
+ feature: ScriptCharFeature,
+ clusters: list[ScriptBaselineCluster],
+ tolerance: float,
+) -> ScriptBaselineCluster | None:
+ """把非字母数字字符附着到最近 origin 基线簇。"""
+ if feature.origin is None or not clusters:
+ return None
+ nearest = min(clusters, key=lambda cluster: abs(feature.origin[1] - cluster.baseline))
+ return nearest if abs(feature.origin[1] - nearest.baseline) <= tolerance else None
+
+
+def _horizontal_gap(first: BBox, second: BBox) -> float:
+ """返回两个字符 tight bbox 的水平间隙。"""
+ return max(0.0, first[0] - second[2], second[0] - first[2])
+
+
+def _drop_unseeded_punctuation(
+ features: list[ScriptCharFeature],
+ component_indices: list[int],
+ roles: list[ScriptRole],
+ body_height: float,
+) -> None:
+ """移除未邻近同类字母数字种子的标点。"""
+ seeded = [
+ features[index]
+ for index in component_indices
+ if roles[index] != "body" and features[index].text.isalnum() and features[index].tight_bbox is not None
+ ]
+ for index in component_indices:
+ feature = features[index]
+ role = roles[index]
+ if role == "body" or feature.text.isalnum() or feature.tight_bbox is None:
+ continue
+ nearby = any(
+ roles[seed.index] == role
+ and _horizontal_gap(feature.tight_bbox, seed.tight_bbox) <= max(2.0, body_height * SCRIPT_COMPONENT_SEED_GAP_RATIO)
+ and abs(feature.index - seed.index) <= SCRIPT_COMPONENT_SEED_MAX_POSITION_DISTANCE
+ for seed in seeded
+ )
+ if not nearby:
+ roles[index] = "body"
+
+
+def _apply_consensus_candidates(
+ features: list[ScriptCharFeature],
+ component_indices: list[int],
+ body_band: ScriptBodyBand,
+ roles: list[ScriptRole],
+) -> None:
+ """用 origin/tight/loose 三证据一致性补充孤立边界字符。"""
+ body_members = [
+ features[index]
+ for index in body_band.member_indices
+ if features[index].tight_bbox is not None
+ and features[index].tight_center_y is not None
+ and features[index].origin is not None
+ ]
+ for index in component_indices:
+ feature = features[index]
+ if (
+ roles[index] != "body"
+ or index in body_band.member_indices
+ or not feature.is_valid
+ or feature.tight_bbox is None
+ or feature.tight_center_y is None
+ or feature.origin is None
+ or not body_members
+ ):
+ continue
+ reference = min(
+ body_members,
+ key=lambda member: (_horizontal_gap(feature.tight_bbox, member.tight_bbox), abs(feature.index - member.index)),
+ )
+ if _horizontal_gap(feature.tight_bbox, reference.tight_bbox) > max(2.5, reference.tight_height * 1.2):
+ continue
+ if feature.tight_height / max(reference.tight_height, 1e-6) > SCRIPT_CONSENSUS_TIGHT_HEIGHT_RATIO:
+ continue
+ shifts = (
+ feature.origin[1] - reference.origin[1],
+ feature.tight_center_y - reference.tight_center_y,
+ feature.loose_center_y - reference.loose_center_y,
+ )
+ positive_votes = sum(value > 0.05 for value in shifts)
+ negative_votes = sum(value < -0.05 for value in shifts)
+ if max(positive_votes, negative_votes) < 2:
+ continue
+ role = "sub" if positive_votes > negative_votes else "sup"
+ if _script_role(shifts[0]) != role:
+ continue
+ origin_ratio = abs(shifts[0]) / max(reference.tight_height, 1e-6)
+ tight_ratio = abs(shifts[1]) / max(reference.tight_height, 1e-6)
+ loose_ratio = abs(shifts[2]) / max(reference.loose_height, 1e-6)
+ if not feature.text.isalnum():
+ expected_positive = role == "sub"
+ if not all(value > 0.05 if expected_positive else value < -0.05 for value in shifts) or not (
+ origin_ratio >= SCRIPT_STRONG_SHIFT_RATIO
+ and tight_ratio >= SCRIPT_CONSENSUS_TIGHT_CENTER_SHIFT_RATIO
+ and loose_ratio >= SCRIPT_CONSENSUS_LOOSE_CENTER_SHIFT_RATIO
+ ):
+ continue
+ if origin_ratio >= SCRIPT_CONSENSUS_ORIGIN_SHIFT_RATIO or (
+ tight_ratio >= SCRIPT_CONSENSUS_TIGHT_CENTER_SHIFT_RATIO
+ and loose_ratio >= SCRIPT_CONSENSUS_LOOSE_CENTER_SHIFT_RATIO
+ ):
+ roles[index] = role
+
+
+def _expand_component_neighbors(
+ features: list[ScriptCharFeature],
+ component_indices: list[int],
+ body_band: ScriptBodyBand,
+ protected_body_indices: set[int],
+ roles: list[ScriptRole],
+) -> None:
+ """把同侧连续字符并入已有角标 run。"""
+ component_set = set(component_indices)
+ changed = True
+ while changed:
+ changed = False
+ for index in component_indices:
+ feature = features[index]
+ if (
+ roles[index] != "body"
+ or index in protected_body_indices
+ or not feature.is_valid
+ or feature.origin is None
+ or feature.text.isspace()
+ or feature.tight_height > body_band.tight_height * SCRIPT_COMPONENT_MAX_HEIGHT_RATIO
+ ):
+ continue
+ neighbor_roles = {
+ roles[neighbor]
+ for neighbor in (index - 1, index + 1)
+ if neighbor in component_set and roles[neighbor] != "body"
+ }
+ if len(neighbor_roles) != 1:
+ continue
+ role = next(iter(neighbor_roles))
+ shift = feature.origin[1] - body_band.baseline
+ if abs(shift) < body_band.tight_height * SCRIPT_COMPONENT_MIN_OFFSET_RATIO or _script_role(shift) != role:
+ continue
+ roles[index] = role
+ changed = True
+
+
+def _assign_component(
+ features: list[ScriptCharFeature],
+ component_indices: list[int],
+ protected_body_indices: set[int],
+ roles: list[ScriptRole],
+) -> None:
+ """在单个视觉组件内按 origin 基线簇和双 bbox 一致性分配角色。"""
+ clusters, tolerance = _cluster_baselines(features, component_indices)
+ body_result = _choose_body_band(features, clusters)
+ if body_result is None:
+ return
+ body_band, body_cluster = body_result
+ if body_band.tight_height <= 0 or body_band.loose_height <= 0:
+ return
+ cluster_roles: dict[ScriptBaselineCluster, ScriptRole] = {body_cluster: "body"}
+ for cluster in clusters:
+ if cluster is body_cluster:
+ continue
+ shift = cluster.baseline - body_band.baseline
+ tight_ratio = _cluster_tight_height(features, cluster) / body_band.tight_height
+ loose_ratio = _cluster_loose_height(features, cluster) / body_band.loose_height
+ minimum_shift = max(SCRIPT_ORIGIN_MIN_SHIFT_ABSOLUTE, body_band.tight_height * SCRIPT_ORIGIN_MIN_SHIFT_RATIO)
+ strong_shift = abs(shift) >= body_band.tight_height * SCRIPT_STRONG_SHIFT_RATIO
+ if (
+ abs(shift) < minimum_shift
+ or (
+ tight_ratio > SCRIPT_TIGHT_HEIGHT_RATIO and not (strong_shift and tight_ratio <= SCRIPT_STRONG_MAX_HEIGHT_RATIO)
+ )
+ or (
+ loose_ratio > SCRIPT_LOOSE_HEIGHT_ANOMALY_RATIO
+ and not _cluster_has_consistent_displacement(features, cluster, body_cluster, body_band)
+ )
+ ):
+ cluster_roles[cluster] = "body"
+ else:
+ cluster_roles[cluster] = _script_role(shift)
+ for index in component_indices:
+ feature = features[index]
+ if (
+ index in protected_body_indices
+ or feature.origin is None
+ or feature.text.isspace()
+ or feature.text in CONTROL_LINE_BREAK_CHARS
+ ):
+ continue
+ cluster = _nearest_cluster(feature, clusters, tolerance)
+ if cluster is not None:
+ roles[index] = cluster_roles.get(cluster, "body")
+ _drop_unseeded_punctuation(features, component_indices, roles, body_band.tight_height)
+ _apply_consensus_candidates(features, component_indices, body_band, roles)
+ _expand_component_neighbors(features, component_indices, body_band, protected_body_indices, roles)
+ for index in protected_body_indices.intersection(component_indices):
+ roles[index] = "body"
+
+
+def classify_char_script_roles(
+ chars: list[Char],
+ *,
+ tight_bboxes: dict[int, BBox],
+ origins: dict[int, tuple[float, float]],
+ protected_body_indices: set[int] | None = None,
+) -> list[ScriptRole]:
+ """按视觉组件、origin 基线簇和双 bbox 一致性识别上下标。"""
+ protected = protected_body_indices or set()
+ features = build_script_features(chars, tight_bboxes, origins, protected)
+ roles: list[ScriptRole] = ["body"] * len(features)
+ for component_indices in split_script_visual_components(features):
+ _assign_component(features, component_indices, protected, roles)
+ return roles
+
+
+__all__ = [
+ "CONTROL_LINE_BREAK_CHARS",
+ "ScriptCharFeature",
+ "ScriptRole",
+ "build_script_features",
+ "classify_char_script_roles",
+ "split_script_visual_components",
+]
diff --git a/mineru/model/flash/pdf/text_blocks.py b/mineru/model/flash/pdf/text_blocks.py
index 587f48db..0fb602ae 100644
--- a/mineru/model/flash/pdf/text_blocks.py
+++ b/mineru/model/flash/pdf/text_blocks.py
@@ -66,9 +66,7 @@ def _starts_structural_reference_entry(
pair_height = max(previous_height, current_height)
return (
current[1][0] <= previous[1][0] - max(5.0, 0.6 * min(previous_height, current_height))
- and -0.75 * pair_height
- <= _effective_text_row_gap(previous, current)
- <= 1.5 * pair_height
+ and -0.75 * pair_height <= _effective_text_row_gap(previous, current) <= 1.5 * pair_height
)
@@ -83,14 +81,11 @@ def _build_hanging_indent_group_map(
return {}
rows = sorted(
(item for item in lane.lines if item[0].semantic_type is None),
- key=lambda item: (item[1
- ][1], item[1][0], item[0].source_index),
+ key=lambda item: (item[1][1], item[1][0], item[0].source_index),
)
if len(rows) < 4:
return {}
- median_height = statistics.median(
- _line_effective_height(line, bbox) for line, bbox in rows
- )
+ median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in rows)
start_tolerance = max(5.0, 0.65 * median_height)
minimum_indent = max(7.0, 0.8 * median_height)
continuation_tolerance = max(4.0, 0.55 * median_height)
@@ -103,15 +98,8 @@ def _build_hanging_indent_group_map(
effective_gap = _effective_text_row_gap(previous, current)
top_pitch = current[1][1] - previous[1][1]
- robust_pitch_fallback = (
- 0.5 * median_height
- <= top_pitch
- <= 1.8 * median_height
- )
- if (
- not -0.6 * median_height <= effective_gap <= 1.3 * median_height
- and not robust_pitch_fallback
- ):
+ robust_pitch_fallback = 0.5 * median_height <= top_pitch <= 1.8 * median_height
+ if not -0.6 * median_height <= effective_gap <= 1.3 * median_height and not robust_pitch_fallback:
return False
if _connection_crosses_table(
previous[0].bbox,
@@ -258,19 +246,11 @@ def _build_grouped_page_footnote_blocks(
) -> tuple[list[dict[str, Any]], set[int]]:
"""按分隔线组切分几何脚注条目,并返回已消费的来源编号。"""
- footnote_by_source = {
- line.source_index: line
- for line in lines
- if line.semantic_type == "page_footnote"
- }
+ footnote_by_source = {line.source_index: line for line in lines if line.semantic_type == "page_footnote"}
blocks: list[dict[str, Any]] = []
consumed_source_indices: set[int] = set()
for source_group in source_groups:
- group_lines = [
- footnote_by_source[source_index]
- for source_index in source_group
- if source_index in footnote_by_source
- ]
+ group_lines = [footnote_by_source[source_index] for source_index in source_group if source_index in footnote_by_source]
for angle in sorted({line.angle for line in group_lines}):
directional_lines = [line for line in group_lines if line.angle == angle]
tight_bboxes = _tight_page_footnote_bboxes(
@@ -292,11 +272,7 @@ def _build_grouped_page_footnote_blocks(
content = _merge_text_line_content([line.text for line in ordered_lines])
if not content:
continue
- visual_row_ids = {
- line.visual_row_id
- for line in ordered_lines
- if line.visual_row_id is not None
- }
+ visual_row_ids = {line.visual_row_id for line in ordered_lines if line.visual_row_id is not None}
single_run_row_id = (
ordered_lines[0].visual_row_id
if len(ordered_lines) == 1
@@ -307,18 +283,15 @@ def _build_grouped_page_footnote_blocks(
blocks.append(
{
"type": "page_footnote",
- "bbox": _bbox_union_many(
- [tight_bboxes[line.source_index] for line in ordered_lines]
- ),
+ "bbox": _bbox_union_many([tight_bboxes[line.source_index] for line in ordered_lines]),
"angle": angle,
"content": content,
"_visual_row_ids": visual_row_ids,
"_single_run_row_id": single_run_row_id,
+ "_inline_math_regions": [region for line in ordered_lines for region in line.inline_math_regions],
}
)
- consumed_source_indices.update(
- line.source_index for line in ordered_lines
- )
+ consumed_source_indices.update(line.source_index for line in ordered_lines)
return blocks, consumed_source_indices
@@ -331,31 +304,15 @@ def _split_page_footnote_entries(
if not lines:
return []
angle = lines[0].angle
- line_geometry = [
- (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))
- for line in lines
- ]
- line_geometry.sort(
- key=lambda item: (item[1][1], item[1][0], item[0].source_index)
- )
+ line_geometry = [(line, _rotate_bbox_to_upright(line.bbox, page_size, angle)) for line in lines]
+ line_geometry.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
if len(line_geometry) == 1:
return [[line_geometry[0][0]]]
- effective_heights = [
- _line_effective_height(line, bbox)
- for line, bbox in line_geometry
- ]
+ effective_heights = [_line_effective_height(line, bbox) for line, bbox in line_geometry]
median_height = statistics.median(effective_heights)
- glyph_widths = [
- line.median_glyph_width
- for line, _bbox in line_geometry
- if line.median_glyph_width is not None
- ]
- median_glyph_width = (
- statistics.median(glyph_widths)
- if glyph_widths
- else 0.5 * median_height
- )
+ glyph_widths = [line.median_glyph_width for line, _bbox in line_geometry if line.median_glyph_width is not None]
+ median_glyph_width = statistics.median(glyph_widths) if glyph_widths else 0.5 * median_height
indent_threshold = max(1.5 * median_height, 2.0 * median_glyph_width)
base_left = min(bbox[0] for _line, bbox in line_geometry)
maximum_row_width = max(bbox[2] - bbox[0] for _line, bbox in line_geometry)
@@ -414,8 +371,7 @@ def _find_page_footnote_marker_rows(
or not 0.0 <= horizontal_gap <= 1.5 * median_height
or body[1][0] - base_left < max(1.5 * marker_width, 0.75 * median_height)
or body_width < max(4.0 * marker_width, 4.0 * median_glyph_width)
- or abs(_bbox_center_y(marker[1]) - _bbox_center_y(body[1]))
- > 0.4 * median_height
+ or abs(_bbox_center_y(marker[1]) - _bbox_center_y(body[1])) > 0.4 * median_height
):
continue
marker_rows.append((marker, body))
@@ -442,11 +398,7 @@ def _split_marked_page_footnote_entries(
maximum_row_width,
indent_threshold,
)
- consumed = {
- line.source_index
- for entry in entries
- for line in entry
- }
+ consumed = {line.source_index for entry in entries for line in entry}
continuation_tolerance = max(0.75 * median_height, 2.0 * median_glyph_width)
for marker_index, (marker, body) in enumerate(marker_rows):
next_marker_top = (
@@ -472,11 +424,7 @@ def _split_marked_page_footnote_entries(
entry_items.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
entries.append([line for line, _bbox in entry_items])
- leftovers = [
- item
- for item in line_geometry
- if item[0].source_index not in consumed
- ]
+ leftovers = [item for item in line_geometry if item[0].source_index not in consumed]
entries.extend(
_split_unmarked_page_footnote_entries(
leftovers,
@@ -487,10 +435,7 @@ def _split_marked_page_footnote_entries(
)
entries.sort(
key=lambda entry: min(
- bbox[1]
- for line in entry
- for candidate, bbox in line_geometry
- if candidate.source_index == line.source_index
+ bbox[1] for line in entry for candidate, bbox in line_geometry if candidate.source_index == line.source_index
)
)
return entries
@@ -515,9 +460,7 @@ def _split_unmarked_page_footnote_entries(
current_is_indented = current[1][0] - base_left > indent_threshold
# 满行后必然续接;其余行按首页观测到的首行/续行缩进模式决定边界。
continues_previous = previous_is_near_full or (
- not current_is_indented
- if first_line_is_indented
- else current_is_indented
+ not current_is_indented if first_line_is_indented else current_is_indented
)
if continues_previous:
entries[-1].append(current[0])
@@ -535,17 +478,9 @@ def _tight_page_footnote_bboxes(
if not lines:
return {}
angle = lines[0].angle
- line_geometry = [
- (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))
- for line in lines
- ]
- line_geometry.sort(
- key=lambda item: (item[1][1], item[1][0], item[0].source_index)
- )
- median_height = statistics.median(
- _line_effective_height(line, bbox)
- for line, bbox in line_geometry
- )
+ line_geometry = [(line, _rotate_bbox_to_upright(line.bbox, page_size, angle)) for line in lines]
+ line_geometry.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
+ median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in line_geometry)
row_pitches = [
current[1][1] - previous[1][1]
for previous, current in zip(line_geometry, line_geometry[1:])
@@ -586,9 +521,7 @@ def _infer_local_text_lane_map(lane: _TextLane) -> dict[int, _TextLane]:
lane.lines,
key=lambda item: (item[1][1], item[1][0], item[0].source_index),
)
- median_height = statistics.median(
- _line_effective_height(line, bbox) for line, bbox in rows
- )
+ median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in rows)
left_tolerance = max(3.0, 0.75 * median_height)
height_ratio_limit = 1.25
runs: list[list[tuple[_LineItem, BBox]]] = []
@@ -611,16 +544,11 @@ def _infer_local_text_lane_map(lane: _TextLane) -> dict[int, _TextLane]:
current_run = [item]
continue
run_left = statistics.median(member[1][0] for member in current_run)
- run_heights = [
- _line_effective_height(member, member_bbox)
- for member, member_bbox in current_run
- ]
+ run_heights = [_line_effective_height(member, member_bbox) for member, member_bbox in current_run]
current_height = _line_effective_height(line, bbox)
if (
abs(bbox[0] - run_left) <= left_tolerance
- and max([*run_heights, current_height])
- / max(0.1, min([*run_heights, current_height]))
- <= height_ratio_limit
+ and max([*run_heights, current_height]) / max(0.1, min([*run_heights, current_height])) <= height_ratio_limit
):
current_run.append(item)
else:
@@ -636,10 +564,7 @@ def _infer_local_text_lane_map(lane: _TextLane) -> dict[int, _TextLane]:
local_left = statistics.median(bbox[0] for _line, bbox in run)
local_right = max(bbox[2] for _line, bbox in run)
local_width = max(0.1, local_right - local_left)
- wide_support = sum(
- bbox[2] - bbox[0] >= 0.7 * local_width
- for _line, bbox in run
- )
+ wide_support = sum(bbox[2] - bbox[0] >= 0.7 * local_width for _line, bbox in run)
if global_width < 1.4 * local_width or wide_support < 3:
continue
local_lane = _TextLane(
@@ -701,11 +626,8 @@ def _structured_text_break_sources(
)
previous_fill = (previous[1][2] - lane.left) / lane_width
vertical_gap = _effective_text_row_gap(previous, current)
- if (
- previous_fill <= 0.8
- and -0.25 * pair_height
- <= vertical_gap
- <= regular_gap + max(0.75 * pair_height, 3.0 * gap_mad)
+ if previous_fill <= 0.8 and -0.25 * pair_height <= vertical_gap <= regular_gap + max(
+ 0.75 * pair_height, 3.0 * gap_mad
):
break_sources.add(current[0].source_index)
return break_sources
@@ -726,11 +648,7 @@ def _build_text_blocks(
page_footnote_groups or [],
page_size,
)
- lines = [
- line
- for line in lines
- if line.source_index not in grouped_footnote_indices
- ]
+ lines = [line for line in lines if line.source_index not in grouped_footnote_indices]
for angle in sorted({line.angle for line in lines}):
line_geometry = [(line, _rotate_bbox_to_upright(line.bbox, page_size, angle)) for line in lines if line.angle == angle]
if not line_geometry:
@@ -777,16 +695,11 @@ def _build_text_blocks(
else:
previous_group = hanging_indent_groups.get(previous[0].source_index)
current_group = hanging_indent_groups.get(current[0].source_index)
- previous_local_lane = local_lane_by_source.get(
- previous[0].source_index
- )
- current_local_lane = local_lane_by_source.get(
- current[0].source_index
- )
+ previous_local_lane = local_lane_by_source.get(previous[0].source_index)
+ current_local_lane = local_lane_by_source.get(current[0].source_index)
connection_lane = (
current_local_lane
- if current_local_lane is not None
- and previous_local_lane is current_local_lane
+ if current_local_lane is not None and previous_local_lane is current_local_lane
else lane
)
if current[0].source_index in structured_break_sources:
@@ -826,30 +739,21 @@ def _build_text_blocks(
for component_geometry in components:
component_lines = [item[0] for item in component_geometry]
- component_local_lane = local_lane_by_source.get(
- component_lines[0].source_index
- )
+ component_local_lane = local_lane_by_source.get(component_lines[0].source_index)
if component_local_lane is None or not all(
- local_lane_by_source.get(line.source_index) is component_local_lane
- for line in component_lines
+ local_lane_by_source.get(line.source_index) is component_local_lane for line in component_lines
):
component_local_lane = lane
if component_lines[0].semantic_type == "doc_title":
# 文档标题保留自然换行,避免混排标题因语言检测在中文折行处插入空格。
content = "\n".join(
- normalized
- for line in component_lines
- if (normalized := _normalize_native_run_text(line.text))
+ normalized for line in component_lines if (normalized := _normalize_native_run_text(line.text))
)
else:
- content = _merge_text_line_content(
- [line.text for line in component_lines]
- )
+ content = _merge_text_line_content([line.text for line in component_lines])
if not content:
continue
- visual_row_ids = {
- line.visual_row_id for line in component_lines if line.visual_row_id is not None
- }
+ visual_row_ids = {line.visual_row_id for line in component_lines if line.visual_row_id is not None}
single_run_row_id = (
component_lines[0].visual_row_id
if len(component_lines) == 1
@@ -866,16 +770,13 @@ def _build_text_blocks(
"_visual_row_ids": visual_row_ids,
"_single_run_row_id": single_run_row_id,
"_local_line_bboxes": [bbox for _line, bbox in component_geometry],
- "_line_heights": [
- _line_effective_height(line, bbox)
- for line, bbox in component_geometry
- ],
+ "_line_heights": [_line_effective_height(line, bbox) for line, bbox in component_geometry],
"_font_signatures": {
line.font_signature
for line in component_lines
- if line.font_signature is not None
- and line.font_coverage >= 0.5
+ if line.font_signature is not None and line.font_coverage >= 0.5
},
+ "_inline_math_regions": [region for line in component_lines for region in line.inline_math_regions],
"_lane_interval": (
component_local_lane.left,
component_local_lane.right,
@@ -913,8 +814,7 @@ def _blocks_share_boundary_visual_row(
lower_boundary = min(lower_rows, key=lambda bbox: (_bbox_center_y(bbox), bbox[0]))
vertical_overlap = max(
0.0,
- min(upper_boundary[3], lower_boundary[3])
- - max(upper_boundary[1], lower_boundary[1]),
+ min(upper_boundary[3], lower_boundary[3]) - max(upper_boundary[1], lower_boundary[1]),
)
shorter_height = max(
0.1,
@@ -955,15 +855,9 @@ def _merge_overlapping_same_line_text_blocks(
):
continue
first_heights = [
- float(height)
- for height in first.get("_line_heights", [])
- if isinstance(height, (int, float)) and height > 0
+ float(height) for height in first.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
]
- first_height = (
- statistics.median(first_heights)
- if first_heights
- else first_bbox[3] - first_bbox[1]
- )
+ first_height = statistics.median(first_heights) if first_heights else first_bbox[3] - first_bbox[1]
for second_index in range(first_index + 1, len(blocks)):
second = blocks[second_index]
second_bbox = second.get("bbox")
@@ -979,20 +873,13 @@ def _merge_overlapping_same_line_text_blocks(
):
continue
second_heights = [
- float(height)
- for height in second.get("_line_heights", [])
- if isinstance(height, (int, float)) and height > 0
+ float(height) for height in second.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
]
- second_height = (
- statistics.median(second_heights)
- if second_heights
- else second_bbox[3] - second_bbox[1]
- )
+ second_height = statistics.median(second_heights) if second_heights else second_bbox[3] - second_bbox[1]
pair_height = max(first_height, second_height, 0.1)
vertical_overlap = max(
0.0,
- min(first_bbox[3], second_bbox[3])
- - max(first_bbox[1], second_bbox[1]),
+ min(first_bbox[3], second_bbox[3]) - max(first_bbox[1], second_bbox[1]),
)
minimum_box_height = max(
0.1,
@@ -1016,8 +903,7 @@ def _merge_overlapping_same_line_text_blocks(
and min(len(first_rows), len(second_rows)) == 1
and abs(first_bbox[0] - second_bbox[0]) <= pair_height
and vertical_overlap / minimum_box_height >= 0.5
- and _bbox_axis_overlap_ratio(first_bbox, second_bbox, axis="x")
- >= 0.75
+ and _bbox_axis_overlap_ratio(first_bbox, second_bbox, axis="x") >= 0.75
)
boundary_overlap = _blocks_share_boundary_visual_row(
first,
@@ -1027,10 +913,7 @@ def _merge_overlapping_same_line_text_blocks(
if fonts_conflict or not (compact_overlap or boundary_overlap):
continue
union_bbox = _bbox_union_many([first_bbox, second_bbox])
- if (
- not boundary_overlap
- and union_bbox[3] - union_bbox[1] > 4.0 * pair_height
- ):
+ if not boundary_overlap and union_bbox[3] - union_bbox[1] > 4.0 * pair_height:
continue
replacement_index = min(first_index, second_index)
replacements[replacement_index] = _merge_internal_text_block_group(
@@ -1040,9 +923,7 @@ def _merge_overlapping_same_line_text_blocks(
consumed.update({first_index, second_index})
break
return [
- replacements.get(index, block)
- for index, block in enumerate(blocks)
- if index not in consumed or index in replacements
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
]
@@ -1063,13 +944,7 @@ def _merge_inline_math_fragment_text_blocks(
if (
host_index in consumed
or host.get("type") != "text"
- or (
- host.get("_single_run_row_id") is None
- and (
- not isinstance(host_rows, list)
- or len(host_rows) > 2
- )
- )
+ or (host.get("_single_run_row_id") is None and (not isinstance(host_rows, list) or len(host_rows) > 2))
or not isinstance(host_bbox, (list, tuple))
or host_bbox[2] - host_bbox[0] < 0.35 * local_page_width
or not isinstance(host_heights, list)
@@ -1077,9 +952,7 @@ def _merge_inline_math_fragment_text_blocks(
):
continue
host_height = statistics.median(
- float(height)
- for height in host_heights
- if isinstance(height, (int, float)) and height > 0
+ float(height) for height in host_heights if isinstance(height, (int, float)) and height > 0
)
fragment_indices: list[int] = []
for candidate_index, candidate in enumerate(blocks):
@@ -1093,8 +966,7 @@ def _merge_inline_math_fragment_text_blocks(
or not isinstance(candidate_bbox, (list, tuple))
or not isinstance(candidate_rows, list)
or len(candidate_rows) != 1
- or candidate_bbox[2] - candidate_bbox[0]
- > 0.25 * (host_bbox[2] - host_bbox[0])
+ or candidate_bbox[2] - candidate_bbox[0] > 0.25 * (host_bbox[2] - host_bbox[0])
or _bbox_axis_overlap_ratio(
host_bbox,
candidate_bbox,
@@ -1106,13 +978,9 @@ def _merge_inline_math_fragment_text_blocks(
union_bbox = _bbox_union_many([host_bbox, candidate_bbox])
vertical_gap = max(
0.0,
- max(host_bbox[1], candidate_bbox[1])
- - min(host_bbox[3], candidate_bbox[3]),
+ max(host_bbox[1], candidate_bbox[1]) - min(host_bbox[3], candidate_bbox[3]),
)
- if (
- vertical_gap <= 0.75 * host_height
- and union_bbox[3] - union_bbox[1] <= 3.5 * host_height
- ):
+ if vertical_gap <= 0.75 * host_height and union_bbox[3] - union_bbox[1] <= 3.5 * host_height:
fragment_indices.append(candidate_index)
if len(fragment_indices) < 2:
continue
@@ -1124,9 +992,7 @@ def _merge_inline_math_fragment_text_blocks(
)
consumed.update(group_indices)
output = [
- replacements.get(index, block)
- for index, block in enumerate(blocks)
- if index not in consumed or index in replacements
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
]
output = _merge_hostless_inline_math_fragment_blocks(output, page_size)
output = _merge_residual_narrow_math_text_blocks(output, page_size)
@@ -1155,22 +1021,14 @@ def _merge_residual_narrow_math_text_blocks(
):
continue
candidate_heights = [
- float(height)
- for height in candidate.get("_line_heights", [])
- if isinstance(height, (int, float)) and height > 0
+ float(height) for height in candidate.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
]
- candidate_height = (
- statistics.median(candidate_heights)
- if candidate_heights
- else candidate_bbox[3] - candidate_bbox[1]
- )
+ candidate_height = statistics.median(candidate_heights) if candidate_heights else candidate_bbox[3] - candidate_bbox[1]
hosts: list[tuple[float, float, int]] = []
for host_index, host in enumerate(blocks):
host_bbox = host.get("bbox")
host_heights = [
- float(height)
- for height in host.get("_line_heights", [])
- if isinstance(height, (int, float)) and height > 0
+ float(height) for height in host.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
]
if (
host_index == candidate_index
@@ -1183,26 +1041,19 @@ def _merge_residual_narrow_math_text_blocks(
or candidate_bbox[2] > host_bbox[2]
):
continue
- host_height = (
- statistics.median(host_heights)
- if host_heights
- else host_bbox[3] - host_bbox[1]
- )
+ host_height = statistics.median(host_heights) if host_heights else host_bbox[3] - host_bbox[1]
vertical_overlap = max(
0.0,
- min(candidate_bbox[3], host_bbox[3])
- - max(candidate_bbox[1], host_bbox[1]),
+ min(candidate_bbox[3], host_bbox[3]) - max(candidate_bbox[1], host_bbox[1]),
)
vertical_gap = max(
0.0,
- max(candidate_bbox[1], host_bbox[1])
- - min(candidate_bbox[3], host_bbox[3]),
+ max(candidate_bbox[1], host_bbox[1]) - min(candidate_bbox[3], host_bbox[3]),
)
pair_height = max(candidate_height, host_height, 0.1)
union_bbox = _bbox_union_many([candidate_bbox, host_bbox])
if (
- vertical_overlap < 0.35 * min(candidate_height, host_height)
- and vertical_gap > 0.5 * pair_height
+ vertical_overlap < 0.35 * min(candidate_height, host_height) and vertical_gap > 0.5 * pair_height
) or union_bbox[3] - union_bbox[1] > 3.0 * pair_height:
continue
hosts.append(
@@ -1222,9 +1073,7 @@ def _merge_residual_narrow_math_text_blocks(
)
consumed.update({candidate_index, host_index})
return [
- replacements.get(index, block)
- for index, block in enumerate(blocks)
- if index not in consumed or index in replacements
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
]
@@ -1235,13 +1084,7 @@ def _merge_hostless_inline_math_fragment_blocks(
"""把没有单一宽宿主但在一栏内二维密集排列的数学碎片合成文本块。"""
grouped_indices: list[list[int]] = []
- for angle in sorted(
- {
- int(block.get("angle", 0) or 0) % 360
- for block in blocks
- if block.get("type") == "text"
- }
- ):
+ for angle in sorted({int(block.get("angle", 0) or 0) % 360 for block in blocks if block.get("type") == "text"}):
local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
candidates = {
index
@@ -1251,8 +1094,7 @@ def _merge_hostless_inline_math_fragment_blocks(
and isinstance(block.get("bbox"), (list, tuple))
and isinstance(block.get("_local_line_bboxes"), list)
and len(block["_local_line_bboxes"]) == 1
- and block["bbox"][2] - block["bbox"][0]
- <= 0.25 * local_page_width
+ and block["bbox"][2] - block["bbox"][0] <= 0.25 * local_page_width
}
while candidates:
component = {candidates.pop()}
@@ -1266,9 +1108,7 @@ def _merge_hostless_inline_math_fragment_blocks(
[],
)
candidate_height = (
- statistics.median(candidate_heights)
- if candidate_heights
- else candidate_bbox[3] - candidate_bbox[1]
+ statistics.median(candidate_heights) if candidate_heights else candidate_bbox[3] - candidate_bbox[1]
)
if any(
(
@@ -1277,28 +1117,24 @@ def _merge_hostless_inline_math_fragment_blocks(
max(candidate_bbox[1], blocks[index]["bbox"][1])
- min(candidate_bbox[3], blocks[index]["bbox"][3]),
)
- <= 0.75 * max(
+ <= 0.75
+ * max(
candidate_height,
- statistics.median(
- blocks[index].get("_line_heights", [])
- )
+ statistics.median(blocks[index].get("_line_heights", []))
if blocks[index].get("_line_heights")
- else blocks[index]["bbox"][3]
- - blocks[index]["bbox"][1],
+ else blocks[index]["bbox"][3] - blocks[index]["bbox"][1],
)
and max(
0.0,
max(candidate_bbox[0], blocks[index]["bbox"][0])
- min(candidate_bbox[2], blocks[index]["bbox"][2]),
)
- <= 1.5 * max(
+ <= 1.5
+ * max(
candidate_height,
- statistics.median(
- blocks[index].get("_line_heights", [])
- )
+ statistics.median(blocks[index].get("_line_heights", []))
if blocks[index].get("_line_heights")
- else blocks[index]["bbox"][3]
- - blocks[index]["bbox"][1],
+ else blocks[index]["bbox"][3] - blocks[index]["bbox"][1],
)
)
for index in component
@@ -1317,9 +1153,7 @@ def _merge_hostless_inline_math_fragment_blocks(
if not component_heights:
continue
median_height = statistics.median(component_heights)
- union_bbox = _bbox_union_many(
- [blocks[index]["bbox"] for index in component]
- )
+ union_bbox = _bbox_union_many([blocks[index]["bbox"] for index in component])
font_signatures = set().union(
*[
signatures
@@ -1332,16 +1166,9 @@ def _merge_hostless_inline_math_fragment_blocks(
)
if (
len(font_signatures) < 2
- or not 0.25 * local_page_width
- <= union_bbox[2] - union_bbox[0]
- <= 0.5 * local_page_width
+ or not 0.25 * local_page_width <= union_bbox[2] - union_bbox[0] <= 0.5 * local_page_width
or union_bbox[3] - union_bbox[1] > 3.5 * median_height
- or sum(
- blocks[index]["bbox"][2] - blocks[index]["bbox"][0]
- >= 3.5 * median_height
- for index in component
- )
- < 2
+ or sum(blocks[index]["bbox"][2] - blocks[index]["bbox"][0] >= 3.5 * median_height for index in component) < 2
):
continue
grouped_indices.append(sorted(component))
@@ -1358,9 +1185,7 @@ def _merge_hostless_inline_math_fragment_blocks(
)
consumed.update(group)
return [
- replacements.get(index, block)
- for index, block in enumerate(blocks)
- if index not in consumed or index in replacements
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
]
@@ -1369,9 +1194,20 @@ def _merge_inline_math_recovery_group(
indices: list[int],
) -> dict[str, Any]:
"""合并数学碎片并保留仅供后续段落闭合使用的内部标记。"""
-
+ member_bboxes = [blocks[index]["bbox"] for index in indices]
+ widths = [bbox[2] - bbox[0] for bbox in member_bboxes]
+ maximum_width = max(widths, default=0.0)
+ detected_regions = [
+ bbox for bbox, width in zip(member_bboxes, widths) if maximum_width <= 0 or width <= 0.25 * maximum_width
+ ]
+ if not detected_regions:
+ detected_regions = list(member_bboxes)
merged = _merge_internal_text_block_group(blocks, indices)
merged[_INLINE_MATH_RECOVERY_MARKER] = True
+ merged["_inline_math_regions"] = [
+ *merged.get("_inline_math_regions", []),
+ *detected_regions,
+ ]
return merged
@@ -1381,13 +1217,7 @@ def _merge_inline_math_paragraph_continuations(
) -> list[dict[str, Any]]:
"""在数学碎片恢复后,合并同栏连续且足够宽的正文段落块。"""
- if (
- sum(
- block.get(_INLINE_MATH_RECOVERY_MARKER) is True
- for block in blocks
- )
- < 2
- ):
+ if sum(block.get(_INLINE_MATH_RECOVERY_MARKER) is True for block in blocks) < 2:
return blocks
lane_groups: list[list[int]] = []
@@ -1396,8 +1226,7 @@ def _merge_inline_math_paragraph_continuations(
key=lambda item: (
int(item[1].get("angle", 0) or 0) % 360,
_text_component_sort_key(item[1])
- if isinstance(item[1].get("_local_line_bboxes"), list)
- and item[1]["_local_line_bboxes"]
+ if isinstance(item[1].get("_local_line_bboxes"), list) and item[1]["_local_line_bboxes"]
else (float("inf"), float("inf")),
),
):
@@ -1410,26 +1239,20 @@ def _merge_inline_math_paragraph_continuations(
):
continue
block_heights = [
- float(height)
- for height in block.get("_line_heights", [])
- if isinstance(height, (int, float)) and height > 0
+ float(height) for height in block.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
]
if not block_heights:
continue
for lane_group in lane_groups:
representative = blocks[lane_group[0]]
- if int(representative.get("angle", 0) or 0) % 360 != int(
- block.get("angle", 0) or 0
- ) % 360:
+ if int(representative.get("angle", 0) or 0) % 360 != int(block.get("angle", 0) or 0) % 360:
continue
representative_heights = [
float(height)
for height in representative.get("_line_heights", [])
if isinstance(height, (int, float)) and height > 0
]
- pair_height = statistics.median(
- [*representative_heights, *block_heights]
- )
+ pair_height = statistics.median([*representative_heights, *block_heights])
if _components_share_lane_role(representative, block, pair_height):
lane_group.append(index)
break
@@ -1478,15 +1301,10 @@ def _merge_inline_math_paragraph_continuations(
vertical_gap = current_local_bbox[1] - previous_local_bbox[3]
connects = (
_components_share_lane_role(previous, current, pair_height)
- and previous_local_bbox[2] - previous_local_bbox[0]
- >= 0.8 * lane_width
- and current_local_bbox[2] - current_local_bbox[0]
- >= 0.8 * lane_width
- and abs(previous_local_bbox[0] - current_local_bbox[0])
- <= 0.75 * pair_height
- and -0.75 * pair_height
- <= vertical_gap
- <= 0.75 * pair_height
+ and previous_local_bbox[2] - previous_local_bbox[0] >= 0.8 * lane_width
+ and current_local_bbox[2] - current_local_bbox[0] >= 0.8 * lane_width
+ and abs(previous_local_bbox[0] - current_local_bbox[0]) <= 0.75 * pair_height
+ and -0.75 * pair_height <= vertical_gap <= 0.75 * pair_height
and not fonts_conflict
and not _component_connection_skips_block(
blocks,
@@ -1505,14 +1323,7 @@ def _merge_inline_math_paragraph_continuations(
consumed: set[int] = set()
replacements: dict[int, dict[str, Any]] = {}
for chain in candidate_chains:
- if (
- len(chain) < 3
- or sum(
- blocks[index].get(_INLINE_MATH_RECOVERY_MARKER) is True
- for index in chain
- )
- < 2
- ):
+ if len(chain) < 3 or sum(blocks[index].get(_INLINE_MATH_RECOVERY_MARKER) is True for index in chain) < 2:
continue
chain_heights = [
float(height)
@@ -1521,13 +1332,7 @@ def _merge_inline_math_paragraph_continuations(
if isinstance(height, (int, float)) and height > 0
]
median_height = statistics.median(chain_heights)
- local_union = _bbox_union_many(
- [
- bbox
- for index in chain
- for bbox in blocks[index]["_local_line_bboxes"]
- ]
- )
+ local_union = _bbox_union_many([bbox for index in chain for bbox in blocks[index]["_local_line_bboxes"]])
if local_union[3] - local_union[1] > 24.0 * median_height:
continue
replacement_index = min(chain)
@@ -1536,9 +1341,7 @@ def _merge_inline_math_paragraph_continuations(
replacements[replacement_index] = merged
consumed.update(chain)
return [
- replacements.get(index, block)
- for index, block in enumerate(blocks)
- if index not in consumed or index in replacements
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
]
@@ -1621,11 +1424,7 @@ def _merge_image_caption_text_blocks(
group_indices,
)
merged_indices.update(tail_indices)
- return [
- replacements.get(index, block)
- for index, block in enumerate(blocks)
- if index not in merged_indices
- ]
+ return [replacements.get(index, block) for index, block in enumerate(blocks) if index not in merged_indices]
def _caption_image_group_bboxes(
@@ -1646,8 +1445,7 @@ def _caption_image_group_bboxes(
for member in group:
overlap = max(
0.0,
- min(candidate[3], member[3])
- - max(candidate[1], member[1]),
+ min(candidate[3], member[3]) - max(candidate[1], member[1]),
)
minimum_height = max(
0.1,
@@ -1658,13 +1456,9 @@ def _caption_image_group_bboxes(
)
horizontal_gap = max(
0.0,
- max(candidate[0], member[0])
- - min(candidate[2], member[2]),
+ max(candidate[0], member[0]) - min(candidate[2], member[2]),
)
- if (
- overlap / minimum_height >= 0.7
- and horizontal_gap <= 2.0 * median_height
- ):
+ if overlap / minimum_height >= 0.7 and horizontal_gap <= 2.0 * median_height:
aligned = True
break
if aligned:
@@ -1691,8 +1485,7 @@ def _caption_seed_matches_image(
_bbox_center_y(bbox) >= image_bbox[3] - 0.25 * median_height
and vertical_gap <= 2.5 * median_height
and _bbox_axis_overlap_ratio(bbox, image_bbox, axis="x") >= 0.35
- and abs(_bbox_center_x(bbox) - _bbox_center_x(image_bbox))
- <= 0.35 * max(image_width, block_width)
+ and abs(_bbox_center_x(bbox) - _bbox_center_x(image_bbox)) <= 0.35 * max(image_width, block_width)
and block_width <= 1.75 * image_width
)
@@ -1730,15 +1523,10 @@ def _caption_body_has_structural_gap(
previous_bbox, previous_height = seed_rows[-1]
current_bbox, current_height = candidate_rows[0]
internal_gaps = [
- max(0.0, current[0][1] - (previous[0][1] + float(previous[1])))
- for previous, current in zip(seed_rows, seed_rows[1:])
+ max(0.0, current[0][1] - (previous[0][1] + float(previous[1]))) for previous, current in zip(seed_rows, seed_rows[1:])
]
regular_gap = statistics.median(internal_gaps) if internal_gaps else 0.0
- gap_mad = (
- statistics.median(abs(gap - regular_gap) for gap in internal_gaps)
- if internal_gaps
- else 0.0
- )
+ gap_mad = statistics.median(abs(gap - regular_gap) for gap in internal_gaps) if internal_gaps else 0.0
seed_fonts = seed.get("_font_signatures")
candidate_fonts = candidate.get("_font_signatures")
reliable_style_change = (
@@ -1777,10 +1565,7 @@ def _caption_tail_matches_seed(
if _caption_body_has_structural_gap(seed, candidate):
return False
vertical_gap = max(0.0, candidate_bbox[1] - seed_bbox[3])
- if (
- vertical_gap > 0.5 * median_height
- or _bbox_axis_overlap_ratio(seed_bbox, candidate_bbox, axis="x") < 0.35
- ):
+ if vertical_gap > 0.5 * median_height or _bbox_axis_overlap_ratio(seed_bbox, candidate_bbox, axis="x") < 0.35:
return False
seed_fonts = seed.get("_font_signatures")
candidate_fonts = candidate.get("_font_signatures")
@@ -1804,8 +1589,7 @@ def _merge_multiline_title_blocks(
indices = [
index
for index, block in enumerate(blocks)
- if block.get("type") == block_type
- and isinstance(block.get("bbox"), (list, tuple))
+ if block.get("type") == block_type and isinstance(block.get("bbox"), (list, tuple))
]
indices.sort(
key=lambda index: (
@@ -1846,9 +1630,7 @@ def _merge_multiline_title_blocks(
and previous_fonts.isdisjoint(current_fonts)
)
if (
- -0.2 * max(previous_height, current_height)
- <= vertical_gap
- <= 0.4 * max(previous_height, current_height)
+ -0.2 * max(previous_height, current_height) <= vertical_gap <= 0.4 * max(previous_height, current_height)
and _bbox_axis_overlap_ratio(
previous_bbox,
current_bbox,
@@ -1868,11 +1650,7 @@ def _merge_multiline_title_blocks(
group,
)
consumed.update(group[1:])
- return [
- replacements.get(index, block)
- for index, block in enumerate(blocks)
- if index not in consumed
- ]
+ return [replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed]
def _merge_fragmented_header_blocks(
@@ -1896,14 +1674,9 @@ def _merge_fragmented_header_blocks(
bbox = blocks[index]["bbox"]
heights = blocks[index].get("_line_heights", [])
effective_height = (
- statistics.median(heights)
- if isinstance(heights, list) and heights
- else max(0.1, bbox[3] - bbox[1])
+ statistics.median(heights) if isinstance(heights, list) and heights else max(0.1, bbox[3] - bbox[1])
)
- if (
- blocks[index].get("type") == "header"
- and bbox[2] - bbox[0] > 1.25 * effective_height
- ):
+ if blocks[index].get("type") == "header" and bbox[2] - bbox[0] > 1.25 * effective_height:
continue
if not components:
components.append([index])
@@ -1917,8 +1690,7 @@ def _merge_fragmented_header_blocks(
else max(0.1, previous_bbox[3] - previous_bbox[1])
)
if (
- bbox[0] - previous_bbox[2]
- <= 4.0 * max(effective_height, previous_height)
+ bbox[0] - previous_bbox[2] <= 4.0 * max(effective_height, previous_height)
and _bbox_axis_overlap_ratio(previous_bbox, bbox, axis="y") >= 0.5
):
components[-1].append(index)
@@ -1935,11 +1707,7 @@ def _merge_fragmented_header_blocks(
replacement["_single_run_row_id"] = None
replacements[component[0]] = replacement
consumed.update(component[1:])
- return [
- replacements.get(index, block)
- for index, block in enumerate(blocks)
- if index not in consumed
- ]
+ return [replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed]
def _merge_front_matter_column_blocks(
@@ -1956,10 +1724,7 @@ def _merge_front_matter_column_blocks(
if page_width <= 0 or page_height <= 0:
return blocks
title_blocks = [
- block
- for block in blocks
- if block.get("type") == "doc_title"
- and isinstance(block.get("bbox"), (list, tuple))
+ block for block in blocks if block.get("type") == "doc_title" and isinstance(block.get("bbox"), (list, tuple))
]
if not title_blocks:
return blocks
@@ -1970,7 +1735,8 @@ def _merge_front_matter_column_blocks(
if block.get("type") == "text"
and isinstance(block.get("bbox"), (list, tuple))
and title_bottom < block["bbox"][1]
- and block["bbox"][3] <= min(
+ and block["bbox"][3]
+ <= min(
0.4 * page_height,
title_bottom + 0.22 * page_height,
)
@@ -1979,10 +1745,7 @@ def _merge_front_matter_column_blocks(
]
if len(candidates) < 9:
return blocks
- median_height = statistics.median(
- blocks[index]["bbox"][3] - blocks[index]["bbox"][1]
- for index in candidates
- )
+ median_height = statistics.median(blocks[index]["bbox"][3] - blocks[index]["bbox"][1] for index in candidates)
row_groups: list[list[int]] = []
for index in sorted(
candidates,
@@ -1996,13 +1759,7 @@ def _merge_front_matter_column_blocks(
(
row
for row in row_groups
- if abs(
- center_y
- - statistics.median(
- _bbox_center_y(blocks[member]["bbox"])
- for member in row
- )
- )
+ if abs(center_y - statistics.median(_bbox_center_y(blocks[member]["bbox"]) for member in row))
<= 0.6 * median_height
),
None,
@@ -2016,9 +1773,7 @@ def _merge_front_matter_column_blocks(
for row in row_groups
if 3 <= len(row) <= 6
and (
- max(blocks[index]["bbox"][2] for index in row)
- - min(blocks[index]["bbox"][0] for index in row)
- >= 0.55 * page_width
+ max(blocks[index]["bbox"][2] for index in row) - min(blocks[index]["bbox"][0] for index in row) >= 0.55 * page_width
)
]
if len(dense_rows) < 2:
@@ -2027,33 +1782,16 @@ def _merge_front_matter_column_blocks(
dense_rows,
key=lambda row: (
-len(row),
- statistics.median(
- _bbox_center_y(blocks[index]["bbox"])
- for index in row
- ),
+ statistics.median(_bbox_center_y(blocks[index]["bbox"]) for index in row),
),
)
- anchor_centers = sorted(
- _bbox_center_x(blocks[index]["bbox"])
- for index in anchor_row
- )
+ anchor_centers = sorted(_bbox_center_x(blocks[index]["bbox"]) for index in anchor_row)
if len(anchor_centers) != 4:
return blocks
- boundaries = [
- 0.5 * (left + right)
- for left, right in zip(anchor_centers, anchor_centers[1:])
- ]
- band_top = min(
- min(blocks[index]["bbox"][1] for index in row)
- for row in dense_rows
- ) - median_height
- band_bottom = max(
- max(blocks[index]["bbox"][3] for index in row)
- for row in dense_rows
- ) + median_height
- column_groups: list[list[int]] = [
- [] for _center in anchor_centers
- ]
+ boundaries = [0.5 * (left + right) for left, right in zip(anchor_centers, anchor_centers[1:])]
+ band_top = min(min(blocks[index]["bbox"][1] for index in row) for row in dense_rows) - median_height
+ band_bottom = max(max(blocks[index]["bbox"][3] for index in row) for row in dense_rows) + median_height
+ column_groups: list[list[int]] = [[] for _center in anchor_centers]
for index in candidates:
bbox = blocks[index]["bbox"]
if not band_top <= _bbox_center_y(bbox) <= band_bottom:
@@ -2081,11 +1819,7 @@ def _merge_front_matter_column_blocks(
ordered,
)
consumed.update(ordered[1:])
- return [
- replacements.get(index, block)
- for index, block in enumerate(blocks)
- if index not in consumed
- ]
+ return [replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed]
def _merge_repeated_compact_title_continuations(
@@ -2111,15 +1845,10 @@ def _merge_repeated_compact_title_continuations(
angle = int(title.get("angle", 0) or 0) % 360
local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
line_heights = [
- float(height)
- for height in title.get("_line_heights", [])
- if isinstance(height, (int, float)) and height > 0
+ float(height) for height in title.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
]
title_height = statistics.median(line_heights) if line_heights else 0.0
- if (
- title_height <= 0
- or title_bbox[2] - title_bbox[0] > 0.55 * local_page_width
- ):
+ if title_height <= 0 or title_bbox[2] - title_bbox[0] > 0.55 * local_page_width:
continue
continuations: list[tuple[float, int]] = []
@@ -2137,10 +1866,7 @@ def _merge_repeated_compact_title_continuations(
):
continue
gap = text_bbox[1] - title_bbox[3]
- if (
- -0.25 * title_height <= gap <= 0.6 * title_height
- and abs(text_bbox[0] - title_bbox[0]) <= 0.75 * title_height
- ):
+ if -0.25 * title_height <= gap <= 0.6 * title_height and abs(text_bbox[0] - title_bbox[0]) <= 0.75 * title_height:
continuations.append((max(0.0, gap), text_index))
if continuations:
_gap, text_index = min(continuations)
@@ -2150,8 +1876,7 @@ def _merge_repeated_compact_title_continuations(
for title_index, text_index, title_height in candidate_pairs:
title_bbox = blocks[title_index]["bbox"]
support_count = sum(
- abs(blocks[other_title]["bbox"][0] - title_bbox[0])
- <= max(title_height, other_height)
+ abs(blocks[other_title]["bbox"][0] - title_bbox[0]) <= max(title_height, other_height)
and 0.75 <= other_height / title_height <= 1.25
for other_title, _other_text, other_height in candidate_pairs
)
@@ -2173,9 +1898,7 @@ def _merge_repeated_compact_title_continuations(
replacements[min(title_index, text_index)] = merged
consumed.update({title_index, text_index})
return [
- replacements.get(index, block)
- for index, block in enumerate(blocks)
- if index not in consumed or index in replacements
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
]
@@ -2204,23 +1927,11 @@ def _merge_internal_text_block_group(
else _merge_text_line_content(contents)
)
merged["_visual_row_ids"] = set().union(
- *[
- row_ids
- for index in ordered_indices
- if isinstance((row_ids := blocks[index].get("_visual_row_ids")), set)
- ]
+ *[row_ids for index in ordered_indices if isinstance((row_ids := blocks[index].get("_visual_row_ids")), set)]
)
merged["_single_run_row_id"] = None
- merged["_local_line_bboxes"] = [
- bbox
- for index in ordered_indices
- for bbox in blocks[index].get("_local_line_bboxes", [])
- ]
- merged["_line_heights"] = [
- height
- for index in ordered_indices
- for height in blocks[index].get("_line_heights", [])
- ]
+ merged["_local_line_bboxes"] = [bbox for index in ordered_indices for bbox in blocks[index].get("_local_line_bboxes", [])]
+ merged["_line_heights"] = [height for index in ordered_indices for height in blocks[index].get("_line_heights", [])]
merged["_font_signatures"] = set().union(
*[
signatures
@@ -2231,6 +1942,9 @@ def _merge_internal_text_block_group(
)
]
)
+ merged["_inline_math_regions"] = [
+ region for index in ordered_indices for region in blocks[index].get("_inline_math_regions", [])
+ ]
return merged
@@ -2351,9 +2065,7 @@ def _merge_spatial_text_components(
)
merged = dict(blocks[ordered_indices[0]])
merged["bbox"] = _bbox_union_many([blocks[index]["bbox"] for index in ordered_indices])
- merged["content"] = _merge_text_line_content(
- [str(blocks[index].get("content", "")) for index in ordered_indices]
- )
+ merged["content"] = _merge_text_line_content([str(blocks[index].get("content", "")) for index in ordered_indices])
merged["_visual_row_ids"] = set().union(
*[
block_ids
@@ -2366,15 +2078,9 @@ def _merge_spatial_text_components(
)
merged["_single_run_row_id"] = None
merged["_local_line_bboxes"] = [
- bbox
- for index in ordered_indices
- for bbox in blocks[index].get("_local_line_bboxes", [])
- ]
- merged["_line_heights"] = [
- height
- for index in ordered_indices
- for height in blocks[index].get("_line_heights", [])
+ bbox for index in ordered_indices for bbox in blocks[index].get("_local_line_bboxes", [])
]
+ merged["_line_heights"] = [height for index in ordered_indices for height in blocks[index].get("_line_heights", [])]
merged["_font_signatures"] = set().union(
*[
signatures
@@ -2385,6 +2091,9 @@ def _merge_spatial_text_components(
)
]
)
+ merged["_inline_math_regions"] = [
+ region for index in ordered_indices for region in blocks[index].get("_inline_math_regions", [])
+ ]
output.append(merged)
return output
@@ -2430,10 +2139,7 @@ def _compatible_component_lane_width(
if first_interval is None or second_interval is None:
return local_page_width
tolerance = 0.75 * median_height
- if (
- abs(first_interval[0] - second_interval[0]) > tolerance
- or abs(first_interval[1] - second_interval[1]) > tolerance
- ):
+ if abs(first_interval[0] - second_interval[0]) > tolerance or abs(first_interval[1] - second_interval[1]) > tolerance:
return local_page_width
return min(
first_interval[1] - first_interval[0],
@@ -2481,10 +2187,7 @@ def _block_starts_with_short_wide_rows(
first_width = first_bbox[2] - first_bbox[0]
second_width = second_bbox[2] - second_bbox[0]
reference_width = _component_reference_width(block, local_page_width)
- return (
- first_width <= 0.35 * reference_width
- and second_width >= max(0.25 * reference_width, 1.8 * first_width)
- )
+ return first_width <= 0.35 * reference_width and second_width >= max(0.25 * reference_width, 1.8 * first_width)
def _find_short_opener_pairs(
@@ -2594,13 +2297,9 @@ def _has_parallel_text_component(
candidate_bbox = blocks[candidate_index]["bbox"]
vertical_overlap = max(
0.0,
- min(current_bbox[3], candidate_bbox[3])
- - max(current_bbox[1], candidate_bbox[1]),
- )
- horizontally_separate = (
- candidate_bbox[0] >= current_bbox[2]
- or current_bbox[0] >= candidate_bbox[2]
+ min(current_bbox[3], candidate_bbox[3]) - max(current_bbox[1], candidate_bbox[1]),
)
+ horizontally_separate = candidate_bbox[0] >= current_bbox[2] or current_bbox[0] >= candidate_bbox[2]
if vertical_overlap > 0 and horizontally_separate:
return True
return False
@@ -2678,11 +2377,7 @@ def _component_connection_skips_block(
continue
other_bbox = local_bboxes[0]
other_center = _bbox_center_y(other_bbox)
- if not (
- corridor_top + 0.1 * median_height
- < other_center
- < corridor_bottom - 0.1 * median_height
- ):
+ if not (corridor_top + 0.1 * median_height < other_center < corridor_bottom - 0.1 * median_height):
continue
if _bbox_axis_overlap_ratio(corridor_bbox, other_bbox, axis="x") >= 0.2:
return True
diff --git a/mineru/model/flash/pdf/text_styles.py b/mineru/model/flash/pdf/text_styles.py
index c7723a8d..29b2866c 100644
--- a/mineru/model/flash/pdf/text_styles.py
+++ b/mineru/model/flash/pdf/text_styles.py
@@ -7,6 +7,7 @@ import html
import math
import re
import statistics
+import unicodedata
from dataclasses import dataclass
from typing import Any, Iterable, Literal, Sequence, TypeVar, cast
@@ -21,6 +22,8 @@ from .._shared.spans import (
normalize_span_dicts,
)
from .document import PDFLinkAnnotation
+from .geometry import _rotate_bbox_to_upright
+from .script_geometry import ScriptRole, classify_char_script_roles
from ....utils.text import is_hyphen_at_line_end
@@ -38,7 +41,15 @@ PDF_BOLD_MIN_WEIGHT = 600.0
PDF_BOLD_MIN_COMPARABLE_CHAR_COUNT = 2
PDF_LINK_CHAR_OVERLAP_THRESHOLD = 0.5
-PDFTextStyle = Literal["bold", "italic", "underline", "strikethrough"]
+PDFTextStyle = Literal[
+ "bold",
+ "italic",
+ "underline",
+ "strikethrough",
+ "superscript",
+ "subscript",
+]
+PDFScriptStyle = Literal["superscript", "subscript"]
_PDF_LINK_INTERVALS_KEY = "_inline_link_intervals"
_PDF_STYLE_INTERVALS_KEY = "_inline_style_intervals"
PDF_NATIVE_SCRIPT_MARKUP_KEY = "_pdf_native_script_markup"
@@ -66,6 +77,8 @@ PDF_TEXT_STYLE_ORDER: tuple[PDFTextStyle, ...] = (
"italic",
"underline",
"strikethrough",
+ "superscript",
+ "subscript",
)
_PDF_TEXT_DECORATION_ORDER: tuple[PDFTextDecoration, ...] = (
"underline",
@@ -94,6 +107,8 @@ _PDF_TEXT_STYLE_TARGET_BLOCK_TYPES: dict[PDFTextStyle, frozenset[str]] = {
"italic": frozenset(),
"underline": frozenset({BlockType.TEXT}),
"strikethrough": PDF_NATURAL_TEXT_STYLE_BLOCK_TYPES,
+ "superscript": PDF_NATURAL_TEXT_STYLE_BLOCK_TYPES,
+ "subscript": PDF_NATURAL_TEXT_STYLE_BLOCK_TYPES,
}
_PDF_FONT_SUBSET_PREFIX_RE = re.compile(r"^[A-Z]{6}\+")
@@ -117,6 +132,16 @@ _LIGATURE_REPLACEMENTS = {
"ſt": "ft",
"st": "st",
}
+_PDF_SCRIPT_TOKEN_CONNECTORS = frozenset({"^", "_", "ˆ", "~"})
+_PDF_SCRIPT_CITATION_BRACKETS = {
+ "[": "]",
+ "[": "]",
+}
+_PDF_SCRIPT_AUTHOR_MARKS = frozenset({"*", "†", "‡", "∗"})
+_PDF_SCRIPT_SIGN_CHARS = frozenset({"+", "-", "−", "–", "⁻", "⁺"})
+_PDF_SCRIPT_SPACED_OPERATORS = frozenset({"+", "-", "−", "–"})
+_PDF_SCRIPT_TRAILING_MARKS = frozenset({")", ")"})
+_PDF_SCRIPT_MATH_BASE_CHARS = frozenset({"∆", "Δ", "σ", "Σ", "φ", "Φ", "μ", "µ", "Ω", "Ω", "λ", "γ", "δ", "ρ", "β", "α"})
@dataclass(frozen=True, slots=True)
@@ -138,6 +163,29 @@ class PDFTextStyleLine:
source_index: int
+@dataclass(frozen=True, slots=True)
+class PDFTextScriptRange:
+ """保存 Flash 上下标的文本区间、页面 tight bbox 与稳定性证据。"""
+
+ start: int
+ end: int
+ style: PDFScriptStyle
+ bbox: BBox
+ stable_body_count: int
+ formula_region: bool
+
+
+@dataclass(frozen=True, slots=True)
+class PDFTextScriptLine:
+ """保存一个 Flash 视觉行的紧凑文本及上下标候选。"""
+
+ bbox: BBox
+ text: str
+ script_ranges: tuple[PDFTextScriptRange, ...]
+ source_index: int
+ angle: int
+
+
@dataclass(frozen=True, slots=True)
class PDFTextLinkRange:
"""保存可比较文本中的一个半开超链接区间。"""
@@ -161,6 +209,7 @@ PDFTextEvidenceLine = TypeVar(
"PDFTextEvidenceLine",
PDFTextStyleLine,
PDFTextLinkLine,
+ PDFTextScriptLine,
)
@@ -586,6 +635,785 @@ def _line_style_payload(line: _LineCandidate) -> PDFTextStyleLine | None:
)
+def _rotate_origin_to_upright(
+ origin: tuple[float, float],
+ page_size: tuple[float, float],
+ angle: int,
+) -> tuple[float, float]:
+ """把页面字符 origin 旋到当前 Flash 行的局部正向坐标。"""
+ x, y = origin
+ page_width, page_height = page_size
+ if angle == 270:
+ return page_height - y, x
+ if angle == 90:
+ return y, page_width - x
+ if angle == 180:
+ return page_width - x, page_height - y
+ return origin
+
+
+def _bbox_center_inside_region(bbox: BBox, region: BBox) -> bool:
+ """判断字符 tight bbox 中心是否落入公式区域。"""
+ center_x = (bbox[0] + bbox[2]) / 2
+ center_y = (bbox[1] + bbox[3]) / 2
+ return region[0] <= center_x <= region[2] and region[1] <= center_y <= region[3]
+
+
+def _script_region_memberships(
+ chars: list[dict[str, Any]],
+ tight_bboxes: dict[int, BBox],
+ regions: list[BBox],
+) -> list[int | None]:
+ """按页面 tight 中心把字符分配到公式区域,区域外返回 None。"""
+ memberships: list[int | None] = []
+ for char in chars:
+ char_idx = char.get("char_idx")
+ tight_bbox = tight_bboxes.get(char_idx) if isinstance(char_idx, int) else None
+ region_index = None
+ if tight_bbox is not None:
+ region_index = next(
+ (index for index, region in enumerate(regions) if _bbox_center_inside_region(tight_bbox, region)),
+ None,
+ )
+ memberships.append(region_index)
+ return memberships
+
+
+def _script_char_text(char: dict[str, Any]) -> str:
+ """返回单字符脚本判定使用的稳定文本。"""
+ return str(char.get("char", ""))
+
+
+def _is_cjk_text(text: str) -> bool:
+ """判断单字符是否属于 CJK、日文假名或韩文书写系统。"""
+ if len(text) != 1:
+ return False
+ codepoint = ord(text)
+ return (
+ 0x3400 <= codepoint <= 0x4DBF
+ or 0x4E00 <= codepoint <= 0x9FFF
+ or 0xF900 <= codepoint <= 0xFAFF
+ or 0x3040 <= codepoint <= 0x30FF
+ or 0xAC00 <= codepoint <= 0xD7AF
+ )
+
+
+def _is_math_identifier_char(text: str) -> bool:
+ """识别可与拉丁 base/index 共同组成数学 token 的字母数字字符。"""
+ if len(text) != 1 or _is_cjk_text(text):
+ return False
+ if text.isascii():
+ return text.isalnum()
+ category = unicodedata.category(text)
+ unicode_name = unicodedata.name(text, "")
+ return (
+ text in _PDF_SCRIPT_MATH_BASE_CHARS
+ or "GREEK" in unicode_name
+ or "MATHEMATICAL" in unicode_name
+ or category in {"Lu", "Ll", "Lm"}
+ )
+
+
+def _is_math_script_token_char(text: str) -> bool:
+ """判断字符是否属于可按 source order 重新锚定的数学 token。"""
+ return _is_math_identifier_char(text) or text in _PDF_SCRIPT_TOKEN_CONNECTORS
+
+
+def _iter_math_script_tokens(chars: list[dict[str, Any]]) -> list[list[int]]:
+ """按连续数学 identifier 和连接符切分局部 token,并在 CJK 边界断开。"""
+ tokens: list[list[int]] = []
+ current: list[int] = []
+ for index, char in enumerate(chars):
+ if _is_math_script_token_char(_script_char_text(char)):
+ current.append(index)
+ continue
+ if current:
+ tokens.append(current)
+ current = []
+ if current:
+ tokens.append(current)
+ return tokens
+
+
+def _citation_script_indices(chars: list[dict[str, Any]], roles: list[ScriptRole]) -> set[int]:
+ """识别方括号引用区间,避免保守 token 规则删除数字引用。"""
+ protected: set[int] = set()
+ for start, char in enumerate(chars):
+ closing = _PDF_SCRIPT_CITATION_BRACKETS.get(_script_char_text(char))
+ if closing is None:
+ continue
+ for end in range(start + 1, min(len(chars), start + 16)):
+ if _script_char_text(chars[end]) != closing:
+ continue
+ if any(roles[index] != "body" and _script_char_text(chars[index]).isalnum() for index in range(start + 1, end)):
+ protected.update(range(start, end + 1))
+ break
+ return protected
+
+
+def _token_origin(
+ char: dict[str, Any],
+ origins: dict[int, tuple[float, float]],
+) -> float | None:
+ """读取 token 字符的局部正向 origin y。"""
+ char_idx = char.get("char_idx")
+ origin = origins.get(char_idx) if isinstance(char_idx, int) else None
+ return float(origin[1]) if origin is not None else None
+
+
+def _token_tight_height(
+ char: dict[str, Any],
+ tight_bboxes: dict[int, BBox],
+) -> float:
+ """读取 token 字符的局部正向 tight 高度。"""
+ char_idx = char.get("char_idx")
+ bbox = tight_bboxes.get(char_idx) if isinstance(char_idx, int) else None
+ return max(0.0, bbox[3] - bbox[1]) if bbox is not None else 0.0
+
+
+def _has_adjacent_math_base(
+ chars: list[dict[str, Any]],
+ index: int,
+ roles: list[ScriptRole],
+ tight_bboxes: dict[int, BBox],
+ origins: dict[int, tuple[float, float]],
+) -> bool:
+ """判断孤立索引左侧是否存在紧邻且位移明确的非 CJK 数学 base。"""
+ if index <= 0 or roles[index - 1] != "body":
+ return False
+ base_text = _script_char_text(chars[index - 1])
+ if not _is_math_identifier_char(base_text):
+ return False
+ base_origin = _token_origin(chars[index - 1], origins)
+ script_origin = _token_origin(chars[index], origins)
+ base_height = _token_tight_height(chars[index - 1], tight_bboxes)
+ base_idx = chars[index - 1].get("char_idx")
+ script_idx = chars[index].get("char_idx")
+ base_bbox = tight_bboxes.get(base_idx) if isinstance(base_idx, int) else None
+ script_bbox = tight_bboxes.get(script_idx) if isinstance(script_idx, int) else None
+ if base_origin is None or script_origin is None or base_bbox is None or script_bbox is None:
+ return False
+ return (
+ _bbox_axis_overlap(base_bbox, script_bbox, axis="y") > 0
+ or _horizontal_gap_between_bboxes(base_bbox, script_bbox) <= max(2.0, 0.5 * base_height)
+ ) and abs(script_origin - base_origin) >= max(0.35, 0.08 * base_height)
+
+
+def _horizontal_gap_between_bboxes(first: BBox, second: BBox) -> float:
+ """返回两个 tight bbox 的水平间隙。"""
+ return max(0.0, first[0] - second[2], second[0] - first[2])
+
+
+def _token_split_position(
+ chars: list[dict[str, Any]],
+ token: list[int],
+ roles: list[ScriptRole],
+ tight_bboxes: dict[int, BBox],
+ origins: dict[int, tuple[float, float]],
+) -> int | None:
+ """用最左 origin 簇和显式连接符确定 base 与索引的分界。"""
+ alnum_positions = [index for index in token if _is_math_identifier_char(_script_char_text(chars[index]))]
+ if len(alnum_positions) < 2:
+ return None
+ first = alnum_positions[0]
+ first_origin = _token_origin(chars[first], origins)
+ first_height = _token_tight_height(chars[first], tight_bboxes)
+ origin_tolerance = max(0.35, 0.06 * first_height)
+ leading_connectors = [
+ index for index in token if index < first and _script_char_text(chars[index]) in _PDF_SCRIPT_TOKEN_CONNECTORS
+ ]
+ if leading_connectors:
+ return alnum_positions[1]
+ for position in alnum_positions[1:]:
+ if any(_script_char_text(chars[index]) in _PDF_SCRIPT_TOKEN_CONNECTORS for index in range(first + 1, position)):
+ return position
+ origin = _token_origin(chars[position], origins)
+ if first_origin is not None and origin is not None and abs(origin - first_origin) > origin_tolerance:
+ return position
+ scripted_positions = [position for position in alnum_positions[1:] if roles[position] != "body"]
+ if roles[first] == "body" and scripted_positions:
+ return scripted_positions[0]
+ return None
+
+
+def _script_geometry_is_aligned(
+ chars: list[dict[str, Any]],
+ first: int,
+ second: int,
+ tight_bboxes: dict[int, BBox],
+ origins: dict[int, tuple[float, float]],
+) -> bool:
+ """判断两个字符是否处在同一 displaced baseline 上。"""
+ first_origin = _token_origin(chars[first], origins)
+ second_origin = _token_origin(chars[second], origins)
+ first_height = _token_tight_height(chars[first], tight_bboxes)
+ second_height = _token_tight_height(chars[second], tight_bboxes)
+ first_idx = chars[first].get("char_idx")
+ second_idx = chars[second].get("char_idx")
+ first_bbox = tight_bboxes.get(first_idx) if isinstance(first_idx, int) else None
+ second_bbox = tight_bboxes.get(second_idx) if isinstance(second_idx, int) else None
+ if first_origin is None or second_origin is None or first_bbox is None or second_bbox is None:
+ return False
+ scale = max(first_height, second_height, 1.0)
+ first_center = (first_bbox[1] + first_bbox[3]) / 2
+ second_center = (second_bbox[1] + second_bbox[3]) / 2
+ return abs(first_origin - second_origin) <= max(0.35, 0.06 * scale) and abs(first_center - second_center) <= max(
+ 0.75,
+ 0.3 * scale,
+ )
+
+
+def _nearest_nonspace_index(
+ chars: list[dict[str, Any]],
+ start: int,
+ step: Literal[-1, 1],
+) -> int | None:
+ """从指定位置向前或向后查找最近的非空白字符。"""
+ index = start + step
+ while 0 <= index < len(chars):
+ if not _script_char_text(chars[index]).isspace():
+ return index
+ index += step
+ return None
+
+
+def _close_spaced_script_operators(
+ chars: list[dict[str, Any]],
+ roles: list[ScriptRole],
+ tight_bboxes: dict[int, BBox],
+ origins: dict[int, tuple[float, float]],
+) -> None:
+ """跨少量 PDF 空格闭合同基线的 `1 - x` 一类角标 run。"""
+ for seed, role in enumerate(list(roles)):
+ if role == "body" or not _is_math_identifier_char(_script_char_text(chars[seed])):
+ continue
+ operator_index = _nearest_nonspace_index(chars, seed, 1)
+ if operator_index is None or operator_index - seed > 3:
+ continue
+ if _script_char_text(chars[operator_index]) not in _PDF_SCRIPT_SPACED_OPERATORS:
+ continue
+ target = _nearest_nonspace_index(chars, operator_index, 1)
+ if target is None or target - operator_index > 3:
+ continue
+ if not _is_math_identifier_char(_script_char_text(chars[target])):
+ continue
+ if not _script_geometry_is_aligned(chars, seed, operator_index, tight_bboxes, origins):
+ continue
+ if not _script_geometry_is_aligned(chars, seed, target, tight_bboxes, origins):
+ continue
+ roles[operator_index] = role
+ roles[target] = role
+
+
+def _protected_subscript_indices(
+ chars: list[dict[str, Any]],
+ roles: list[ScriptRole],
+ tokens: list[list[int]],
+ tight_bboxes: dict[int, BBox],
+ origins: dict[int, tuple[float, float]],
+) -> set[int]:
+ """找出拥有内部 base 或与其同基线连通的下标字符。"""
+ protected: set[int] = set()
+ for token in tokens:
+ for position, index in enumerate(token):
+ if roles[index] != "sub" or not _is_math_identifier_char(_script_char_text(chars[index])):
+ continue
+ if any(
+ earlier < index and roles[earlier] == "body" and _is_math_identifier_char(_script_char_text(chars[earlier]))
+ for earlier in token[:position]
+ ) or _has_adjacent_math_base(chars, index, roles, tight_bboxes, origins):
+ protected.add(index)
+ changed = True
+ while changed:
+ changed = False
+ for index, role in enumerate(roles):
+ if role != "sub" or index in protected or not _is_math_identifier_char(_script_char_text(chars[index])):
+ continue
+ for seed in tuple(protected):
+ start, end = sorted((seed, index))
+ if end - start > 5 or not _script_geometry_is_aligned(chars, seed, index, tight_bboxes, origins):
+ continue
+ if all(
+ _script_char_text(chars[bridge]).isspace()
+ or _script_char_text(chars[bridge]) in _PDF_SCRIPT_TOKEN_CONNECTORS
+ or _script_char_text(chars[bridge]) in _PDF_SCRIPT_SIGN_CHARS
+ or _script_char_text(chars[bridge]) == "."
+ for bridge in range(start + 1, end)
+ ):
+ protected.add(index)
+ changed = True
+ break
+ return protected
+
+
+def _refine_math_script_tokens(
+ chars: list[dict[str, Any]],
+ roles: list[ScriptRole],
+ tight_bboxes: dict[int, BBox],
+ origins: dict[int, tuple[float, float]],
+ *,
+ formula_region: bool,
+) -> list[ScriptRole]:
+ """以最左稳定簇保护 base,并对弱单字符和复杂未分段 token 保守拒识。"""
+ refined = list(roles)
+ citation_indices = _citation_script_indices(chars, refined)
+ complex_unsegmented_token = False
+ tokens = _iter_math_script_tokens(chars)
+ token_alnum_positions = {
+ tuple(token): [index for index in token if _is_math_identifier_char(_script_char_text(chars[index]))]
+ for token in tokens
+ }
+ token_splits = {
+ tuple(token): _token_split_position(
+ chars,
+ token,
+ refined,
+ tight_bboxes,
+ origins,
+ )
+ for token in tokens
+ }
+ token_families: dict[str, list[tuple[int, ...]]] = {}
+ for token in tokens:
+ key = tuple(token)
+ alnum_positions = token_alnum_positions[key]
+ if len(alnum_positions) >= 2:
+ token_families.setdefault(_script_char_text(chars[alnum_positions[0]]), []).append(key)
+ trusted_family_bases = {
+ base
+ for base, members in token_families.items()
+ if len(members) >= 3
+ or any(token_splits[member] is not None for member in members)
+ or any(any(_script_char_text(chars[index]) in _PDF_SCRIPT_TOKEN_CONNECTORS for index in member) for member in members)
+ }
+ for token in tokens:
+ if any(index in citation_indices for index in token):
+ continue
+ token_key = tuple(token)
+ alnum_positions = token_alnum_positions[token_key]
+ if not alnum_positions or not any(refined[index] != "body" for index in token):
+ continue
+ token_roles = {refined[index] for index in token if refined[index] != "body"}
+ if token_roles == {"sup", "sub"}:
+ complex_unsegmented_token = True
+ if len(alnum_positions) == 1:
+ continue
+ first_position = alnum_positions[0]
+ suffix_positions = alnum_positions[1:]
+ if (
+ refined[first_position] == "sup"
+ and all(refined[index] == "body" for index in suffix_positions)
+ and len(suffix_positions) >= 2
+ and all(_script_char_text(chars[index]).isalpha() for index in suffix_positions)
+ ):
+ continue
+ split_position = token_splits[token_key]
+ if split_position is None and _script_char_text(chars[alnum_positions[0]]) in trusted_family_bases:
+ split_position = alnum_positions[1]
+ if split_position is None:
+ if all(refined[index] != "body" for index in alnum_positions):
+ for index in token:
+ refined[index] = "body"
+ continue
+ base_positions = [index for index in alnum_positions if index < split_position]
+ base_origins = [origin for index in base_positions if (origin := _token_origin(chars[index], origins)) is not None]
+ base_heights = [_token_tight_height(chars[index], tight_bboxes) for index in base_positions]
+ base_origin = statistics.median(base_origins) if base_origins else None
+ base_height = statistics.median([height for height in base_heights if height > 0]) if any(base_heights) else 0.0
+ for index in token:
+ if index < split_position or _script_char_text(chars[index]) in _PDF_SCRIPT_TOKEN_CONNECTORS:
+ refined[index] = "body"
+ continue
+ text = _script_char_text(chars[index])
+ if not _is_math_identifier_char(text) or refined[index] != "body":
+ continue
+ origin = _token_origin(chars[index], origins)
+ if base_origin is None or origin is None:
+ continue
+ shift = origin - base_origin
+ if abs(shift) >= max(0.35, 0.08 * base_height):
+ refined[index] = "sub" if shift > 0 else "sup"
+ _close_spaced_script_operators(
+ chars,
+ refined,
+ tight_bboxes,
+ origins,
+ )
+ if complex_unsegmented_token and not formula_region:
+ for index in range(len(refined)):
+ if index not in citation_indices:
+ refined[index] = "body"
+ scripted_alnum = [
+ index for index, role in enumerate(refined) if role != "body" and _script_char_text(chars[index]).isalnum()
+ ]
+ if not formula_region and len(scripted_alnum) >= 2 and any(_script_char_text(char) in {"∑", "∫"} for char in chars):
+ for index in range(len(refined)):
+ if index not in citation_indices:
+ refined[index] = "body"
+ has_compact_multiply = any(
+ _script_char_text(char) == "×"
+ and 0 < index < len(chars) - 1
+ and not _script_char_text(chars[index - 1]).isspace()
+ and not _script_char_text(chars[index + 1]).isspace()
+ for index, char in enumerate(chars)
+ )
+ if not formula_region and len(scripted_alnum) >= 2 and has_compact_multiply:
+ for index in range(len(refined)):
+ if index not in citation_indices:
+ refined[index] = "body"
+ if not formula_region:
+ for operator_index, char in enumerate(chars):
+ operator = _script_char_text(char)
+ nearby = [candidate for candidate in scripted_alnum if abs(candidate - operator_index) <= 5]
+ if (
+ operator in {"/", "⁄"}
+ and any(candidate < operator_index for candidate in nearby)
+ and any(candidate > operator_index for candidate in nearby)
+ ):
+ for candidate in nearby:
+ if candidate not in citation_indices:
+ refined[candidate] = "body"
+ protected_subscripts = _protected_subscript_indices(
+ chars,
+ refined,
+ tokens,
+ tight_bboxes,
+ origins,
+ )
+ for index, role in enumerate(list(refined)):
+ if (
+ role == "sub"
+ and index not in citation_indices
+ and index not in protected_subscripts
+ and _is_math_identifier_char(_script_char_text(chars[index]))
+ ):
+ refined[index] = "body"
+ for index, role in enumerate(list(refined)):
+ if role == "body" or index in citation_indices:
+ continue
+ text = _script_char_text(chars[index])
+ if text.isalnum() or text in _PDF_SCRIPT_AUTHOR_MARKS:
+ continue
+ if text in {",", ","} and all(
+ 0 <= neighbor < len(refined)
+ and refined[neighbor] == role
+ and (_script_char_text(chars[neighbor]).isalnum() or _script_char_text(chars[neighbor]) in _PDF_SCRIPT_AUTHOR_MARKS)
+ for neighbor in (index - 1, index + 1)
+ ):
+ continue
+ if text == "." and all(
+ 0 <= neighbor < len(refined) and refined[neighbor] == role and _script_char_text(chars[neighbor]).isdigit()
+ for neighbor in (index - 1, index + 1)
+ ):
+ continue
+ if text in _PDF_SCRIPT_SIGN_CHARS:
+ sign_neighbors = [
+ neighbor
+ for step in (-1, 1)
+ if (neighbor := _nearest_nonspace_index(chars, index, step)) is not None
+ and abs(neighbor - index) <= 3
+ and refined[neighbor] == role
+ ]
+ if sign_neighbors and any(_script_char_text(chars[neighbor]).isdigit() for neighbor in sign_neighbors):
+ continue
+ if text in _PDF_SCRIPT_TRAILING_MARKS:
+ previous = _nearest_nonspace_index(chars, index, -1)
+ body_prefix = previous - 1 if previous is not None else -1
+ if (
+ role == "sup"
+ and previous is not None
+ and index - previous == 1
+ and body_prefix >= 0
+ and refined[body_prefix] == "body"
+ and _script_char_text(chars[body_prefix]).isalpha()
+ and refined[previous] == role
+ and roles[index] == role
+ and _script_char_text(chars[previous]).isalpha()
+ and _script_geometry_is_aligned(chars, previous, index, tight_bboxes, origins)
+ ):
+ continue
+ refined[index] = "body"
+ return refined
+
+
+def _bbox_axis_overlap(first: BBox, second: BBox, *, axis: Literal["x", "y"]) -> float:
+ """返回两个 bbox 在指定轴上的绝对重叠长度。"""
+ start, end = (0, 2) if axis == "x" else (1, 3)
+ return max(0.0, min(first[end], second[end]) - max(first[start], second[start]))
+
+
+def _fraction_member_indices(
+ page_size: tuple[float, float],
+ all_chars: list[dict[str, Any]],
+ tight_bboxes: dict[int, BBox],
+ drawing_lines: Sequence[Any],
+ angle: int,
+) -> set[int]:
+ """按页面方向一次识别分数线两侧的上下叠字,供复杂分式整块拒识。"""
+ if not all_chars or not drawing_lines:
+ return set()
+ local_chars: list[tuple[int, str, BBox]] = []
+ local_heights = []
+ for char in all_chars:
+ char_idx = char.get("char_idx")
+ text = _script_char_text(char)
+ bbox = tight_bboxes.get(char_idx) if isinstance(char_idx, int) else None
+ if not isinstance(char_idx, int) or bbox is None or not text.isprintable() or text.isspace():
+ continue
+ local_bbox = _rotate_bbox_to_upright(bbox, page_size, angle)
+ local_chars.append((char_idx, text, local_bbox))
+ local_heights.append(local_bbox[3] - local_bbox[1])
+ scale = statistics.median([height for height in local_heights if height > 0]) if local_heights else 8.0
+ members: set[int] = set()
+ for drawing in drawing_lines:
+ raw_bbox = _coerce_bbox(getattr(drawing, "bbox", drawing))
+ if raw_bbox is None:
+ continue
+ local_rule = _rotate_bbox_to_upright(raw_bbox, page_size, angle)
+ width = local_rule[2] - local_rule[0]
+ height = local_rule[3] - local_rule[1]
+ if width < max(2.0, 0.45 * scale) or width > 12.0 * scale or height > max(1.25, 0.25 * scale):
+ continue
+ rule_y = (local_rule[1] + local_rule[3]) / 2
+ aligned = [
+ (char_idx, bbox)
+ for char_idx, text, bbox in local_chars
+ if text.isalnum()
+ and abs((bbox[1] + bbox[3]) / 2 - rule_y) <= 2.25 * scale
+ and (
+ _bbox_axis_overlap(bbox, local_rule, axis="x") > 0
+ or local_rule[0] - 0.25 * scale <= (bbox[0] + bbox[2]) / 2 <= local_rule[2] + 0.25 * scale
+ )
+ ]
+ above = [
+ (char_idx, bbox)
+ for char_idx, bbox in aligned
+ if bbox[3] <= rule_y + 0.2 * scale and rule_y - bbox[3] <= 1.75 * scale
+ ]
+ below = [
+ (char_idx, bbox)
+ for char_idx, bbox in aligned
+ if bbox[1] >= rule_y - 0.2 * scale and bbox[1] - rule_y <= 1.75 * scale
+ ]
+ if above and below:
+ members.update(char_idx for char_idx, _bbox in above)
+ members.update(char_idx for char_idx, _bbox in below)
+ return members
+
+
+def _classify_script_runs(
+ chars: list[dict[str, Any]],
+ local_tight_bboxes: dict[int, BBox],
+ local_origins: dict[int, tuple[float, float]],
+ memberships: list[int | None],
+) -> tuple[list[str], list[int], list[bool]]:
+ """按公式区域边界分段分类,并要求公式段内部存在稳定 body。"""
+ roles: list[ScriptRole] = ["body"] * len(chars)
+ body_counts = [0] * len(chars)
+ formula_flags = [False] * len(chars)
+ start = 0
+ while start < len(chars):
+ membership = memberships[start]
+ end = start + 1
+ while end < len(chars) and memberships[end] == membership:
+ end += 1
+ run_chars = chars[start:end]
+ run_indices = {int(char["char_idx"]) for char in run_chars if isinstance(char.get("char_idx"), int)}
+ run_roles = classify_char_script_roles(
+ run_chars,
+ tight_bboxes={index: local_tight_bboxes[index] for index in run_indices if index in local_tight_bboxes},
+ origins={index: local_origins[index] for index in run_indices if index in local_origins},
+ )
+ run_roles = _refine_math_script_tokens(
+ run_chars,
+ run_roles,
+ local_tight_bboxes,
+ local_origins,
+ formula_region=membership is not None,
+ )
+ visible = [
+ index
+ for index, char in enumerate(run_chars)
+ if str(char.get("char", "")).isprintable() and not str(char.get("char", "")).isspace()
+ ]
+ body_count = sum(run_roles[index] == "body" and str(run_chars[index].get("char", "")).isalnum() for index in visible)
+ marked_count = sum(run_roles[index] != "body" for index in visible)
+ body_tight_heights = [
+ local_tight_bboxes[int(run_chars[index]["char_idx"])][3] - local_tight_bboxes[int(run_chars[index]["char_idx"])][1]
+ for index in visible
+ if run_roles[index] == "body"
+ and isinstance(run_chars[index].get("char_idx"), int)
+ and int(run_chars[index]["char_idx"]) in local_tight_bboxes
+ ]
+ script_tight_heights = [
+ local_tight_bboxes[int(run_chars[index]["char_idx"])][3] - local_tight_bboxes[int(run_chars[index]["char_idx"])][1]
+ for index in visible
+ if run_roles[index] != "body"
+ and isinstance(run_chars[index].get("char_idx"), int)
+ and int(run_chars[index]["char_idx"]) in local_tight_bboxes
+ ]
+ stable_formula_body = (
+ body_count > 0
+ and bool(body_tight_heights)
+ and (not script_tight_heights or max(body_tight_heights) >= 1.1 * max(script_tight_heights))
+ )
+ if membership is not None and (not stable_formula_body or marked_count >= len(visible)):
+ run_roles = ["body"] * len(run_chars)
+ for offset, role in enumerate(run_roles, start=start):
+ roles[offset] = role
+ body_counts[offset] = body_count
+ formula_flags[offset] = membership is not None
+ start = end
+ return roles, body_counts, formula_flags
+
+
+def _script_line_payload(
+ line: Any,
+ page_size: tuple[float, float],
+ tight_bboxes: dict[int, BBox],
+ origins: dict[int, tuple[float, float]],
+ fraction_members: set[int],
+) -> PDFTextScriptLine | None:
+ """把 Flash 行转换为公式分段后的紧凑上下标 sidecar。"""
+ chars = _ordered_line_chars(line)
+ if not chars:
+ return None
+ angle = int(getattr(line, "angle", 0) or 0) % 360
+ local_chars: list[dict[str, Any]] = []
+ local_tight_bboxes: dict[int, BBox] = {}
+ local_origins: dict[int, tuple[float, float]] = {}
+ for char in chars:
+ local_char = dict(char)
+ bbox = _coerce_bbox(char.get("bbox"))
+ if bbox is not None:
+ local_char["bbox"] = _rotate_bbox_to_upright(bbox, page_size, angle)
+ local_chars.append(local_char)
+ char_idx = char.get("char_idx")
+ if not isinstance(char_idx, int):
+ continue
+ tight_bbox = tight_bboxes.get(char_idx)
+ if tight_bbox is not None:
+ local_tight_bboxes[char_idx] = _rotate_bbox_to_upright(
+ tight_bbox,
+ page_size,
+ angle,
+ )
+ origin = origins.get(char_idx)
+ if origin is not None:
+ local_origins[char_idx] = _rotate_origin_to_upright(
+ origin,
+ page_size,
+ angle,
+ )
+ regions = [bbox for value in getattr(line, "inline_math_regions", []) if (bbox := _coerce_bbox(value)) is not None]
+ memberships = _script_region_memberships(chars, tight_bboxes, regions)
+ roles, body_counts, formula_flags = _classify_script_runs(
+ local_chars,
+ local_tight_bboxes,
+ local_origins,
+ memberships,
+ )
+ if bool(getattr(line, "compact_formula_cluster", False)) or (
+ bool(getattr(line, "restored_inline_cluster", False)) and bool(regions)
+ ):
+ roles = ["body"] * len(roles)
+ for index, char in enumerate(chars):
+ char_idx = char.get("char_idx")
+ if isinstance(char_idx, int) and char_idx in fraction_members:
+ roles[index] = "body"
+ compact_parts: list[str] = []
+ compact_roles: list[str] = []
+ compact_bboxes: list[BBox | None] = []
+ compact_body_counts: list[int] = []
+ compact_formula_flags: list[bool] = []
+ for index, char in enumerate(chars):
+ fragment = _normalize_match_fragment(char.get("char"))
+ if not fragment:
+ continue
+ compact_parts.append(fragment)
+ char_idx = char.get("char_idx")
+ page_tight_bbox = tight_bboxes.get(char_idx) if isinstance(char_idx, int) else None
+ compact_roles.extend([roles[index]] * len(fragment))
+ compact_bboxes.extend([page_tight_bbox] * len(fragment))
+ compact_body_counts.extend([body_counts[index]] * len(fragment))
+ compact_formula_flags.extend([formula_flags[index]] * len(fragment))
+ text = "".join(compact_parts)
+ if not text:
+ return None
+ ranges: list[PDFTextScriptRange] = []
+ start = 0
+ while start < len(compact_roles):
+ role = compact_roles[start]
+ end = start + 1
+ while end < len(compact_roles) and compact_roles[end] == role:
+ end += 1
+ if role in {"sup", "sub"}:
+ range_bboxes = [bbox for bbox in compact_bboxes[start:end] if bbox is not None]
+ if range_bboxes:
+ page_bbox = (
+ min(bbox[0] for bbox in range_bboxes),
+ min(bbox[1] for bbox in range_bboxes),
+ max(bbox[2] for bbox in range_bboxes),
+ max(bbox[3] for bbox in range_bboxes),
+ )
+ ranges.append(
+ PDFTextScriptRange(
+ start=start,
+ end=end,
+ style="superscript" if role == "sup" else "subscript",
+ bbox=page_bbox,
+ stable_body_count=max(compact_body_counts[start:end], default=0),
+ formula_region=any(compact_formula_flags[start:end]),
+ )
+ )
+ start = end
+ return PDFTextScriptLine(
+ bbox=getattr(line, "bbox"),
+ text=text,
+ script_ranges=tuple(ranges),
+ source_index=int(getattr(line, "source_index", 0) or 0),
+ angle=angle,
+ )
+
+
+def detect_pdf_text_script_lines(
+ lines: list[Any],
+ page_size: tuple[float, float],
+ tight_bboxes: dict[int, BBox],
+ origins: dict[int, tuple[float, float]],
+ *,
+ all_chars: list[dict[str, Any]] | None = None,
+ drawing_lines: Sequence[Any] | None = None,
+) -> list[PDFTextScriptLine]:
+ """检测 Flash 剩余自然文本行中的上下标候选。"""
+ resolved_chars = all_chars or []
+ resolved_drawings = drawing_lines or []
+ fraction_members_by_angle = {
+ angle: _fraction_member_indices(
+ page_size,
+ resolved_chars,
+ tight_bboxes,
+ resolved_drawings,
+ angle,
+ )
+ for angle in {int(getattr(line, "angle", 0) or 0) % 360 for line in lines}
+ }
+ return [
+ payload
+ for line in lines
+ if (
+ payload := _script_line_payload(
+ line,
+ page_size,
+ tight_bboxes,
+ origins,
+ fraction_members_by_angle[int(getattr(line, "angle", 0) or 0) % 360],
+ )
+ )
+ is not None
+ ]
+
+
def _build_line_geometry_grids(
candidates: Sequence[_LineCandidate],
) -> tuple[
@@ -1806,7 +2634,141 @@ def apply_pdf_text_styles(
continue
intervals = _raw_style_intervals(content, projected, style_ranges)
if intervals:
- block[_PDF_STYLE_INTERVALS_KEY] = intervals
+ existing = block.get(_PDF_STYLE_INTERVALS_KEY, [])
+ block[_PDF_STYLE_INTERVALS_KEY] = _merge_raw_style_intervals(
+ content,
+ [
+ *(interval for interval in existing if isinstance(interval, _RawStyleInterval)),
+ *intervals,
+ ],
+ )
+
+
+def _script_range_hits_late_formula_region(
+ script_range: PDFTextScriptRange,
+ regions: list[BBox],
+) -> bool:
+ """判断非公式候选是否落入后续文本块恢复出的行内数学区域。"""
+ if script_range.formula_region:
+ return False
+ center_x = (script_range.bbox[0] + script_range.bbox[2]) / 2
+ center_y = (script_range.bbox[1] + script_range.bbox[3]) / 2
+ return any(region[0] <= center_x <= region[2] and region[1] <= center_y <= region[3] for region in regions)
+
+
+def _record_materialized_script_ranges(
+ content: str,
+ projected: Sequence[_ProjectedChar],
+ combined_ranges: Sequence[PDFTextStyleRange],
+ block_index: int,
+ line: PDFTextScriptLine,
+ script_ranges: Sequence[PDFTextScriptRange],
+ output: list[dict[str, Any]],
+) -> None:
+ """记录真正通过文本投影的私有上下标区间,供审阅产物精确回溯。"""
+ for script_range in script_ranges:
+ evidence_line = PDFTextStyleLine(
+ bbox=line.bbox,
+ text=line.text,
+ style_ranges=(
+ PDFTextStyleRange(
+ script_range.start,
+ script_range.end,
+ (script_range.style,),
+ ),
+ ),
+ source_index=line.source_index,
+ )
+ matched = _match_style_ranges(projected, [evidence_line])
+ if len(matched) != 1:
+ continue
+ mapped = matched[0]
+ if not any(
+ mapped.start >= combined.start and mapped.end <= combined.end and script_range.style in combined.styles
+ for combined in combined_ranges
+ ):
+ continue
+ raw_intervals = _raw_style_intervals(content, projected, [mapped])
+ if len(raw_intervals) != 1:
+ continue
+ raw_interval = raw_intervals[0]
+ output.append(
+ {
+ "block_index": block_index,
+ "raw_start": raw_interval.start,
+ "raw_end": raw_interval.end,
+ "source_index": line.source_index,
+ "range_start": script_range.start,
+ "range_end": script_range.end,
+ "role": script_range.style,
+ "text": line.text[script_range.start : script_range.end],
+ "bbox": script_range.bbox,
+ "angle": line.angle,
+ "formula_region": script_range.formula_region,
+ "stable_body_count": script_range.stable_body_count,
+ }
+ )
+
+
+def apply_pdf_text_scripts(
+ blocks: list[dict[str, Any]],
+ lines: list[PDFTextScriptLine],
+ page_size: tuple[float, float],
+ *,
+ materialized_diagnostics: list[dict[str, Any]] | None = None,
+) -> None:
+ """把 Flash 上下标 sidecar 投影到最终自然语言 block,并清理公式私有区域。"""
+ assignments = _assign_lines_to_blocks(blocks, lines, page_size)
+ for block_index, block_lines in assignments.items():
+ block = blocks[block_index]
+ regions = [
+ region
+ for value in block.get("_inline_math_regions", [])
+ if (region := _block_bbox_to_page_bbox(value, page_size)) is not None
+ ]
+ projected_lines = []
+ eligible_ranges: dict[int, tuple[PDFTextScriptRange, ...]] = {}
+ for line in block_lines:
+ retained = tuple(
+ script_range
+ for script_range in line.script_ranges
+ if not _script_range_hits_late_formula_region(script_range, regions)
+ )
+ eligible_ranges[id(line)] = retained
+ ranges = tuple(
+ PDFTextStyleRange(
+ script_range.start,
+ script_range.end,
+ (script_range.style,),
+ )
+ for script_range in retained
+ )
+ projected_lines.append(
+ PDFTextStyleLine(
+ bbox=line.bbox,
+ text=line.text,
+ style_ranges=ranges,
+ source_index=line.source_index,
+ )
+ )
+ projected_lines = _filter_line_styles_for_block(projected_lines, block.get("type"))
+ content = block.get("content")
+ if materialized_diagnostics is not None and isinstance(content, str):
+ projected = _project_content_chars(content)
+ combined_ranges = _match_style_ranges(projected, projected_lines)
+ for line in block_lines:
+ _record_materialized_script_ranges(
+ content,
+ projected,
+ combined_ranges,
+ block_index,
+ line,
+ eligible_ranges.get(id(line), ()),
+ materialized_diagnostics,
+ )
+ apply_pdf_text_styles([block], projected_lines, page_size)
+ for block in blocks:
+ block.pop("_inline_math_regions", None)
def _parse_native_script_markup(content: str) -> _NativeScriptMarkup | None:
@@ -1918,12 +2880,16 @@ __all__ = [
"PDF_FONT_ITALIC_FLAG",
"PDFTextLinkLine",
"PDFTextLinkRange",
+ "PDFTextScriptLine",
+ "PDFTextScriptRange",
"PDFTextStyle",
"PDFTextStyleLine",
"PDFTextStyleRange",
"apply_pdf_text_links",
+ "apply_pdf_text_scripts",
"apply_pdf_text_styles",
"detect_pdf_text_link_lines",
+ "detect_pdf_text_script_lines",
"detect_pdf_text_style_lines",
"materialize_pdf_inline_spans",
]
diff --git a/scripts/render_flash_script_review.py b/scripts/render_flash_script_review.py
new file mode 100644
index 00000000..7a990752
--- /dev/null
+++ b/scripts/render_flash_script_review.py
@@ -0,0 +1,521 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+import os
+import re
+import shutil
+import tempfile
+import unicodedata
+from collections import Counter, defaultdict, deque
+from pathlib import Path
+from typing import Any
+
+from PIL import Image, ImageDraw, ImageFont
+
+from mineru.model.flash.pdf.document import PDFDocument
+from mineru.model.flash.pdf.pipeline import _analyze_native_document
+from mineru.model.flash.pdf.text_styles import PDFTextScriptLine
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+OUTPUT_DIR = PROJECT_ROOT / "output/pdf/flash_script_review"
+PDF_PATHS = sorted((PROJECT_ROOT / "demo/pdfs").glob("*.pdf")) + [
+ Path("/Users/myhloli/pdf/NPU_开发环境部署_参考指南.pdf"),
+]
+RENDER_DPI = 200
+CONTEXT_CHARS = 40
+CONTACT_COLUMNS = 3
+CONTACT_ROWS = 5
+
+
+def _sha256(path: Path) -> str:
+ """计算源 PDF 摘要,供候选 ID 和审阅追踪使用。"""
+ digest = hashlib.sha256()
+ with path.open("rb") as input_file:
+ for chunk in iter(lambda: input_file.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _normalized_text(value: str) -> str:
+ """生成适合 sidecar 与最终 TextSpan 对齐的稳定文本键。"""
+ normalized = unicodedata.normalize("NFKC", value)
+ normalized = "".join(char for char in normalized if char.isprintable())
+ return re.sub(r"\s+", "", normalized)
+
+
+def _safe_stem(path: Path) -> str:
+ """生成适合作为产物目录的稳定文件名。"""
+ value = re.sub(r"[^\w.-]+", "_", path.stem, flags=re.UNICODE).strip("_.")
+ return value[:64] or "document"
+
+
+def _load_font(size: int) -> ImageFont.ImageFont:
+ """优先加载支持中英文标签的系统字体。"""
+ for font_path in (
+ Path("/System/Library/Fonts/STHeiti Medium.ttc"),
+ Path("/System/Library/Fonts/Supplemental/Arial.ttf"),
+ ):
+ if font_path.exists():
+ return ImageFont.truetype(str(font_path), size=size)
+ return ImageFont.load_default(size=size)
+
+
+def _page_bbox_from_normalized(
+ bbox: Any,
+ page_size: tuple[float, float],
+) -> tuple[float, float, float, float] | None:
+ """把最终 Flash block bbox 转回页面 point。"""
+ if not isinstance(bbox, list) or len(bbox) != 4:
+ return None
+ try:
+ values = tuple(float(value) for value in bbox)
+ except (TypeError, ValueError):
+ return None
+ if values[2] <= values[0] or values[3] <= values[1]:
+ return None
+ return (
+ values[0] * page_size[0],
+ values[1] * page_size[1],
+ values[2] * page_size[0],
+ values[3] * page_size[1],
+ )
+
+
+def _script_candidates(
+ diagnostic: dict[str, Any],
+) -> tuple[dict[tuple[int | None, str, str], deque[dict[str, Any]]], list[dict[str, Any]]]:
+ """把检测及最终投影 sidecar 转成按 block、角色和文本消费的候选队列。"""
+ detected = []
+ detected_by_key: dict[tuple[int, int, int, str, str], deque[dict[str, Any]]] = defaultdict(deque)
+ lines = sorted(
+ diagnostic["lines"],
+ key=lambda item: (item["source_index"], item["bbox"][1], item["bbox"][0]),
+ )
+ line_position = {item["source_index"]: index for index, item in enumerate(lines)}
+ for script_line in diagnostic["script_lines"]:
+ if not isinstance(script_line, PDFTextScriptLine):
+ continue
+ position = line_position.get(script_line.source_index)
+ current = lines[position]["text"] if position is not None else script_line.text
+ previous = lines[position - 1]["text"] if position is not None and position > 0 else ""
+ following = lines[position + 1]["text"] if position is not None and position + 1 < len(lines) else ""
+ for script_range in script_line.script_ranges:
+ text = script_line.text[script_range.start : script_range.end]
+ candidate = {
+ "source_index": script_line.source_index,
+ "range_start": script_range.start,
+ "range_end": script_range.end,
+ "role": script_range.style,
+ "text": text,
+ "bbox": list(script_range.bbox),
+ "angle": script_line.angle,
+ "formula_region": script_range.formula_region,
+ "stable_body_count": script_range.stable_body_count,
+ "previous_line": previous,
+ "current_line": current,
+ "next_line": following,
+ }
+ detected.append(candidate)
+ detected_by_key[
+ (
+ script_line.source_index,
+ script_range.start,
+ script_range.end,
+ script_range.style,
+ text,
+ )
+ ].append(candidate)
+
+ queues: dict[tuple[int | None, str, str], deque[dict[str, Any]]] = defaultdict(deque)
+ materialized = diagnostic.get("materialized_ranges")
+ if isinstance(materialized, list):
+ candidates = []
+ for mapped in sorted(
+ materialized,
+ key=lambda item: (
+ int(item.get("block_index", -1)),
+ int(item.get("raw_start", -1)),
+ int(item.get("source_index", -1)),
+ int(item.get("range_start", -1)),
+ ),
+ ):
+ identity = (
+ int(mapped["source_index"]),
+ int(mapped["range_start"]),
+ int(mapped["range_end"]),
+ str(mapped["role"]),
+ str(mapped["text"]),
+ )
+ candidate = dict(detected_by_key[identity].popleft()) if detected_by_key[identity] else dict(mapped)
+ candidate.update(mapped)
+ candidate["bbox"] = list(candidate["bbox"])
+ candidates.append(candidate)
+ queues[
+ (
+ int(mapped["block_index"]),
+ str(mapped["role"]),
+ _normalized_text(str(mapped["text"])),
+ )
+ ].append(candidate)
+ return queues, candidates
+
+ for candidate in detected:
+ queues[(None, str(candidate["role"]), _normalized_text(str(candidate["text"])))].append(candidate)
+ return queues, detected
+
+
+def _final_script_runs(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """收集最终真正物化的 Flash 上下标 TextSpan。"""
+ runs = []
+ for block_index, block in enumerate(blocks):
+ block_type = str(block.get("type") or "")
+ block_bbox = _page_bbox_from_normalized(block.get("bbox"), page_size)
+
+ def walk(value: Any) -> None:
+ """递归遍历 block 的 InlineSpan。"""
+ if isinstance(value, dict):
+ content = value.get("content")
+ styles = value.get("styles")
+ if value.get("type") == "text" and isinstance(content, str) and isinstance(styles, list):
+ for role in ("superscript", "subscript"):
+ if role in styles and _normalized_text(content):
+ runs.append(
+ {
+ "block_index": block_index,
+ "block_type": block_type,
+ "block_bbox": list(block_bbox) if block_bbox is not None else None,
+ "role": role,
+ "text": content,
+ }
+ )
+ if isinstance(content, (dict, list)):
+ walk(content)
+ elif isinstance(value, list):
+ for child in value:
+ walk(child)
+
+ walk(block.get("content"))
+ return runs
+
+
+def _candidate_id(
+ source_sha256: str,
+ page_number: int,
+ candidate: dict[str, Any],
+) -> str:
+ """用源文件、页、来源区间和角色构造稳定候选 ID。"""
+ payload = "|".join(
+ (
+ source_sha256,
+ str(page_number),
+ str(candidate.get("source_index", -1)),
+ str(candidate.get("range_start", -1)),
+ str(candidate.get("range_end", -1)),
+ str(candidate["role"]),
+ str(candidate["text"]),
+ )
+ )
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
+
+
+def _clip_context(value: str, styled_text: str) -> str:
+ """围绕样式文本保留约 40 字符上下文。"""
+ compact = re.sub(r"\s+", " ", value).strip()
+ position = compact.find(styled_text)
+ if position < 0:
+ return compact[: 2 * CONTEXT_CHARS + len(styled_text)]
+ start = max(0, position - CONTEXT_CHARS)
+ end = min(len(compact), position + len(styled_text) + CONTEXT_CHARS)
+ return compact[start:end]
+
+
+def _render_crop(
+ page_image: Image.Image,
+ scale: float,
+ bbox: tuple[float, float, float, float],
+ record: dict[str, Any],
+ output_path: Path,
+) -> None:
+ """裁剪上下标周围源页,并用角色颜色标出 tight bbox。"""
+ x0, y0, x1, y1 = bbox
+ line_height = max(1.0, y1 - y0)
+ padding_x = max(96.0, 10.0 * line_height)
+ padding_y = max(18.0, 1.75 * line_height)
+ crop_box = (
+ max(0, round((x0 - padding_x) * scale)),
+ max(0, round((y0 - padding_y) * scale)),
+ min(page_image.width, round((x1 + padding_x) * scale)),
+ min(page_image.height, round((y1 + padding_y) * scale)),
+ )
+ crop = page_image.crop(crop_box).convert("RGB")
+ label_height = 42
+ canvas = Image.new("RGB", (crop.width, crop.height + label_height), "white")
+ canvas.paste(crop, (0, label_height))
+ draw = ImageDraw.Draw(canvas)
+ color = (220, 40, 40) if record["role"] == "superscript" else (30, 90, 220)
+ draw.rectangle(
+ (
+ round(x0 * scale) - crop_box[0],
+ round(y0 * scale) - crop_box[1] + label_height,
+ round(x1 * scale) - crop_box[0],
+ round(y1 * scale) - crop_box[1] + label_height,
+ ),
+ outline=color,
+ width=4,
+ )
+ label = f"{record['id']} p{record['page']} {record['role']} {record['text']}"
+ draw.text((8, 8), label, fill=color, font=_load_font(20))
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ canvas.save(output_path)
+
+
+def _build_contact_sheets(
+ records: list[dict[str, Any]],
+ staging: Path,
+) -> list[str]:
+ """按文档把候选 crop 组合成多张联系表。"""
+ contact_paths = []
+ page_size = (520, 250)
+ per_sheet = CONTACT_COLUMNS * CONTACT_ROWS
+ grouped: dict[str, list[dict[str, Any]]] = defaultdict(list)
+ for record in records:
+ grouped[record["file"]].append(record)
+ for document_name, document_records in sorted(grouped.items()):
+ for sheet_index in range(math.ceil(len(document_records) / per_sheet)):
+ subset = document_records[sheet_index * per_sheet : (sheet_index + 1) * per_sheet]
+ canvas = Image.new(
+ "RGB",
+ (CONTACT_COLUMNS * page_size[0], CONTACT_ROWS * page_size[1]),
+ "white",
+ )
+ for index, record in enumerate(subset):
+ with Image.open(staging / record["crop"]) as source_crop:
+ crop = source_crop.convert("RGB")
+ crop.thumbnail((page_size[0] - 12, page_size[1] - 12))
+ x = (index % CONTACT_COLUMNS) * page_size[0] + 6
+ y = (index // CONTACT_COLUMNS) * page_size[1] + 6
+ canvas.paste(crop, (x, y))
+ relative = Path("contact_sheets") / (f"{_safe_stem(Path(document_name))}_{sheet_index + 1:02d}.png")
+ output = staging / relative
+ output.parent.mkdir(parents=True, exist_ok=True)
+ canvas.save(output)
+ contact_paths.append(relative.as_posix())
+ return contact_paths
+
+
+def _write_review_markdown(records: list[dict[str, Any]], staging: Path) -> Path:
+ """生成按文件和页码分组、带勾选框和 crop 的人工审阅 Markdown。"""
+ lines = [
+ "# Flash 上下标人工审阅",
+ "",
+ f"候选总数:{len(records)}",
+ "",
+ "- 红框:superscript",
+ "- 蓝框:subscript",
+ "",
+ ]
+ grouped: dict[tuple[str, int], list[dict[str, Any]]] = defaultdict(list)
+ for record in records:
+ grouped[(record["file"], record["page"])].append(record)
+ for (file_name, page_number), page_records in sorted(grouped.items()):
+ lines.extend([f"## {file_name} - p{page_number}", ""])
+ for record in page_records:
+ context = _clip_context(record["current_line"], record["text"])
+ lines.extend(
+ [
+ f"- [ ] `{record['id']}` **{record['role']}** `{record['text']}`",
+ f" - block: `{record['block_type']}`; angle: `{record['angle']}`; "
+ f"formula_region: `{record['formula_region']}`; stable_body_count: `{record['stable_body_count']}`",
+ f" - previous: {record['previous_line']}",
+ f" - context: {context}",
+ f" - next: {record['next_line']}",
+ f" - ![{record['id']}]({record['crop']})",
+ "",
+ ]
+ )
+ output = staging / "review.md"
+ output.write_text("\n".join(lines), encoding="utf-8")
+ return output
+
+
+def _promote(staging: Path) -> None:
+ """把已验证 staging 目录原子提升为最终审阅目录。"""
+ OUTPUT_DIR.parent.mkdir(parents=True, exist_ok=True)
+ backup = OUTPUT_DIR.with_name(f"{OUTPUT_DIR.name}.previous")
+ if backup.exists():
+ shutil.rmtree(backup)
+ if OUTPUT_DIR.exists():
+ OUTPUT_DIR.rename(backup)
+ try:
+ os.replace(staging, OUTPUT_DIR)
+ except Exception:
+ if backup.exists() and not OUTPUT_DIR.exists():
+ backup.rename(OUTPUT_DIR)
+ raise
+ if backup.exists():
+ shutil.rmtree(backup)
+
+
+def main() -> None:
+ """扫描全部 Flash PDF,生成可追踪的上下标人工审阅产物。"""
+ OUTPUT_DIR.parent.mkdir(parents=True, exist_ok=True)
+ staging = Path(
+ tempfile.mkdtemp(
+ prefix="flash_script_review_",
+ dir=OUTPUT_DIR.parent,
+ )
+ )
+ records = []
+ documents = []
+ try:
+ for document_index, pdf_path in enumerate(PDF_PATHS, start=1):
+ source_sha256 = _sha256(pdf_path)
+ diagnostics: list[dict[str, Any]] = []
+ print(f"解析 {document_index}/{len(PDF_PATHS)} {pdf_path.name}", flush=True)
+ with PDFDocument(str(pdf_path)) as document:
+ pages = _analyze_native_document(
+ document,
+ script_diagnostics=diagnostics,
+ )
+ page_images: dict[int, tuple[Image.Image, float]] = {}
+ document_count = 0
+ for page_index, blocks in enumerate(pages):
+ diagnostic = diagnostics[page_index]
+ queues, _candidates = _script_candidates(diagnostic)
+ final_runs = _final_script_runs(blocks, diagnostic["page_size"])
+ for final_index, final_run in enumerate(final_runs):
+ key = (
+ final_run["block_index"],
+ final_run["role"],
+ _normalized_text(final_run["text"]),
+ )
+ fallback_key = (
+ None,
+ final_run["role"],
+ _normalized_text(final_run["text"]),
+ )
+ candidate = (
+ queues[key].popleft()
+ if queues[key]
+ else queues[fallback_key].popleft()
+ if queues[fallback_key]
+ else {
+ "source_index": -1,
+ "range_start": final_index,
+ "range_end": final_index + 1,
+ "role": final_run["role"],
+ "text": final_run["text"],
+ "bbox": final_run["block_bbox"],
+ "angle": 0,
+ "formula_region": False,
+ "stable_body_count": 0,
+ "previous_line": "",
+ "current_line": final_run["text"],
+ "next_line": "",
+ }
+ )
+ bbox = candidate.get("bbox") or final_run["block_bbox"]
+ if not isinstance(bbox, list) or len(bbox) != 4:
+ raise AssertionError((pdf_path, page_index, final_run))
+ record_id = _candidate_id(
+ source_sha256,
+ page_index + 1,
+ candidate,
+ )
+ relative_crop = Path("crops") / _safe_stem(pdf_path) / f"{record_id}.png"
+ record = {
+ "id": record_id,
+ "file": pdf_path.name,
+ "source_path": str(pdf_path),
+ "source_sha256": source_sha256,
+ "page": page_index + 1,
+ "block_type": final_run["block_type"],
+ "role": final_run["role"],
+ "text": final_run["text"],
+ "bbox": [float(value) for value in bbox],
+ "angle": int(candidate.get("angle", 0)),
+ "source_index": int(candidate.get("source_index", -1)),
+ "range_start": int(candidate.get("range_start", -1)),
+ "range_end": int(candidate.get("range_end", -1)),
+ "formula_region": bool(candidate.get("formula_region", False)),
+ "stable_body_count": int(candidate.get("stable_body_count", 0)),
+ "previous_line": str(candidate.get("previous_line", "")),
+ "current_line": str(candidate.get("current_line", final_run["text"])),
+ "next_line": str(candidate.get("next_line", "")),
+ "crop": relative_crop.as_posix(),
+ }
+ if page_index not in page_images:
+ rendered = document.render_page(
+ page_index,
+ scale=RENDER_DPI / 72,
+ )
+ page_images[page_index] = (
+ rendered.pil_image,
+ rendered.scale,
+ )
+ image, scale = page_images[page_index]
+ _render_crop(
+ image,
+ scale,
+ tuple(record["bbox"]),
+ record,
+ staging / relative_crop,
+ )
+ records.append(record)
+ document_count += 1
+ documents.append(
+ {
+ "file": pdf_path.name,
+ "source_path": str(pdf_path),
+ "source_sha256": source_sha256,
+ "page_count": document.page_count,
+ "candidate_count": document_count,
+ }
+ )
+ contact_sheets = _build_contact_sheets(records, staging)
+ review_path = _write_review_markdown(records, staging)
+ manifest = {
+ "source_count": len(PDF_PATHS),
+ "page_count": sum(document["page_count"] for document in documents),
+ "candidate_count": len(records),
+ "role_counts": dict(Counter(record["role"] for record in records)),
+ "formula_region_count": sum(record["formula_region"] for record in records),
+ "documents": documents,
+ "contact_sheets": contact_sheets,
+ "records": records,
+ }
+ manifest_path = staging / "manifest.json"
+ manifest_path.write_text(
+ json.dumps(manifest, ensure_ascii=False, indent=2),
+ encoding="utf-8",
+ )
+ crop_count = len(list((staging / "crops").rglob("*.png")))
+ checkbox_count = review_path.read_text(encoding="utf-8").count("- [ ]")
+ if not (
+ len(records) == crop_count == checkbox_count
+ and sum(document["candidate_count"] for document in documents) == len(records)
+ ):
+ raise AssertionError(
+ {
+ "records": len(records),
+ "crops": crop_count,
+ "checkboxes": checkbox_count,
+ }
+ )
+ _promote(staging)
+ print(OUTPUT_DIR / "manifest.json")
+ print(OUTPUT_DIR / "review.md")
+ except Exception:
+ if staging.exists():
+ shutil.rmtree(staging)
+ raise
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/unittest/test_flash_pdf_native_text.py b/tests/unittest/test_flash_pdf_native_text.py
index ada99901..6ad06c85 100644
--- a/tests/unittest/test_flash_pdf_native_text.py
+++ b/tests/unittest/test_flash_pdf_native_text.py
@@ -93,10 +93,7 @@ def test_small_oblique_span_stays_inside_standard_direction_line() -> None:
def test_sheared_horizontal_line_uses_char_baseline_and_splits_far_sidecar() -> None:
"""验证仿斜体粗行可由水平字符基线恢复,并继续拆开远端页码。"""
- chars = [
- _char(value, (10.0 + index * 5.0, 80.0, 14.0 + index * 5.0, 88.0))
- for index, value in enumerate("NOTICE")
- ]
+ chars = [_char(value, (10.0 + index * 5.0, 80.0, 14.0 + index * 5.0, 88.0)) for index, value in enumerate("NOTICE")]
chars.append(_char("2", (90.0, 80.2, 94.0, 88.2)))
pdf_line = _line(
[
@@ -143,6 +140,49 @@ def test_true_diagonal_char_baseline_is_not_recovered_as_horizontal() -> None:
assert native_text._build_native_line_items([pdf_line], (100.0, 100.0)) == []
+def test_small_shear_formula_line_is_retained_as_formula_only() -> None:
+ """验证带数学运算符的小角度多基线粗行只进入 formula-only 流。"""
+ chars = [
+ _char("x", (10.0, 20.0, 15.0, 28.0)),
+ _char("=", (18.0, 24.0, 24.0, 30.0)),
+ ]
+ pdf_line = _line(
+ [_span("x=", (10.0, 20.0, 24.0, 30.0), 10.0, chars=chars)],
+ 10.0,
+ bbox=(10.0, 20.0, 24.0, 30.0),
+ )
+
+ items = native_text._build_native_line_items([pdf_line], (100.0, 100.0))
+
+ assert [(item.text, item.angle, item.formula_candidate_only) for item in items] == [("x=", 0, True)]
+
+
+def test_formula_only_rows_do_not_shift_existing_source_indices() -> None:
+ """验证新增公式候选使用尾部 source index,不改变既有自然文本身份。"""
+ first = _line([_span("first", (10.0, 10.0, 35.0, 18.0), 0.0)], 0.0)
+ formula = _line([_span("x=", (10.0, 20.0, 24.0, 30.0), 10.0)], 10.0)
+ second = _line([_span("second", (10.0, 32.0, 40.0, 40.0), 0.0)], 0.0)
+
+ items = native_text._build_native_line_items([first, formula, second], (100.0, 100.0))
+
+ assert {item.text: item.source_index for item in items} == {"first": 0, "second": 1, "x=": 2}
+
+
+def test_small_true_diagonal_without_formula_evidence_stays_rejected() -> None:
+ """验证缺少公式证据的短斜向文字不会借 formula-only 流回到正文。"""
+ chars = [
+ _char(value, (10.0 + index * 5.0, 30.0 - index * 2.0, 14.0 + index * 5.0, 38.0 - index * 2.0))
+ for index, value in enumerate("mark")
+ ]
+ pdf_line = _line(
+ [_span("mark", (10.0, 24.0, 29.0, 38.0), 10.0, chars=chars)],
+ 10.0,
+ bbox=(10.0, 24.0, 29.0, 38.0),
+ )
+
+ assert native_text._build_native_line_items([pdf_line], (100.0, 100.0)) == []
+
+
@pytest.mark.parametrize(
("line_angle", "page_rotation", "expected_angle"),
[
@@ -193,9 +233,7 @@ def test_native_line_builder_can_opt_in_to_180_degree_visual_runs() -> None:
)
assert default_items == []
- assert [(item.text, item.angle) for item in low_txt_items] == [
- ("upside down", 180)
- ]
+ assert [(item.text, item.angle) for item in low_txt_items] == [("upside down", 180)]
@pytest.mark.parametrize(
@@ -222,10 +260,13 @@ def test_native_line_builder_can_opt_in_to_180_degree_visual_runs() -> None:
def test_pdf_unicode_separator_spaces_are_normalized_to_ascii(separator: str) -> None:
"""验证所有 Unicode Zs 排版空格均转换为普通 ASCII 空格。"""
- assert native_text._sanitize_pdf_control_text(
- f"left{separator}right",
- preserve_newlines=True,
- ) == "left right"
+ assert (
+ native_text._sanitize_pdf_control_text(
+ f"left{separator}right",
+ preserve_newlines=True,
+ )
+ == "left right"
+ )
def test_pdf_unicode_line_separators_follow_newline_policy() -> None:
@@ -233,14 +274,20 @@ def test_pdf_unicode_line_separators_follow_newline_policy() -> None:
content = "first\u0085second\u2028third\u2029fourth"
- assert native_text._sanitize_pdf_control_text(
- content,
- preserve_newlines=True,
- ) == "first\nsecond\nthird\nfourth"
- assert native_text._sanitize_pdf_control_text(
- content,
- preserve_newlines=False,
- ) == "firstsecondthirdfourth"
+ assert (
+ native_text._sanitize_pdf_control_text(
+ content,
+ preserve_newlines=True,
+ )
+ == "first\nsecond\nthird\nfourth"
+ )
+ assert (
+ native_text._sanitize_pdf_control_text(
+ content,
+ preserve_newlines=False,
+ )
+ == "firstsecondthirdfourth"
+ )
def test_pdf_safe_invisible_and_control_characters_are_removed_idempotently() -> None:
@@ -253,10 +300,13 @@ def test_pdf_safe_invisible_and_control_characters_are_removed_idempotently() ->
)
assert normalized == "ABCDEFGHI"
- assert native_text._sanitize_pdf_control_text(
- normalized,
- preserve_newlines=True,
- ) == normalized
+ assert (
+ native_text._sanitize_pdf_control_text(
+ normalized,
+ preserve_newlines=True,
+ )
+ == normalized
+ )
def test_pdf_soft_hyphens_keep_only_latin_line_end_breaks() -> None:
@@ -273,7 +323,10 @@ def test_pdf_semantic_joiners_and_decode_markers_are_preserved() -> None:
content = "a\u200cb\u200dc\uf8f1d\ufffde"
- assert native_text._sanitize_pdf_control_text(
- content,
- preserve_newlines=True,
- ) == content
+ assert (
+ native_text._sanitize_pdf_control_text(
+ content,
+ preserve_newlines=True,
+ )
+ == content
+ )
diff --git a/tests/unittest/test_flash_pdf_scripts.py b/tests/unittest/test_flash_pdf_scripts.py
new file mode 100644
index 00000000..b6232a56
--- /dev/null
+++ b/tests/unittest/test_flash_pdf_scripts.py
@@ -0,0 +1,638 @@
+from __future__ import annotations
+
+from dataclasses import replace
+from functools import lru_cache
+from pathlib import Path
+from typing import Any
+
+import pytest
+from pdftext.schema import Bbox, Char
+
+from mineru.model.flash.pdf.geometry import _rotate_bbox_from_upright
+from mineru.model.flash import PdfModel
+from mineru.model.flash.pdf.document import PDFDocument
+from mineru.model.flash.pdf.models import _AxisLine, _LineItem
+from mineru.model.flash.pdf.pipeline import _analyze_native_document
+from mineru.model.flash.pdf.text_styles import (
+ PDFTextLinkLine,
+ PDFTextLinkRange,
+ PDFTextScriptLine,
+ PDFTextScriptRange,
+ PDFTextStyleLine,
+ PDFTextStyleRange,
+ apply_pdf_text_links,
+ apply_pdf_text_scripts,
+ apply_pdf_text_styles,
+ detect_pdf_text_script_lines,
+ materialize_pdf_inline_spans,
+)
+from mineru.types import BBox
+
+
+_PROJECT_ROOT = Path(__file__).resolve().parents[2]
+_DEMO_PDF_DIR = _PROJECT_ROOT / "demo" / "pdfs"
+
+_REVIEWED_SCRIPT_EXPECTATIONS = {
+ "demo1.pdf": {
+ (3, 45): (("2", "superscript"), ("2", "superscript")),
+ (3, 50): (("2", "superscript"),),
+ },
+ "demo3.pdf": {
+ (1, 74): (("1", "subscript"), ("2", "subscript"), ("n", "subscript")),
+ (3, 5): (("i", "subscript"), ("j", "subscript")),
+ (3, 7): (("i", "subscript"),),
+ (3, 8): (("j", "subscript"), ("i", "subscript"), ("j", "subscript")),
+ (3, 13): (("i", "subscript"), ("j", "subscript")),
+ (3, 60): (),
+ },
+ "中文论文2.pdf": {
+ (7, 46): (("1", "subscript"),),
+ (7, 47): (("1", "subscript"),),
+ (7, 80): (),
+ (7, 82): (("m", "subscript"),),
+ (7, 83): (("m", "subscript"),),
+ (7, 87): (("i", "subscript"), ("i", "subscript")),
+ (7, 88): (("m", "subscript"),),
+ (8, 7): (("i", "subscript"),),
+ (8, 8): (("m", "subscript"),),
+ (8, 14): (),
+ (8, 22): (),
+ (10, 25): (("i", "subscript"),),
+ (10, 26): (),
+ (10, 27): (("[112]", "superscript"),),
+ (11, 35): (("[127]", "superscript"), ("[128]", "superscript"), ("[129]", "superscript")),
+ (11, 56): (
+ ("1", "subscript"),
+ ("2", "subscript"),
+ ("n", "subscript"),
+ ("1", "subscript"),
+ ("2", "subscript"),
+ ("m", "subscript"),
+ ),
+ (11, 66): (("1", "subscript"),),
+ (11, 73): (("Score", "subscript"),),
+ (11, 92): (),
+ (11, 94): (),
+ (11, 97): (),
+ },
+ "IEBM_A_2667169_O-5.pdf": {
+ (0, 3): (),
+ (0, 7): (),
+ (0, 11): (),
+ (0, 14): (),
+ },
+}
+
+_RUN_CLOSURE_EXPECTATIONS = {
+ "demo2.pdf": {
+ (2, 22): (("t-1", "subscript"),),
+ (2, 25): (("t-1", "subscript"),),
+ },
+ "mixed_elements_pages_03_06.pdf": {
+ (0, 22): (("–3", "superscript"),),
+ (0, 64): (("6.6", "subscript"),),
+ (1, 25): (("–7", "superscript"),),
+ (1, 26): (("–5", "superscript"),),
+ (3, 19): (("1–x", "subscript"),),
+ },
+ "mixed_elements_pages_11_15.pdf": {
+ (3, 156): (
+ ("a)", "superscript"),
+ ("b)", "superscript"),
+ ("c)", "superscript"),
+ ("d)", "superscript"),
+ ),
+ },
+ "mixed_elements_pages_39_40.pdf": {
+ (1, 44): (("i−1", "subscript"), ("i+1", "subscript")),
+ (1, 46): (("i−1", "subscript"), ("i+1", "subscript")),
+ },
+}
+
+_NO_SCRIPT_SOURCE_EXPECTATIONS = {
+ "中文论文2.pdf": {
+ (15, 15),
+ (15, 35),
+ (15, 37),
+ }
+}
+
+
+def _origin_from_upright(
+ origin: tuple[float, float],
+ page_size: tuple[float, float],
+ angle: int,
+) -> tuple[float, float]:
+ """把局部正向 origin 逆变换到页面坐标。"""
+ x, y = origin
+ page_width, page_height = page_size
+ if angle == 270:
+ return y, page_height - x
+ if angle == 90:
+ return page_width - y, x
+ if angle == 180:
+ return page_width - x, page_height - y
+ return origin
+
+
+def _script_fixture(
+ *,
+ angle: int = 0,
+ formula_region: bool = True,
+) -> tuple[_LineItem, dict[int, BBox], dict[int, tuple[float, float]], tuple[float, float]]:
+ """构造同时含稳定上标和下标的 D-i-p 局部公式行。"""
+ page_size = (100.0, 120.0)
+ local_bboxes = (
+ (10.0, 40.0, 20.0, 50.0),
+ (20.0, 34.0, 26.0, 40.0),
+ (20.0, 50.0, 26.0, 56.0),
+ )
+ local_origins = ((10.0, 49.0), (20.0, 40.0), (20.0, 56.0))
+ page_bboxes = tuple(_rotate_bbox_from_upright(bbox, page_size, angle) for bbox in local_bboxes)
+ page_origins = tuple(_origin_from_upright(origin, page_size, angle) for origin in local_origins)
+ chars: list[Char] = [
+ {
+ "char": text,
+ "char_idx": index,
+ "bbox": Bbox(list(page_bboxes[index])),
+ "rotation": 0.0,
+ "font": {},
+ }
+ for index, text in enumerate("Dip")
+ ]
+ line = _LineItem(
+ text="Dip",
+ bbox=(
+ min(bbox[0] for bbox in page_bboxes),
+ min(bbox[1] for bbox in page_bboxes),
+ max(bbox[2] for bbox in page_bboxes),
+ max(bbox[3] for bbox in page_bboxes),
+ ),
+ angle=angle,
+ source_index=0,
+ chars=chars,
+ inline_math_regions=[
+ (
+ min(bbox[0] for bbox in page_bboxes),
+ min(bbox[1] for bbox in page_bboxes),
+ max(bbox[2] for bbox in page_bboxes),
+ max(bbox[3] for bbox in page_bboxes),
+ )
+ ]
+ if formula_region
+ else [],
+ )
+ return (
+ line,
+ dict(enumerate(page_bboxes)),
+ dict(enumerate(page_origins)),
+ page_size,
+ )
+
+
[email protected]("angle", [0, 90, 180, 270])
+def test_flash_script_geometry_uses_upright_coordinates(angle: int) -> None:
+ """验证四种页面方向下 loose/tight/origin 同步正向化后角色一致。"""
+ line, tight_bboxes, origins, page_size = _script_fixture(angle=angle)
+
+ script_lines = detect_pdf_text_script_lines(
+ [line],
+ page_size,
+ tight_bboxes,
+ origins,
+ )
+
+ assert [(item.start, item.end, item.style, item.formula_region) for item in script_lines[0].script_ranges] == [
+ (1, 2, "superscript", True),
+ (2, 3, "subscript", True),
+ ]
+
+
+def test_flash_formula_region_rebases_before_classification() -> None:
+ """验证公式区域使用内部 D 基线,同时稳定输出 i 上标和 p 下标。"""
+ line, tight_bboxes, origins, page_size = _script_fixture()
+
+ script_line = detect_pdf_text_script_lines(
+ [line],
+ page_size,
+ tight_bboxes,
+ origins,
+ )[0]
+
+ assert all(item.stable_body_count == 1 for item in script_line.script_ranges)
+ assert [item.style for item in script_line.script_ranges] == [
+ "superscript",
+ "subscript",
+ ]
+
+
+def test_flash_formula_region_without_internal_body_stays_plain() -> None:
+ """验证公式区域全部字符同步偏移且无内部正文基线时不输出 style。"""
+ line, tight_bboxes, origins, page_size = _script_fixture()
+ line = replace(line, chars=line.chars[1:], text="ip")
+ line.inline_math_regions = [line.bbox]
+
+ script_line = detect_pdf_text_script_lines(
+ [line],
+ page_size,
+ tight_bboxes,
+ origins,
+ )[0]
+
+ assert script_line.script_ranges == ()
+
+
+def test_flash_missing_extended_geometry_stays_plain() -> None:
+ """验证 Flash 缺少 tight/origin 时不通过 loose bbox 猜测上下标。"""
+ line, _tight_bboxes, _origins, page_size = _script_fixture()
+
+ script_line = detect_pdf_text_script_lines([line], page_size, {}, {})[0]
+
+ assert script_line.script_ranges == ()
+
+
+def test_flash_fraction_bar_suppresses_stacked_script_candidate() -> None:
+ """验证上下叠字被短横线分隔时按整处分式拒识上下标。"""
+ page_size = (100.0, 120.0)
+ line_chars: list[Char] = [
+ {"char": "x", "char_idx": 0, "bbox": Bbox([10.0, 40.0, 20.0, 50.0]), "rotation": 0.0, "font": {}},
+ {"char": "1", "char_idx": 1, "bbox": Bbox([22.0, 32.0, 30.0, 40.0]), "rotation": 0.0, "font": {}},
+ ]
+ denominator: Char = {
+ "char": "M",
+ "char_idx": 2,
+ "bbox": Bbox([22.0, 44.0, 30.0, 52.0]),
+ "rotation": 0.0,
+ "font": {},
+ }
+ line = _LineItem(
+ text="x1",
+ bbox=(10.0, 32.0, 30.0, 52.0),
+ angle=0,
+ source_index=0,
+ chars=line_chars,
+ )
+ tight_bboxes = {
+ 0: (10.0, 40.0, 20.0, 50.0),
+ 1: (22.0, 32.0, 30.0, 40.0),
+ 2: (22.0, 44.0, 30.0, 52.0),
+ }
+ origins = {0: (10.0, 49.0), 1: (22.0, 40.0), 2: (22.0, 52.0)}
+
+ unfiltered = detect_pdf_text_script_lines([line], page_size, tight_bboxes, origins)[0]
+ filtered = detect_pdf_text_script_lines(
+ [line],
+ page_size,
+ tight_bboxes,
+ origins,
+ all_chars=[*line_chars, denominator],
+ drawing_lines=[_AxisLine((21.0, 41.0, 31.0, 42.0), 1.0, "horizontal")],
+ )[0]
+
+ assert [(item.start, item.end, item.style) for item in unfiltered.script_ranges] == [(1, 2, "superscript")]
+ assert filtered.script_ranges == ()
+
+
[email protected]("text", ["Bm", "r1"])
+def test_flash_formula_region_marks_only_the_index(text: str) -> None:
+ """验证公式内部 B_m 与 r_1 只标记下移索引,不把整个 token 标成下标。"""
+ line, tight_bboxes, origins, page_size = _script_fixture()
+ body_char = {**line.chars[0], "char": text[0]}
+ index_char = {**line.chars[2], "char": text[1]}
+ line = replace(line, text=text, chars=[body_char, index_char])
+
+ script_line = detect_pdf_text_script_lines(
+ [line],
+ page_size,
+ tight_bboxes,
+ origins,
+ )[0]
+
+ assert [(item.start, item.end, item.style) for item in script_line.script_ranges] == [(1, 2, "subscript")]
+
+
+def test_flash_script_projection_combines_font_styles() -> None:
+ """验证 Flash 上下标与已有粗体区间在同一 InlineSpan 流中组合。"""
+ blocks = [
+ {
+ "type": "text",
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "Bm",
+ }
+ ]
+ style_line = PDFTextStyleLine(
+ bbox=(10.0, 10.0, 30.0, 20.0),
+ text="Bm",
+ style_ranges=(PDFTextStyleRange(0, 1, ("bold",)),),
+ source_index=0,
+ )
+ script_line = PDFTextScriptLine(
+ bbox=(10.0, 10.0, 30.0, 20.0),
+ text="Bm",
+ script_ranges=(
+ PDFTextScriptRange(
+ 1,
+ 2,
+ "subscript",
+ (20.0, 15.0, 25.0, 20.0),
+ 1,
+ True,
+ ),
+ ),
+ source_index=0,
+ angle=0,
+ )
+
+ apply_pdf_text_styles(blocks, [style_line], (100.0, 100.0))
+ apply_pdf_text_scripts(blocks, [script_line], (100.0, 100.0))
+ materialize_pdf_inline_spans(blocks)
+
+ assert blocks[0]["content"] == [
+ {"type": "text", "content": "B", "styles": ["bold"]},
+ {"type": "text", "content": "m", "styles": ["subscript"]},
+ ]
+
+
+def test_flash_script_projection_does_not_leak_to_same_text() -> None:
+ """验证公式内候选按整行区间投影,不会回退到同行同名普通字符。"""
+ blocks = [
+ {
+ "type": "text",
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "Bm Bm",
+ }
+ ]
+ script_line = PDFTextScriptLine(
+ bbox=(10.0, 10.0, 90.0, 20.0),
+ text="BmBm",
+ script_ranges=(PDFTextScriptRange(3, 4, "subscript", (70.0, 15.0, 75.0, 20.0), 1, True),),
+ source_index=0,
+ angle=0,
+ )
+
+ apply_pdf_text_scripts(blocks, [script_line], (100.0, 100.0))
+ materialize_pdf_inline_spans(blocks)
+
+ assert blocks[0]["content"] == [
+ {"type": "text", "content": "Bm B"},
+ {"type": "text", "content": "m", "styles": ["subscript"]},
+ ]
+
+
+def test_flash_script_projection_combines_hyperlink() -> None:
+ """验证超链接与上下标区间共同物化时保持子 Span 顺序和 URL。"""
+ blocks = [
+ {
+ "type": "text",
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "x2",
+ }
+ ]
+ link_line = PDFTextLinkLine(
+ bbox=(10.0, 10.0, 30.0, 20.0),
+ text="x2",
+ link_ranges=(PDFTextLinkRange(0, 2, "https://example.test/x2"),),
+ source_index=0,
+ )
+ script_line = PDFTextScriptLine(
+ bbox=link_line.bbox,
+ text="x2",
+ script_ranges=(PDFTextScriptRange(1, 2, "superscript", (20.0, 10.0, 25.0, 15.0), 1, False),),
+ source_index=0,
+ angle=0,
+ )
+
+ apply_pdf_text_links(blocks, [link_line], (100.0, 100.0))
+ apply_pdf_text_scripts(blocks, [script_line], (100.0, 100.0))
+ materialize_pdf_inline_spans(blocks)
+
+ assert blocks[0]["content"] == [
+ {
+ "type": "hyperlink",
+ "content": [
+ {"type": "text", "content": "x", "styles": []},
+ {"type": "text", "content": "2", "styles": ["superscript"]},
+ ],
+ "url": "https://example.test/x2",
+ }
+ ]
+
+
[email protected]("block_type", ["table", "code", "equation", "image"])
+def test_flash_scripts_exclude_non_natural_blocks(block_type: str) -> None:
+ """验证表格、代码、独立公式和图片容器不接收 Flash 上下标。"""
+ blocks = [
+ {
+ "type": block_type,
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "Bm",
+ }
+ ]
+ script_line = PDFTextScriptLine(
+ bbox=(10.0, 10.0, 30.0, 20.0),
+ text="Bm",
+ script_ranges=(
+ PDFTextScriptRange(
+ 1,
+ 2,
+ "subscript",
+ (20.0, 15.0, 25.0, 20.0),
+ 1,
+ False,
+ ),
+ ),
+ source_index=0,
+ angle=0,
+ )
+
+ apply_pdf_text_scripts(blocks, [script_line], (100.0, 100.0))
+ materialize_pdf_inline_spans(blocks)
+
+ assert blocks[0]["content"] == "Bm"
+
+
+def test_late_inline_math_region_drops_unrebased_candidate() -> None:
+ """验证后续恢复的公式区域会过滤未在公式内部重新基线的候选。"""
+ blocks = [
+ {
+ "type": "text",
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "Bm",
+ "_inline_math_regions": [[0.15, 0.1, 0.3, 0.3]],
+ }
+ ]
+ script_line = PDFTextScriptLine(
+ bbox=(10.0, 10.0, 30.0, 30.0),
+ text="Bm",
+ script_ranges=(
+ PDFTextScriptRange(
+ 1,
+ 2,
+ "subscript",
+ (20.0, 15.0, 25.0, 20.0),
+ 1,
+ False,
+ ),
+ ),
+ source_index=0,
+ angle=0,
+ )
+
+ apply_pdf_text_scripts(blocks, [script_line], (100.0, 100.0))
+ materialize_pdf_inline_spans(blocks)
+
+ assert blocks[0]["content"] == [{"type": "text", "content": "Bm"}]
+ assert "_inline_math_regions" not in blocks[0]
+
+
+def _flash_script_runs(pdf_name: str) -> list[tuple[str, tuple[str, ...]]]:
+ """解析真实 Flash PDF 并收集最终 TextSpan 上下标。"""
+ with PDFDocument(str(_DEMO_PDF_DIR / pdf_name)) as document:
+ pages = PdfModel().predict(document)
+ runs: list[tuple[str, tuple[str, ...]]] = []
+
+ def walk(value: Any) -> None:
+ """递归收集最终 TextSpan style。"""
+ if isinstance(value, dict):
+ styles = tuple(str(style) for style in value.get("styles", []))
+ content = value.get("content")
+ if value.get("type") == "text" and isinstance(content, str) and {"superscript", "subscript"}.intersection(styles):
+ runs.append((content, styles))
+ for child in value.values():
+ walk(child)
+ elif isinstance(value, list):
+ for child in value:
+ walk(child)
+
+ walk(pages)
+ return runs
+
+
+@lru_cache(maxsize=None)
+def _flash_script_diagnostics(pdf_name: str) -> tuple[dict[str, Any], ...]:
+ """解析真实 Flash PDF 并缓存逐行上下标 sidecar。"""
+ diagnostics: list[dict[str, Any]] = []
+ with PDFDocument(str(_DEMO_PDF_DIR / pdf_name)) as document:
+ _analyze_native_document(document, script_diagnostics=diagnostics)
+ return tuple(diagnostics)
+
+
[email protected]("pdf_name", tuple(_REVIEWED_SCRIPT_EXPECTATIONS))
+def test_user_reviewed_flash_script_ranges(pdf_name: str) -> None:
+ """逐项锁定人工审阅反馈涉及的 base、索引、分式和复杂公式边界。"""
+ diagnostics = _flash_script_diagnostics(pdf_name)
+
+ for (page_index, source_index), expected in _REVIEWED_SCRIPT_EXPECTATIONS[pdf_name].items():
+ script_line = next(line for line in diagnostics[page_index]["script_lines"] if line.source_index == source_index)
+ actual = tuple(
+ (script_line.text[script_range.start : script_range.end], script_range.style)
+ for script_range in script_line.script_ranges
+ )
+ assert actual == expected, (page_index + 1, source_index, script_line.text)
+ materialized = tuple(
+ (item["text"], item["role"])
+ for item in diagnostics[page_index]["materialized_ranges"]
+ if item["source_index"] == source_index
+ )
+ assert materialized == expected, (page_index + 1, source_index, script_line.text)
+
+
[email protected]("pdf_name", tuple(_RUN_CLOSURE_EXPECTATIONS))
+def test_user_reviewed_flash_script_run_closures(pdf_name: str) -> None:
+ """验证运算符、小数点和作者括号与同基线角标保持为连续 run。"""
+ diagnostics = _flash_script_diagnostics(pdf_name)
+
+ for (page_index, source_index), expected in _RUN_CLOSURE_EXPECTATIONS[pdf_name].items():
+ script_line = next(line for line in diagnostics[page_index]["script_lines"] if line.source_index == source_index)
+ actual = tuple(
+ (script_line.text[script_range.start : script_range.end], script_range.style)
+ for script_range in script_line.script_ranges
+ )
+ materialized = tuple(
+ (item["text"], item["role"])
+ for item in diagnostics[page_index]["materialized_ranges"]
+ if item["source_index"] == source_index
+ )
+ assert all(item in actual for item in expected), (page_index + 1, source_index, script_line.text)
+ assert all(item in materialized for item in expected), (page_index + 1, source_index, script_line.text)
+
+
[email protected]("pdf_name", tuple(_NO_SCRIPT_SOURCE_EXPECTATIONS))
+def test_user_reviewed_unicode_math_tokens_stay_body(pdf_name: str) -> None:
+ """验证没有内部 base 的独立 Greek token 不因 CJK 正文基线而成为下标。"""
+ diagnostics = _flash_script_diagnostics(pdf_name)
+
+ for page_index, source_index in _NO_SCRIPT_SOURCE_EXPECTATIONS[pdf_name]:
+ script_line = next(line for line in diagnostics[page_index]["script_lines"] if line.source_index == source_index)
+ assert script_line.script_ranges == ()
+ assert not any(item["source_index"] == source_index for item in diagnostics[page_index]["materialized_ranges"])
+
+
+def test_chinese_paper_page_12_recovers_numbered_formula_regions() -> None:
+ """验证栏顶公式 6、7、8 被完整认领为 equation,且不吸收相邻正文。"""
+ diagnostics: list[dict[str, Any]] = []
+ with PDFDocument(str(_DEMO_PDF_DIR / "中文论文2.pdf")) as document:
+ pages = _analyze_native_document(document, script_diagnostics=diagnostics)
+
+ equations = {
+ tag: block
+ for block in pages[11]
+ if block.get("type") == "equation" and isinstance((content := block.get("content")), str)
+ for tag in ("6", "7", "8")
+ if f"\\tag{{{tag}}}" in content
+ }
+ assert set(equations) == {"6", "7", "8"}
+ assert 0.6 < equations["6"]["bbox"][0] < 0.7
+ assert equations["6"]["bbox"][1] < equations["7"]["bbox"][1] < equations["8"]["bbox"][1]
+ assert all(block["bbox"][2] > 0.9 for block in equations.values())
+ assert all("如下" not in block["content"] and "然后根据" not in block["content"] for block in equations.values())
+ assert not any(item["source_index"] in {61, 64} for item in diagnostics[11]["materialized_ranges"])
+
+
+ ("pdf_name", "expected"),
+ [
+ pytest.param(
+ "中文论文.pdf",
+ (("2", "superscript"), ("[1]", "superscript"), ("-3", "superscript")),
+ id="chinese-paper",
+ ),
+ pytest.param(
+ "中文论文2.pdf",
+ (("[1]", "superscript"), ("[82]", "superscript"), ("i", "subscript")),
+ id="chinese-paper-2",
+ ),
+ pytest.param(
+ "demo3.pdf",
+ (("i", "subscript"), ("BASE", "subscript"), ("LARGE", "subscript")),
+ id="model-subscripts",
+ ),
+ pytest.param(
+ "demo4.pdf",
+ (("18", "superscript"), ("2", "superscript")),
+ id="isotope-and-unit",
+ ),
+ ],
+)
+def test_real_flash_pdfs_materialize_confirmed_scripts(
+ pdf_name: str,
+ expected: tuple[tuple[str, str], ...],
+) -> None:
+ """验证真实 Flash PDF 的已确认上下标进入最终 InlineSpan。"""
+ runs = _flash_script_runs(pdf_name)
+
+ assert all(
+ any(content == expected_content and role in styles for content, styles in runs) for expected_content, role in expected
+ )
+
+
+def test_real_flash_plain_layouts_do_not_gain_scripts() -> None:
+ """验证财经图表样本的旋转和容器文本不会产生 Flash 上下标。"""
+ assert _flash_script_runs("caibao1.pdf") == []
+
+
+def test_zh2_normal_english_words_stay_plain_in_flash() -> None:
+ """验证中文论文2的普通混合字体英文不会被 Flash 误标上下标。"""
+ styled_text = {content for content, _styles in _flash_script_runs("中文论文2.pdf")}
+
+ assert styled_text.isdisjoint({"Source", "Hypothesis", "Reference", "BLEU", "ROUGE"})