Skip to content

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

fix: bound PDFPageTextGeometry handling in PDF analysis and rendering

myhlolibec1c2c85bb0
diff --git "a/demo/pdfs/\344\270\255\346\226\207\350\256\272\346\226\2072.pdf" "b/demo/pdfs/\344\270\255\346\226\207\350\256\272\346\226\2072.pdf"
new file mode 100644
index 00000000..62c6896a
Binary files /dev/null and "b/demo/pdfs/\344\270\255\346\226\207\350\256\272\346\226\2072.pdf" differ
diff --git a/mineru/backend/analysis/pdf/text/content.py b/mineru/backend/analysis/pdf/text/content.py
index 1167c629..cf445a09 100644
--- a/mineru/backend/analysis/pdf/text/content.py
+++ b/mineru/backend/analysis/pdf/text/content.py
@@ -7,14 +7,12 @@ from typing import Any, Literal
import numpy as np
from PIL import Image
-from pdftext.schema import Char
-
from .....model.runtime.hybrid import HybridLocalModelContext, run_ocr_inference
from .....types import BBox, BlockType, ContentType
from .....utils.language import detect_lang
from .....model.ocr.image import rotate_vertical_crop_if_needed
from .....model.ocr.results import OcrConfidence
-from .....model.flash.pdf.document import PDFPage, get_lines_from_chars
+from .....model.flash.pdf.document import PDFPage, PDFPageTextGeometry, get_lines_from_chars
from .....model.flash.pdf.text_styles import (
PDF_NATIVE_SCRIPT_MARKUP_KEY,
PDFTextLinkLine,
@@ -152,7 +150,7 @@ def _fill_native_pdf_text_spans(
render_scale: float,
page_size: tuple[float, float],
*,
- page_chars: list[Char] | None = None,
+ page_text_geometry: PDFPageTextGeometry | None = None,
) -> list[_AnalyzeSpan]:
"""复用原生 PDF 字符回填逻辑,并允许共享同页删除线检测读取的字符。"""
page_width, page_height = page_size
@@ -164,7 +162,9 @@ def _fill_native_pdf_text_spans(
render_scale,
[virtual_block],
[],
- page_chars=page_chars,
+ page_chars=page_text_geometry.chars if page_text_geometry is not None else None,
+ tight_bboxes=page_text_geometry.tight_bboxes if page_text_geometry is not None else None,
+ origins=page_text_geometry.origins if page_text_geometry is not None else None,
)
@@ -365,7 +365,7 @@ def _fill_window_block_content_and_lines(
style_lines: list[PDFTextStyleLine] = []
link_lines: list[PDFTextLinkLine] = []
if parse_mode == "txt":
- page_chars = None
+ page_text_geometry = None
try:
page_char_count = pdf_page.get_char_count()
except Exception:
@@ -375,16 +375,19 @@ def _fill_window_block_content_and_lines(
or isinstance(page_char_count, bool)
or page_char_count <= MAX_NATIVE_TEXT_CHARS_PER_PAGE
):
- page_chars, _line_items, style_lines, link_lines = build_pdf_native_visual_lines_and_styles(
- pdf_page,
- )
+ (
+ page_text_geometry,
+ _line_items,
+ style_lines,
+ link_lines,
+ ) = build_pdf_native_visual_lines_and_styles(pdf_page)
page_spans = _fill_native_pdf_text_spans(
pdf_page,
page_spans,
page_pil_image,
render_scale,
page_size,
- page_chars=page_chars,
+ page_text_geometry=page_text_geometry,
)
block_lines = _group_page_spans_by_block(
diff --git a/mineru/backend/analysis/pdf/text/native.py b/mineru/backend/analysis/pdf/text/native.py
index 1c4aa217..240e7097 100644
--- a/mineru/backend/analysis/pdf/text/native.py
+++ b/mineru/backend/analysis/pdf/text/native.py
@@ -80,6 +80,8 @@ def txt_spans_extract(
all_discarded_blocks: list[tuple[Any, ...]],
*,
page_chars: list[Char] | dict[str, list[Char]] | None = None,
+ tight_bboxes: dict[int, BBox] | None = None,
+ origins: dict[int, tuple[float, float]] | None = None,
) -> list[_AnalyzeSpan]:
"""从 PDF 原生字符中提取文本 Span,并允许复用调用方已读取的页面字符。"""
page_char_count = None
@@ -94,7 +96,10 @@ def txt_spans_extract(
return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)
if page_chars is None:
- page_chars = pdf_page.get_chars()
+ page_text_geometry = pdf_page.get_chars_with_geometry()
+ page_chars = page_text_geometry.chars
+ tight_bboxes = page_text_geometry.tight_bboxes
+ origins = page_text_geometry.origins
page_all_chars = _get_chars_for_span_fill(page_chars)
# 计算所有span的高度的中位数
@@ -153,7 +158,13 @@ def txt_spans_extract(
span.metadata["chars"] = []
new_spans.append(span)
- need_ocr_spans = fill_char_in_spans(new_spans, page_all_chars, median_span_height)
+ need_ocr_spans = fill_char_in_spans(
+ new_spans,
+ page_all_chars,
+ median_span_height,
+ tight_bboxes=tight_bboxes,
+ origins=origins,
+ )
return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)
@@ -329,52 +340,218 @@ class SpanBlockMatcher:
return calculate_overlap_area_in_bbox1_area_ratio(span.bbox, block_bbox)
+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 cast(BBox, bbox)
+
+
+def _coerce_finite_whitespace_bbox(value: Any) -> BBox | None:
+ """解析空白字符的 loose bbox,并允许 PDF 中常见的零面积 advance point。"""
+ 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 cast(BBox, bbox)
+
+
+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 _span_match_rank(char_bbox: BBox, span_bbox: BBox, span_index: int) -> tuple[float, float, int]:
+ """按归一化纵向中心距离、横向中心距离和原顺序稳定排序。"""
+ char_center_x = (char_bbox[0] + char_bbox[2]) / 2
+ char_center_y = (char_bbox[1] + char_bbox[3]) / 2
+ span_center_x = (span_bbox[0] + span_bbox[2]) / 2
+ span_center_y = (span_bbox[1] + span_bbox[3]) / 2
+ span_width = max(span_bbox[2] - span_bbox[0], 1e-6)
+ span_height = max(span_bbox[3] - span_bbox[1], 1e-6)
+ return (
+ abs(char_center_y - span_center_y) / span_height,
+ abs(char_center_x - span_center_x) / span_width,
+ span_index,
+ )
+
+
+def _match_char_bbox_to_span(
+ char_bbox: BBox,
+ char_text: str,
+ span_bboxes: list[BBox],
+ grid: dict[int, list[int]],
+ grid_size: float,
+) -> int | None:
+ """在给定 bbox 对应的全部候选 Span 中返回几何距离最优者。"""
+ char_center_x = (char_bbox[0] + char_bbox[2]) / 2
+ char_center_y = (char_bbox[1] + char_bbox[3]) / 2
+ candidate_span_indices = grid.get(int(char_center_y / grid_size), [])
+ matches = []
+ for span_index in candidate_span_indices:
+ span_bbox = span_bboxes[span_index]
+ if (
+ char_text not in LINE_STOP_FLAG
+ and char_text not in LINE_START_FLAG
+ and not span_bbox[0] < char_center_x < span_bbox[2]
+ ):
+ continue
+ if calculate_char_in_span(char_bbox, span_bbox, char_text):
+ matches.append(span_index)
+ if not matches:
+ return None
+ return min(
+ matches,
+ key=lambda span_index: _span_match_rank(char_bbox, span_bboxes[span_index], span_index),
+ )
+
+
+def _match_whitespace_bbox_to_first_span(
+ char_bbox: BBox,
+ char_text: str,
+ span_bboxes: list[BBox],
+ grid: dict[int, list[int]],
+ grid_size: float,
+) -> int | None:
+ """按旧 loose 顺序归属无可见字形的空白,避免重叠 Span 改变词间距。"""
+ char_center_x = (char_bbox[0] + char_bbox[2]) / 2
+ char_center_y = (char_bbox[1] + char_bbox[3]) / 2
+ for span_index in grid.get(int(char_center_y / grid_size), []):
+ span_bbox = span_bboxes[span_index]
+ if (
+ char_text not in LINE_STOP_FLAG
+ and char_text not in LINE_START_FLAG
+ and not span_bbox[0] < char_center_x < span_bbox[2]
+ ):
+ continue
+ if calculate_char_in_span(char_bbox, span_bbox, char_text):
+ return span_index
+ return None
+
+
def fill_char_in_spans(
spans: list[_AnalyzeSpan],
all_chars: list[Char],
median_span_height: float,
+ *,
+ tight_bboxes: dict[int, BBox] | None = None,
+ origins: dict[int, tuple[float, float]] | None = None,
) -> list[_AnalyzeSpan]:
- """将 PDF 字符分配到对应 Span,并返回仍需后置 OCR 的 Span。"""
- # 简单从上到下排一下序
+ """以 tight-first、loose-fallback 将字符分配到 Span,并返回待 OCR Span。"""
spans = sorted(spans, key=lambda x: x.bbox[1])
+ tight_bboxes = tight_bboxes or {}
+ origins = origins or {}
grid_size = max(1, median_span_height)
grid = collections.defaultdict(list)
span_bboxes = []
- for i, span in enumerate(spans):
+ for span_index, span in enumerate(spans):
span_bbox = span.bbox
span_bboxes.append(span_bbox)
start_cell = int(span_bbox[1] / grid_size)
end_cell = int(span_bbox[3] / grid_size)
for cell_idx in range(start_cell, end_cell + 1):
- grid[cell_idx].append(i)
+ grid[cell_idx].append(span_index)
+
+ assigned_span_indices: list[int | None] = [None] * len(all_chars)
+ for char_position, char in enumerate(all_chars):
+ char_idx = _char_geometry_key(char)
+ tight_bbox = _coerce_finite_bbox(tight_bboxes.get(char_idx)) if char_idx is not None else None
+ loose_bbox = _coerce_finite_bbox(char.get("bbox"))
+ char_text = str(char.get("char", ""))
+ if char_text.isspace():
+ continue
+ for candidate_bbox in (tight_bbox, loose_bbox):
+ if candidate_bbox is None:
+ continue
+ assigned_span_indices[char_position] = _match_char_bbox_to_span(
+ candidate_bbox,
+ char_text,
+ span_bboxes,
+ grid,
+ grid_size,
+ )
+ if assigned_span_indices[char_position] is not None:
+ break
- for char in all_chars:
- char_bbox = char["bbox"]
- char_center_x = (char_bbox[0] + char_bbox[2]) / 2
- char_center_y = (char_bbox[1] + char_bbox[3]) / 2
- cell_idx = int(char_center_y / grid_size)
+ previous_visible_owners: list[int | None] = [None] * len(all_chars)
+ previous_owner = None
+ for char_position, char in enumerate(all_chars):
+ char_text = str(char.get("char", ""))
+ if char_text in CONTROL_LINE_BREAK_CHARS:
+ previous_owner = None
+ continue
+ previous_visible_owners[char_position] = previous_owner
+ if not char_text.isspace() and assigned_span_indices[char_position] is not None:
+ previous_owner = assigned_span_indices[char_position]
+
+ next_visible_owners: list[int | None] = [None] * len(all_chars)
+ next_owner = None
+ for char_position in range(len(all_chars) - 1, -1, -1):
+ char_text = str(all_chars[char_position].get("char", ""))
+ if char_text in CONTROL_LINE_BREAK_CHARS:
+ next_owner = None
+ continue
+ next_visible_owners[char_position] = next_owner
+ if not char_text.isspace() and assigned_span_indices[char_position] is not None:
+ next_owner = assigned_span_indices[char_position]
- candidate_span_indices = grid.get(cell_idx, [])
+ for char_position, char in enumerate(all_chars):
+ char_text = str(char.get("char", ""))
+ if not char_text.isspace():
+ continue
+ loose_bbox = _coerce_finite_whitespace_bbox(char.get("bbox"))
+ if loose_bbox is None:
+ continue
+ previous_owner = previous_visible_owners[char_position]
+ next_owner = next_visible_owners[char_position]
+ same_neighbor_owner = previous_owner is not None and previous_owner == next_owner
+ neighbor_owner = previous_owner if same_neighbor_owner else None
+ if neighbor_owner is None:
+ neighbor_owner = previous_owner if next_owner is None else next_owner if previous_owner is None else None
+ if (
+ char_text not in CONTROL_LINE_BREAK_CHARS
+ and neighbor_owner is not None
+ and (same_neighbor_owner or calculate_char_in_span(loose_bbox, span_bboxes[neighbor_owner], char_text))
+ ):
+ assigned_span_indices[char_position] = neighbor_owner
+ else:
+ assigned_span_indices[char_position] = _match_whitespace_bbox_to_first_span(
+ loose_bbox,
+ char_text,
+ span_bboxes,
+ grid,
+ grid_size,
+ )
- for span_idx in candidate_span_indices:
- span = spans[span_idx]
- span_bbox = span_bboxes[span_idx]
- if (
- char["char"] not in LINE_STOP_FLAG
- and char["char"] not in LINE_START_FLAG
- and not span_bbox[0] < char_center_x < span_bbox[2]
- ):
- continue
- if calculate_char_in_span(char_bbox, span_bbox, char["char"]):
- span.metadata["chars"].append(char)
- break
+ for char, span_index in zip(all_chars, assigned_span_indices):
+ if span_index is not None:
+ spans[span_index].metadata["chars"].append(char)
need_ocr_spans = []
for span in spans:
private_use_signal = _get_private_use_text_signal(span.metadata["chars"])
should_post_ocr_private_use = _should_fallback_to_post_ocr_for_private_use_text(private_use_signal)
- chars_to_content(span)
+ chars_to_content(
+ span,
+ tight_bboxes=tight_bboxes,
+ origins=origins,
+ )
# 有的span中虽然没有字但有一两个空的占位符,用宽高和content长度过滤
if should_post_ocr_private_use and span.content:
span.metadata[POST_OCR_FALLBACK_CONTENT_KEY] = span.content
@@ -432,57 +609,85 @@ LINE_START_FLAG = (
)
Span_Height_Ratio = 0.33 # 字符的中轴和span的中轴高度差不能超过1/3span高度
-# 正文带阈值:只允许接近最大高度的字符参与正文基线估计。
-SCRIPT_BODY_FULL_HEIGHT_RATIO = 0.9
-# 三类证据阈值:依次对应强几何、成对结构和相邻字体切换。
-SCRIPT_GEOMETRY_MAX_HEIGHT_RATIO = 0.8
-SCRIPT_GEOMETRY_MIN_OFFSET_RATIO = 0.24
-SCRIPT_STRUCTURE_MIN_OFFSET_RATIO = 0.18
-SCRIPT_TYPOGRAPHY_MIN_LOCAL_OFFSET_RATIO = 0.1
-# 连续组件阈值:弱证据只能扩展已有种子,不能独立产生上下标。
+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
-SCRIPT_BRACKET_PAIRS = {"[": "]", "[": "]", "(": ")", "(": ")"}
-SCRIPT_NUMERIC_REFERENCE_OPENERS = {"[", "["}
-SCRIPT_NUMERIC_REFERENCE_SEPARATORS = {"-", "–", "—", "‑", ",", ",", " ", "\u00a0"}
SPAN_FILL_LOCAL_ROTATION_MAX_DEGREES = 30.0
CONTROL_LINE_BREAK_CHARS = {"\r", "\n"}
_ScriptRole = Literal["body", "sup", "sub"]
_ScriptMarkRole = Literal["sup", "sub"]
-_ScriptEvidenceKind = Literal["geometry", "typography", "structure"]
@dataclass(frozen=True, slots=True)
class _ScriptCharFeature:
- """保存单个字符参与上下标判定所需的只读排版特征。"""
+ """保存单个字符参与纯几何上下标判定所需的只读特征。"""
index: int
text: str
- height: float
- center_y: float
- font_signature: tuple[Any, Any]
+ 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:
- """表示当前 span 的正文中心线和参考高度。"""
+ """表示当前视觉组件的正文 origin 基线与双 bbox 参考高度。"""
- center_y: float
- height: float
+ baseline: float
+ tight_height: float
+ loose_height: float
+ member_indices: frozenset[int]
@dataclass(frozen=True, slots=True)
-class _ScriptSeed:
- """表示可让连续组件成立的高置信证据区间及其角色。"""
+class _ScriptBaselineCluster:
+ """表示共享近似字符 origin 的正文或角标基线簇。"""
- start: int
- end: int
- role: _ScriptMarkRole
- evidence: _ScriptEvidenceKind
- protected_body_indices: frozenset[int] = frozenset()
+ baseline: float
+ member_indices: tuple[int, ...]
def _is_private_use_char(char: str) -> bool:
@@ -608,282 +813,493 @@ def _get_char_bbox_metrics_list(chars: list[Char]) -> list[dict[str, float]]:
return [_get_char_bbox_metrics(char) for char in chars]
-def _is_valid_script_reference_char(char: Char, metrics: dict[str, float]) -> bool:
- """过滤空白和退化 bbox,只用真实可见字符估计正文主带。"""
- if char["char"] in {" ", "\r", "\n"}:
- return False
-
- return metrics["height"] > 1 and metrics["width"] > 0
-
-
def _get_script_role(offset: float) -> _ScriptMarkRole:
- """把相对正文中心的纵向偏移转换为上标或下标角色。"""
+ """把相对正文 origin 基线的纵向偏移转换为上下标角色。"""
return "sub" if offset > 0 else "sup"
def _build_script_features(
chars: list[Char],
- char_metrics: list[dict[str, float]],
+ 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, metrics) in enumerate(zip(chars, char_metrics)):
+ for index, char in enumerate(chars):
text = str(char.get("char", ""))
- font = char.get("font") or {}
- is_valid = _is_valid_script_reference_char(char, metrics)
+ 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,
- height=metrics["height"],
- center_y=metrics["center_y"],
- font_signature=(font.get("name"), font.get("flags")),
+ loose_bbox=loose_bbox,
+ tight_bbox=tight_bbox,
+ origin=origin,
is_valid=is_valid,
- is_body_anchor=is_valid and text.isalnum(),
+ is_body_anchor=is_valid and text.isalnum() and index not in protected_body_indices,
)
)
return features
-def _estimate_script_body_band(features: list[_ScriptCharFeature]) -> _ScriptBodyBand | None:
- """使用全高正文锚点的最低中心估计正文带,排除项目符号与标点干扰。"""
- anchors = [feature for feature in features if feature.is_body_anchor]
- if not anchors:
- return None
+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]
- body_height = max(feature.height for feature in anchors)
- full_height_anchors = [feature for feature in anchors if feature.height >= body_height * SCRIPT_BODY_FULL_HEIGHT_RATIO]
- if not full_height_anchors:
- return None
- return _ScriptBodyBand(
- center_y=max(feature.center_y for feature in full_height_anchors),
- height=body_height,
- )
+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
-def _is_script_identifier_char(text: str) -> bool:
- """判断字符是否属于可承载数学角标的非 CJK 字母或数字。"""
- if len(text) != 1:
- return False
- if text.isdigit():
- return True
- if not text.isalpha():
- return False
- unicode_name = unicodedata.name(text, "")
- return not any(marker in unicode_name for marker in ("CJK", "HIRAGANA", "KATAKANA", "HANGUL", "BOPOMOFO"))
+ 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
-def _estimate_main_font_body_band(features: list[_ScriptCharFeature]) -> _ScriptBodyBand | None:
- """使用字母和汉字投票选出主字体,并据此估计局部正文带。"""
- voters = [feature for feature in features if feature.is_body_anchor and feature.text.isalpha()]
- if not voters:
- return None
+ if current:
+ components.append(current)
+ return components
- font_counts: dict[tuple[Any, Any], int] = collections.Counter(feature.font_signature for feature in voters)
- first_indices: dict[tuple[Any, Any], int] = {}
- for feature in voters:
- first_indices.setdefault(feature.font_signature, feature.index)
- main_font = min(
- font_counts,
- key=lambda signature: (-font_counts[signature], first_indices[signature]),
+
+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,
)
- anchors = [feature for feature in voters if feature.font_signature == main_font]
- body_height = max(feature.height for feature in anchors)
- full_height_anchors = [feature for feature in anchors if feature.height >= body_height * SCRIPT_BODY_FULL_HEIGHT_RATIO]
- return _ScriptBodyBand(
- center_y=max(feature.center_y for feature in full_height_anchors),
- height=body_height,
+ 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 _get_structure_script_role(
- open_feature: _ScriptCharFeature,
- close_feature: _ScriptCharFeature,
- body_band: _ScriptBodyBand,
-) -> _ScriptMarkRole | None:
- """按指定正文带判断成对括号是否构成同向缩小的结构角标。"""
- if (
- open_feature.height > body_band.height * SCRIPT_GEOMETRY_MAX_HEIGHT_RATIO
- or close_feature.height > body_band.height * SCRIPT_GEOMETRY_MAX_HEIGHT_RATIO
- ):
- return None
+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,
+ )
- open_offset = open_feature.center_y - body_band.center_y
- close_offset = close_feature.center_y - body_band.center_y
- minimum_offset = body_band.height * SCRIPT_STRUCTURE_MIN_OFFSET_RATIO
- if open_offset * close_offset <= 0 or min(abs(open_offset), abs(close_offset)) < minimum_offset:
- return None
- return _get_script_role((open_offset + close_offset) / 2)
+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 _is_numeric_square_reference(
+
+def _script_cluster_has_consistent_displacement(
features: list[_ScriptCharFeature],
- open_index: int,
- close_index: int,
+ cluster: _ScriptBaselineCluster,
+ body_cluster: _ScriptBaselineCluster,
+ body_band: _ScriptBodyBand,
) -> bool:
- """判断成对方括号内部是否只包含数字及引用范围分隔符。"""
- if features[open_index].text not in SCRIPT_NUMERIC_REFERENCE_OPENERS:
+ """要求 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
- inner_text = [feature.text for feature in features[open_index + 1 : close_index]]
- return (
- bool(inner_text)
- and any(text.isdigit() for text in inner_text)
- and all(text.isdigit() or text in SCRIPT_NUMERIC_REFERENCE_SEPARATORS for text in inner_text)
+
+ 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 _collect_script_seeds(
+def _choose_script_body_band(
features: list[_ScriptCharFeature],
- body_band: _ScriptBodyBand,
-) -> list[_ScriptSeed]:
- """统一收集强几何、局部字体和成对结构三类上下标证据。"""
- seeds: list[_ScriptSeed] = []
- claimed_indices: set[int] = set()
+ 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
- for feature in features:
- is_symbol = len(feature.text) == 1 and unicodedata.category(feature.text).startswith("S")
- offset = feature.center_y - body_band.center_y
- if (
- feature.is_valid
- and (feature.text.isalnum() or is_symbol)
- and feature.height <= body_band.height * SCRIPT_GEOMETRY_MAX_HEIGHT_RATIO
- and abs(offset) >= body_band.height * SCRIPT_GEOMETRY_MIN_OFFSET_RATIO
- ):
- seeds.append(
- _ScriptSeed(
- start=feature.index,
- end=feature.index,
- role=_get_script_role(offset),
- evidence="geometry",
- )
+
+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,
)
- claimed_indices.add(feature.index)
+ and abs(feature.index - seed.index) <= SCRIPT_COMPONENT_SEED_MAX_POSITION_DISTANCE
+ for seed in seeded
+ )
+ if not nearby_seed:
+ roles[index] = "body"
+
- for index in range(1, len(features)):
+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]
- previous_feature = features[index - 1]
if (
- index in claimed_indices
- or index - 1 in claimed_indices
- or not feature.text.isalnum()
- or not previous_feature.text.isalnum()
- or not _is_script_identifier_char(feature.text)
- or not _is_script_identifier_char(previous_feature.text)
- or feature.font_signature == previous_feature.font_signature
- or feature.height > previous_feature.height * SCRIPT_COMPONENT_MAX_HEIGHT_RATIO
+ 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
-
- local_offset = feature.center_y - previous_feature.center_y
- minimum_offset = previous_feature.height * SCRIPT_TYPOGRAPHY_MIN_LOCAL_OFFSET_RATIO
- if abs(local_offset) >= minimum_offset:
- seeds.append(
- _ScriptSeed(
- start=index,
- end=index,
- role=_get_script_role(local_offset),
- evidence="typography",
- protected_body_indices=frozenset({index - 1}),
- )
- )
- claimed_indices.add(index)
-
- bracket_stack: list[tuple[int, str]] = []
- main_font_body_band = _estimate_main_font_body_band(features)
- for feature in features:
- if feature.text in SCRIPT_BRACKET_PAIRS:
- bracket_stack.append((feature.index, feature.text))
+ 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
- if not bracket_stack or feature.text != SCRIPT_BRACKET_PAIRS[bracket_stack[-1][1]]:
+ tight_ratio = feature.tight_height / max(reference.tight_height, 1e-6)
+ if tight_ratio > SCRIPT_CONSENSUS_TIGHT_HEIGHT_RATIO:
continue
- open_index, _open_text = bracket_stack.pop()
- open_feature = features[open_index]
- if not open_feature.is_valid or not feature.is_valid:
+ 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 = _get_structure_script_role(open_feature, feature, body_band)
- if (
- role is None
- and main_font_body_band is not None
- and _is_numeric_square_reference(features, open_index, feature.index)
+ 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
+ )
):
- role = _get_structure_script_role(open_feature, feature, main_font_body_band)
- if role is None:
continue
+ roles[index] = role
- seeds.append(
- _ScriptSeed(
- start=open_index,
- end=feature.index,
- role=role,
- evidence="structure",
- )
- )
- return seeds
+
+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],
- body_band: _ScriptBodyBand,
- seeds: list[_ScriptSeed],
-) -> list[_ScriptRole]:
- """线性划分同侧连续组件,只有包含高置信种子的组件才输出上下标。"""
- seed_roles: dict[int, _ScriptMarkRole] = {}
- protected_body_indices: set[int] = set()
- for seed in seeds:
- protected_body_indices.update(seed.protected_body_indices)
- for index in range(seed.start, seed.end + 1):
- seed_roles[index] = seed.role
-
- minimum_offset = body_band.height * SCRIPT_COMPONENT_MIN_OFFSET_RATIO
- maximum_height = body_band.height * SCRIPT_COMPONENT_MAX_HEIGHT_RATIO
- candidate_roles: list[_ScriptMarkRole | None] = []
- for feature in features:
- if feature.index in seed_roles:
- candidate_roles.append(seed_roles[feature.index])
+ 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 (
- feature.index in protected_body_indices
- or not feature.is_valid
+ 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.height > maximum_height
+ or feature.text in CONTROL_LINE_BREAK_CHARS
):
- candidate_roles.append(None)
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"
- offset = feature.center_y - body_band.center_y
- if abs(offset) < minimum_offset:
- candidate_roles.append(None)
- else:
- candidate_roles.append(_get_script_role(offset))
+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_body_indices = protected_body_indices or set()
+ features = _build_script_features(
+ chars,
+ tight_bboxes,
+ origins,
+ protected_body_indices,
+ )
roles: list[_ScriptRole] = ["body"] * len(features)
- component_start = 0
- while component_start < len(features):
- component_role = candidate_roles[component_start]
- if component_role is None:
- component_start += 1
- continue
-
- component_end = component_start + 1
- while component_end < len(features) and candidate_roles[component_end] == component_role:
- component_end += 1
- if any(index in seed_roles for index in range(component_start, component_end)):
- roles[component_start:component_end] = [component_role] * (component_end - component_start)
- component_start = component_end
+ for component_indices in _split_script_visual_components(features):
+ _assign_script_components(
+ features,
+ component_indices,
+ protected_body_indices,
+ roles,
+ )
return roles
-def _classify_char_script_roles(chars: list[Char], char_metrics: list[dict[str, float]]) -> list[str]:
- """按字符特征、正文带、证据和连续组件四步识别上下标。"""
- features = _build_script_features(chars, char_metrics)
- body_band = _estimate_script_body_band(features)
- if body_band is None or body_band.height <= 0:
- return ["body"] * len(chars)
- seeds = _collect_script_seeds(features, body_band)
- return _assign_script_components(features, body_band, seeds)
-
-
def _append_script_wrapped_text(parts: list[str], role: str | None, text: str) -> None:
"""把连续同类上下标文本包裹成 HTML 标签,正文保持原样。"""
if not text:
@@ -955,9 +1371,12 @@ def _compose_overlapping_spacing_diacritic(base: Char, modifier: Char) -> Char |
return cast(Char, merged)
-def _merge_overlapping_spacing_diacritics(chars: list[Char]) -> list[Char]:
- """合并字符流中位于基字符前后且几何重叠的 spacing diacritic。"""
+def _merge_overlapping_spacing_diacritics_with_protection(
+ chars: list[Char],
+) -> tuple[list[Char], set[int]]:
+ """合并 spacing diacritic,并返回必须保持正文角色的合成字符位置。"""
merged_chars: list[Char] = []
+ protected_body_indices: set[int] = set()
cursor = 0
while cursor < len(chars):
current = chars[cursor]
@@ -969,14 +1388,26 @@ def _merge_overlapping_spacing_diacritics(chars: list[Char]) -> list[Char]:
merged = _compose_overlapping_spacing_diacritic(current, following)
if merged is not None:
merged_chars.append(merged)
+ protected_body_indices.add(len(merged_chars) - 1)
cursor += 2
continue
merged_chars.append(current)
cursor += 1
+ return merged_chars, protected_body_indices
+
+
+def _merge_overlapping_spacing_diacritics(chars: list[Char]) -> list[Char]:
+ """兼容调用方:只返回合并后的 spacing diacritic 字符流。"""
+ merged_chars, _protected_body_indices = _merge_overlapping_spacing_diacritics_with_protection(chars)
return merged_chars
-def chars_to_content(span: _AnalyzeSpan) -> None:
+def chars_to_content(
+ span: _AnalyzeSpan,
+ *,
+ tight_bboxes: dict[int, BBox] | None = None,
+ origins: dict[int, tuple[float, float]] | None = None,
+) -> None:
"""将 Span 内字符重建为文本,并合并连续的上标、下标片段。"""
span.metadata.pop(PDF_NATIVE_SCRIPT_MARKUP_KEY, None)
# 检查span中的char是否为空
@@ -985,14 +1416,19 @@ def chars_to_content(span: _AnalyzeSpan) -> None:
# 大多数情况下 char 已按 PDF 原始顺序进入,只有乱序时才排序。
if any(chars[idx]["char_idx"] > chars[idx + 1]["char_idx"] for idx in range(len(chars) - 1)):
chars = sorted(chars, key=lambda x: x["char_idx"])
- chars = _merge_overlapping_spacing_diacritics(chars)
+ chars, protected_body_indices = _merge_overlapping_spacing_diacritics_with_protection(chars)
char_metrics = _get_char_bbox_metrics_list(chars)
# Calculate the width of each character
char_widths = [metrics["width"] for metrics in char_metrics]
# Calculate the median width
median_width = statistics.median(char_widths)
- script_roles = _classify_char_script_roles(chars, char_metrics)
+ script_roles = _classify_char_script_roles(
+ chars,
+ tight_bboxes=tight_bboxes or {},
+ origins=origins or {},
+ protected_body_indices=protected_body_indices,
+ )
role_text_parts = []
for idx, char1 in enumerate(chars):
diff --git a/mineru/backend/analysis/pdf/text/styles.py b/mineru/backend/analysis/pdf/text/styles.py
index 1f66d4fe..34bdf237 100644
--- a/mineru/backend/analysis/pdf/text/styles.py
+++ b/mineru/backend/analysis/pdf/text/styles.py
@@ -5,9 +5,7 @@ from __future__ import annotations
from typing import Any, Sequence
-from pdftext.schema import Char
-
-from .....model.flash.pdf.document import PDFPage, get_lines_from_chars
+from .....model.flash.pdf.document import PDFPage, PDFPageTextGeometry, get_lines_from_chars
from .....model.flash.pdf.text_styles import (
PDFTextLinkLine,
PDFTextStyleLine,
@@ -19,10 +17,10 @@ from .....model.flash.pdf.text_styles import (
def build_pdf_native_visual_lines_and_styles(
pdf_page: PDFPage,
*,
- page_chars: list[Char] | None = None,
+ page_text_geometry: PDFPageTextGeometry | None = None,
supported_angles: Sequence[float] = (0.0,),
) -> tuple[
- list[Char],
+ PDFPageTextGeometry,
list[Any],
list[PDFTextStyleLine],
list[PDFTextLinkLine],
@@ -32,7 +30,8 @@ def build_pdf_native_visual_lines_and_styles(
# 延迟导入避免 Hybrid 模块初始化时提前加载完整 Flash PDF 流水线。
from .....model.flash.pdf.native_text import _build_native_line_items
- chars = page_chars if page_chars is not None else pdf_page.get_chars()
+ geometry = page_text_geometry if page_text_geometry is not None else pdf_page.get_chars_with_geometry()
+ chars = geometry.chars
line_items = _build_native_line_items(
get_lines_from_chars(chars),
tuple(float(value) for value in pdf_page.size),
@@ -47,7 +46,7 @@ def build_pdf_native_visual_lines_and_styles(
line_items,
pdf_page.get_link_annotations(),
)
- return chars, line_items, style_lines, link_lines
+ return geometry, line_items, style_lines, link_lines
__all__ = ["build_pdf_native_visual_lines_and_styles"]
diff --git a/mineru/backend/postprocess/legacy_schema_adapter.py b/mineru/backend/postprocess/legacy_schema_adapter.py
index 1b0e4098..a4296e01 100644
--- a/mineru/backend/postprocess/legacy_schema_adapter.py
+++ b/mineru/backend/postprocess/legacy_schema_adapter.py
@@ -23,11 +23,9 @@ from .inline import join_inline_spans
_VISUAL_PARENT_TYPES: frozenset[str] = frozenset(
{
"image",
- "image_block",
"table",
"chart",
"code",
- "algorithm",
}
)
@@ -52,7 +50,6 @@ _INLINE_CONTENT_BLOCK_TYPES: frozenset[str] = frozenset(
"code_footnote",
"caption",
"footnote",
- "algorithm",
"phonetic",
}
)
@@ -69,19 +66,14 @@ _STRING_CONTENT_BLOCK_TYPES: frozenset[str] = frozenset(
_BLOCK_TYPE_ALIASES: dict[str, str] = {
"abstract": "text",
- "vertical_text": "text",
"phonetic": "text",
- "formula_number": "text",
- "discarded": "aside_text",
"interline_equation": "equation",
- "image_block": "image",
- "algorithm_body": "code_body",
- "algorithm_caption": "code_caption",
- "algorithm_footnote": "code_footnote",
- "header_image": "image_body",
- "footer_image": "image_body",
}
+_SUPPORTED_BLOCK_TYPES: frozenset[str] = frozenset(
+ _VISUAL_PARENT_TYPES | _INLINE_CONTENT_BLOCK_TYPES | _STRING_CONTENT_BLOCK_TYPES | {"list", "index"}
+)
+
_INLINE_START_RE = re.compile(
r"<(?P<tag>eq|code|text|hyperlink|sup|sub|strong|b|em|i|s|u)(?P<attrs>\s[^<>]*?)?>",
re.IGNORECASE,
@@ -168,17 +160,16 @@ def _collect_blocks(
inherited: dict[str, Any] | None,
) -> None:
"""递归展平视觉父块,并把普通叶子转换为当前 raw block。"""
- source_type = str(block.get("type", "") or "")
+ block_type = _normalize_block_type(block)
nested = block.get("blocks")
- if source_type in _VISUAL_PARENT_TYPES and isinstance(nested, list) and nested:
- child_context = _visual_child_context(block, source_type, inherited)
+ if block_type in _VISUAL_PARENT_TYPES and isinstance(nested, list) and nested:
+ child_context = _visual_child_context(block, inherited)
for child in nested:
if not isinstance(child, dict):
raise ValueError("legacy visual block children must be dicts")
_collect_blocks(child, width, height, output, inherited=child_context)
return
- block_type = _normalize_block_type(block)
if block_type == "list" and isinstance(nested, list) and nested:
output.append(_convert_leaf_block(block, block_type, width, height, inherited))
output.extend(_flatten_nested_list_items(nested, width, height))
@@ -197,7 +188,6 @@ def _collect_blocks(
def _visual_child_context(
block: dict[str, Any],
- source_type: str,
inherited: dict[str, Any] | None,
) -> dict[str, Any]:
"""收集视觉父块上需要下沉到 body 的元数据。"""
@@ -205,7 +195,7 @@ def _visual_child_context(
context["bbox"] = block.get("bbox", context.get("bbox"))
sub_type = block.get("sub_type")
if not isinstance(sub_type, str) or not sub_type.strip():
- sub_type = "algorithm" if source_type == "algorithm" else None
+ sub_type = None
if sub_type:
context["sub_type"] = sub_type
if isinstance(block.get("guess_lang"), str) and block["guess_lang"].strip():
@@ -694,11 +684,14 @@ def _copy_leaf_metadata(
def _normalize_block_type(block: dict[str, Any]) -> str:
- """把 3.4.5 block discriminator 映射到当前 raw block 类型。"""
+ """把最终 3.4.5 discriminator 映射到当前 raw 类型并拒绝内部标签。"""
block_type = str(block.get("type", "") or "")
if block_type == "title":
return "doc_title" if block.get("level") == 1 else "paragraph_title"
- return _BLOCK_TYPE_ALIASES.get(block_type, block_type)
+ normalized = _BLOCK_TYPE_ALIASES.get(block_type, block_type)
+ if normalized not in _SUPPORTED_BLOCK_TYPES:
+ raise ValueError(f"unsupported MinerU 3.4.5 block type {block_type!r}; source reparse required")
+ return normalized
def _normalize_bbox(value: Any, width: float, height: float) -> tuple[float, float, float, float]:
diff --git a/mineru/model/flash/ofd/path.py b/mineru/model/flash/ofd/path.py
index 7f9605ca..7ca64d33 100644
--- a/mineru/model/flash/ofd/path.py
+++ b/mineru/model/flash/ofd/path.py
@@ -144,7 +144,10 @@ def build_axis_lines(
if boundary is None:
return []
boundary_page = transform_bbox(boundary, parent_transform)
- if boundary_page is None or bbox_intersection(boundary_page, parent_clip) is None:
+ if boundary_page is None:
+ return []
+ object_clip = bbox_intersection(boundary_page, parent_clip)
+ if object_clip is None:
return []
try:
width = max(0.1, float(style.get("LineWidth") or path_object.get("LineWidth") or 0.353))
@@ -155,28 +158,13 @@ def build_axis_lines(
)
extracted: list[AxisLine] = []
data = first_descendant(path_object, "AbbreviatedData")
- if data is not None:
- for first, second in _segments(element_text(data), object_transform, budget):
- line = _line_bbox(first, second, width)
- if line is None:
- continue
- line_bbox, orientation = line
- clipped = bbox_intersection(line_bbox, parent_clip)
- if clipped is not None:
- extracted.append(
- AxisLine(
- bbox=clipped,
- orientation=orientation,
- width=width,
- paint_order=paint_order,
- template_id=template_id,
- )
- )
- boundary_width = boundary_page[2] - boundary_page[0]
- boundary_height = boundary_page[3] - boundary_page[1]
- if not extracted and max(boundary_width, boundary_height) >= 5 * max(min(boundary_width, boundary_height), 0.01):
- orientation = "horizontal" if boundary_width >= boundary_height else "vertical"
- clipped = bbox_intersection(boundary_page, parent_clip)
+ segments = _segments(element_text(data), object_transform, budget) if data is not None else []
+ for first, second in segments:
+ line = _line_bbox(first, second, width)
+ if line is None:
+ continue
+ line_bbox, orientation = line
+ clipped = bbox_intersection(line_bbox, object_clip)
if clipped is not None:
extracted.append(
AxisLine(
@@ -187,6 +175,23 @@ def build_axis_lines(
template_id=template_id,
)
)
+ boundary_width = boundary_page[2] - boundary_page[0]
+ boundary_height = boundary_page[3] - boundary_page[1]
+ if (
+ not extracted
+ and not segments
+ and max(boundary_width, boundary_height) >= 5 * max(min(boundary_width, boundary_height), 0.01)
+ ):
+ orientation = "horizontal" if boundary_width >= boundary_height else "vertical"
+ extracted.append(
+ AxisLine(
+ bbox=object_clip,
+ orientation=orientation,
+ width=width,
+ paint_order=paint_order,
+ template_id=template_id,
+ )
+ )
if not extracted and parse_int(path_object.get("ID")) is None:
logger.debug("OFD_PATH_SKIPPED: path without stable ID produced no axis lines")
return extracted
diff --git a/mineru/model/flash/pdf/document.py b/mineru/model/flash/pdf/document.py
index d7c54b8e..32fcf753 100644
--- a/mineru/model/flash/pdf/document.py
+++ b/mineru/model/flash/pdf/document.py
@@ -71,6 +71,15 @@ class PDFPageImage:
self.scale = scale
+@dataclass(frozen=True, slots=True)
+class PDFPageTextGeometry:
+ """保存 Hybrid TXT 需要的原始字符、tight bbox 和视觉字符原点。"""
+
+ chars: list[Char]
+ tight_bboxes: dict[int, BBox]
+ origins: dict[int, tuple[float, float]]
+
+
@dataclass(frozen=True)
class PDFDrawingLine:
"""PDF 页面中可见的水平或竖直绘图线,坐标使用页面左上原点的 PDF point。"""
@@ -142,6 +151,10 @@ class PDFPage:
def get_chars(self) -> list[Char]:
return self.pdf_doc.get_page_chars(self._idx)
+ def get_chars_with_geometry(self) -> PDFPageTextGeometry:
+ """一次读取字符及 Hybrid TXT 匹配所需的额外几何。"""
+ return self.pdf_doc.get_page_chars_with_geometry(self._idx)
+
def get_drawing_lines(self) -> list[PDFDrawingLine]:
"""读取当前页已规范到视觉页面坐标的横竖 drawing。"""
@@ -380,23 +393,51 @@ class PDFDocument:
return cast(int, n_chars)
def get_page_chars(self, page_idx: int) -> list[Char]:
+ return self._get_page_text_geometry(page_idx, include_extended_geometry=False).chars
+
+ def get_page_chars_with_geometry(self, page_idx: int) -> PDFPageTextGeometry:
+ """一次读取字符、tight bbox 和字符原点,避免 Hybrid 重复打开 textpage。"""
+ return self._get_page_text_geometry(page_idx, include_extended_geometry=True)
+
+ def _get_page_text_geometry(
+ self,
+ page_idx: int,
+ *,
+ include_extended_geometry: bool,
+ ) -> PDFPageTextGeometry:
+ """在同一 PDFium textpage 生命周期内物化字符及可选扩展几何。"""
with self._open_page(page_idx) as page:
textpage = None
try:
textpage = page.get_textpage()
- page_bbox: list[float] = list(page.get_bbox())
+ raw_page_bbox: list[float] = list(page.get_bbox())
+ page_bbox = _normalize_pdf_page_bbox(tuple(raw_page_bbox))
page_rotation: int = 0
try:
page_rotation = page.get_rotation()
except Exception:
pass
- chars = get_chars(textpage, page_bbox, page_rotation)
+ chars = get_chars(textpage, raw_page_bbox, page_rotation)
chars = _deduplicate_pdftext_chars(chars)
chars = _ensure_legacy_chars(chars)
chars = _restore_pdfium_surrogate_pairs(chars, textpage)
+ chars = _deduplicate_near_identical_chars(chars)
+ if include_extended_geometry:
+ tight_bboxes, origins = _extract_page_char_extended_geometry(
+ textpage,
+ chars,
+ page_bbox,
+ page_rotation,
+ )
+ else:
+ tight_bboxes, origins = {}, {}
finally:
_try_close(textpage)
- return _deduplicate_near_identical_chars(chars)
+ return PDFPageTextGeometry(
+ chars=chars,
+ tight_bboxes=tight_bboxes,
+ origins=origins,
+ )
def get_page_lines(self, page_idx: int) -> list[Line]:
chars = self.get_page_chars(page_idx)
@@ -578,6 +619,101 @@ def _transform_drawing_point(
return x - left, top - y
+def _char_visual_bbox_from_pdfium(
+ left: float,
+ right: float,
+ bottom: float,
+ top: float,
+ page_bbox: BBox,
+ page_rotation: int,
+) -> BBox | None:
+ """把 PDFium 字符 user-space 框转换为合法视觉页面 bbox。"""
+ points = [
+ _transform_drawing_point(point, page_bbox, page_rotation)
+ for point in (
+ (left, bottom),
+ (left, top),
+ (right, bottom),
+ (right, top),
+ )
+ ]
+ bbox = (
+ min(point[0] for point in points),
+ min(point[1] for point in points),
+ max(point[0] for point in points),
+ max(point[1] for point in points),
+ )
+ if not all(math.isfinite(value) for value in bbox) or bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
+ return None
+ return bbox
+
+
+def _extract_page_char_extended_geometry(
+ textpage: pdfium.PdfTextPage,
+ chars: list[Char],
+ page_bbox: BBox,
+ page_rotation: int,
+) -> tuple[dict[int, BBox], dict[int, tuple[float, float]]]:
+ """逐字符读取 tight bbox 和 origin;单字符失败不影响其余文本。"""
+ tight_bboxes: dict[int, BBox] = {}
+ origins: dict[int, tuple[float, float]] = {}
+ textpage_raw = textpage.raw
+
+ for char in chars:
+ raw_char_idx = char.get("char_idx")
+ if isinstance(raw_char_idx, bool) or not isinstance(raw_char_idx, int):
+ continue
+
+ left = ctypes.c_double()
+ right = ctypes.c_double()
+ bottom = ctypes.c_double()
+ top = ctypes.c_double()
+ try:
+ has_tight_bbox = pdfium_c.FPDFText_GetCharBox(
+ textpage_raw,
+ raw_char_idx,
+ left,
+ right,
+ bottom,
+ top,
+ )
+ except Exception:
+ has_tight_bbox = False
+ if has_tight_bbox:
+ tight_bbox = _char_visual_bbox_from_pdfium(
+ left.value,
+ right.value,
+ bottom.value,
+ top.value,
+ page_bbox,
+ page_rotation,
+ )
+ if tight_bbox is not None:
+ tight_bboxes[raw_char_idx] = tight_bbox
+
+ origin_x = ctypes.c_double()
+ origin_y = ctypes.c_double()
+ try:
+ has_origin = pdfium_c.FPDFText_GetCharOrigin(
+ textpage_raw,
+ raw_char_idx,
+ origin_x,
+ origin_y,
+ )
+ except Exception:
+ has_origin = False
+ if has_origin:
+ origin = _transform_drawing_point(
+ (origin_x.value, origin_y.value),
+ page_bbox,
+ page_rotation,
+ )
+ if all(math.isfinite(value) for value in origin):
+ origins[raw_char_idx] = origin
+
+ return tight_bboxes, origins
+
+
def _multiply_pdf_matrices(
first: tuple[float, float, float, float, float, float],
second: tuple[float, float, float, float, float, float],
diff --git a/tests/unittest/test_flash_ofd.py b/tests/unittest/test_flash_ofd.py
index 28c51351..255c07bf 100644
--- a/tests/unittest/test_flash_ofd.py
+++ b/tests/unittest/test_flash_ofd.py
@@ -34,7 +34,7 @@ from mineru.model.flash.ofd.geometry import Affine, canonical_angle
from mineru.model.flash.ofd.images import build_image_item
from mineru.model.flash.ofd.models import MediaResource, OfdPageScene, ResourceRegistry
from mineru.model.flash.ofd.package import OfdPackage
-from mineru.model.flash.ofd.path import OfdPathBudget, _segments
+from mineru.model.flash.ofd.path import OfdPathBudget, _segments, build_axis_lines
from mineru.model.flash.ofd.reading_order import OfdReadingOrderProjector
from mineru.model.flash.ofd.resources import resolve_draw_param
from mineru.model.flash.ofd.text import FontMetricResolver, OfdTextBudget, build_text_lines
@@ -512,6 +512,47 @@ def test_ofd_path_rejects_unexpected_numeric_tokens_without_hanging() -> None:
assert _segments("M 0 0 L 10 0", Affine(), OfdPathBudget()) == [((0.0, 0.0), (10.0, 0.0))]
+def test_ofd_path_segments_are_clipped_to_object_boundary() -> None:
+ """验证完全越界路径被丢弃,穿越路径裁到对象与父级裁剪交集。"""
+ outside = etree.fromstring(
+ b'<PathObject ID="1" Boundary="10 10 10 1" LineWidth="0.2">'
+ b"<AbbreviatedData>M 20 0.5 L 30 0.5</AbbreviatedData></PathObject>"
+ )
+ outside_lines = build_axis_lines(
+ outside,
+ parent_transform=Affine(),
+ parent_clip=(0.0, 0.0, 100.0, 100.0),
+ paint_order=0,
+ template_id=None,
+ budget=OfdPathBudget(),
+ )
+ assert outside_lines == []
+
+ cases = [
+ ("M -5 5 L 15 5", "horizontal", (12.0, 14.9, 18.0, 15.1)),
+ ("M 5 -5 L 5 15", "vertical", (14.9, 12.0, 15.1, 18.0)),
+ ]
+ for data, orientation, expected_bbox in cases:
+ crossing = etree.fromstring(
+ (
+ '<PathObject ID="2" Boundary="10 10 10 10" LineWidth="0.2">'
+ f"<AbbreviatedData>{data}</AbbreviatedData></PathObject>"
+ ).encode()
+ )
+ lines = build_axis_lines(
+ crossing,
+ parent_transform=Affine(),
+ parent_clip=(12.0, 12.0, 18.0, 18.0),
+ paint_order=0,
+ template_id=None,
+ budget=OfdPathBudget(),
+ )
+
+ assert len(lines) == 1
+ assert lines[0].orientation == orientation
+ assert lines[0].bbox == pytest.approx(expected_bbox)
+
+
def test_ofd_template_grid_recovers_table() -> None:
"""验证模板路径和页面文字共同恢复高置信全线表。"""
paths = "".join(
diff --git a/tests/unittest/test_legacy_schema_adapter.py b/tests/unittest/test_legacy_schema_adapter.py
index 7fb22e18..39895631 100644
--- a/tests/unittest/test_legacy_schema_adapter.py
+++ b/tests/unittest/test_legacy_schema_adapter.py
@@ -186,6 +186,105 @@ def test_legacy_adapter_normalizes_bbox_and_block_aliases() -> None:
_current_pages([raw_page])
+def test_legacy_adapter_keeps_only_final_middle_json_aliases() -> None:
+ """验证最终 3.4.5 仍会序列化的三个旧类型继续转换。"""
+ page = {
+ "page_size": [100, 100],
+ "preproc_blocks": [
+ {"type": "abstract", "bbox": [0, 0, 100, 20], "lines": [_legacy_line("Abstract")]},
+ {"type": "phonetic", "bbox": [0, 30, 100, 50], "lines": [_legacy_line("phonetic")]},
+ {
+ "type": "interline_equation",
+ "bbox": [0, 60, 100, 80],
+ "lines": [
+ {
+ "bbox": [0, 60, 100, 80],
+ "spans": [{"type": "interline_equation", "content": "x=1"}],
+ }
+ ],
+ },
+ ],
+ "discarded_blocks": [],
+ }
+
+ raw_page = legacy_page_to_model_list(page)
+
+ assert [block["type"] for block in raw_page] == ["text", "text", "equation"]
+ assert raw_page[0]["content"][0]["content"] == "Abstract"
+ assert raw_page[1]["content"][0]["content"] == "phonetic"
+ assert raw_page[2]["content"] == "x=1"
+ _current_pages([raw_page])
+
+
+ "block_type",
+ [
+ "vertical_text",
+ "formula_number",
+ "discarded",
+ "image_block",
+ "algorithm",
+ "algorithm_body",
+ "algorithm_caption",
+ "algorithm_footnote",
+ "header_image",
+ "footer_image",
+ ],
+)
+def test_legacy_adapter_rejects_pre_middle_json_block_types(block_type: str) -> None:
+ """验证 finalize 前布局、raw model 与 Content List 类型要求源文件重解析。"""
+ block = {
+ "type": block_type,
+ "bbox": [0, 0, 100, 20],
+ "lines": [_legacy_line("internal")],
+ }
+ if block_type in {"image_block", "algorithm"}:
+ block["blocks"] = [{"type": "text", "bbox": [0, 0, 100, 20], "lines": [_legacy_line("nested")]}]
+ page = {
+ "page_size": [100, 100],
+ "preproc_blocks": [block],
+ "discarded_blocks": [],
+ }
+
+ with pytest.raises(ValueError, match=rf"{block_type!s}.*source reparse"):
+ legacy_page_to_model_list(page)
+
+
+def test_legacy_adapter_preserves_canonical_image_and_auxiliary_blocks() -> None:
+ """验证规范 image 视觉块及 header/footer 辅助块不会提升为正文图片。"""
+ page = {
+ "page_size": [100, 100],
+ "preproc_blocks": [
+ {
+ "type": "image",
+ "bbox": [10, 20, 90, 80],
+ "blocks": [
+ {
+ "type": "image_body",
+ "bbox": [10, 20, 90, 80],
+ "lines": [
+ {
+ "bbox": [10, 20, 90, 80],
+ "spans": [{"type": "image", "image_path": "images/body.png"}],
+ }
+ ],
+ }
+ ],
+ }
+ ],
+ "discarded_blocks": [
+ {"type": "header", "bbox": [0, 0, 100, 10], "lines": [_legacy_line("Header")]},
+ {"type": "footer", "bbox": [0, 90, 100, 100], "lines": [_legacy_line("Footer")]},
+ ],
+ }
+
+ pages = _current_pages([legacy_page_to_model_list(page)])
+
+ assert [block.type for block in pages[0].blocks] == [BlockType.IMAGE, BlockType.HEADER, BlockType.FOOTER]
+ image = pages[0].blocks[0]
+ assert image.content[0].image_path == "images/body.png"
+
+
def test_legacy_adapter_recovers_pdf_list_items_from_line_flags() -> None:
"""验证旧 PDF list 的物理行重新生成当前列表文本子块。"""
page = {
diff --git a/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.py
index 4f5cccaa..65460533 100644
--- a/tests/unittest/test_pdf_analyze_block_content.py
+++ b/tests/unittest/test_pdf_analyze_block_content.py
@@ -13,6 +13,7 @@ from mineru.backend.analysis.pdf import constants, layout, normalization, ocr, p
from mineru.backend.analysis.pdf.text import content as text_content
from mineru.backend.analysis.pdf.text.models import _AnalyzeLine, _AnalyzeSpan
from mineru.backend.postprocess import document as postprocess_document
+from mineru.model.flash.pdf.document import PDFPageTextGeometry
from mineru.types import RAW_ALGORITHM, RAW_CAPTION, RAW_FOOTNOTE
from mineru.backend.analysis.pdf.text.native import (
POST_OCR_FALLBACK_CONTENT_KEY,
@@ -441,7 +442,7 @@ def test_fill_window_batches_txt_post_ocr_before_page_content(monkeypatch: pytes
monkeypatch.setattr(
text_content,
"build_pdf_native_visual_lines_and_styles",
- lambda *_args, **_kwargs: ([], [], [], []),
+ lambda *_args, **_kwargs: (PDFPageTextGeometry([], {}, {}), [], [], []),
)
monkeypatch.setattr(
text_content,
diff --git a/tests/unittest/test_pdf_document.py b/tests/unittest/test_pdf_document.py
index 9dec77cd..6a30a122 100644
--- a/tests/unittest/test_pdf_document.py
+++ b/tests/unittest/test_pdf_document.py
@@ -34,6 +34,16 @@ def test_pdf_page_exposes_path_infos_without_raw_pdfium_access() -> None:
document.get_page_path_infos.assert_called_once_with(3)
+def test_pdf_page_exposes_chars_with_geometry_without_raw_pdfium_access() -> None:
+ """验证 PDFPage 代理扩展字符几何并保留页索引。"""
+ document = MagicMock()
+ expected = pdf_document.PDFPageTextGeometry(chars=[], tight_bboxes={}, origins={})
+ document.get_page_chars_with_geometry.return_value = expected
+
+ assert pdf_document.PDFPage(document, 4).get_chars_with_geometry() is expected
+ document.get_page_chars_with_geometry.assert_called_once_with(4)
+
+
def _build_drawing_pdf() -> bytes:
"""构造包含描边、填充细矩形、相邻线段、Form 矩阵和斜线的测试 PDF。"""
output = BytesIO()
@@ -235,9 +245,7 @@ def _build_rotated_cropped_signature_pdf() -> bytes:
add_widget((20, 80, 40, 100), field_type="/Btn")
add_widget((20, 80, 40, 100), subtype="/Text")
page[NameObject("/Annots")] = annotations
- writer._root_object[NameObject("/AcroForm")] = DictionaryObject(
- {NameObject("/Fields"): form_fields}
- )
+ writer._root_object[NameObject("/AcroForm")] = DictionaryObject({NameObject("/Fields"): form_fields})
output = BytesIO()
writer.write(output)
@@ -267,9 +275,7 @@ def _build_rotated_cropped_link_pdf() -> bytes:
{
NameObject("/Type"): NameObject("/Annot"),
NameObject("/Subtype"): NameObject("/Link"),
- NameObject("/Rect"): ArrayObject(
- [FloatObject(value) for value in rect]
- ),
+ NameObject("/Rect"): ArrayObject([FloatObject(value) for value in rect]),
NameObject("/A"): DictionaryObject(
{
NameObject("/S"): NameObject("/URI"),
@@ -279,9 +285,7 @@ def _build_rotated_cropped_link_pdf() -> bytes:
}
)
if quad_points is not None:
- annotation[NameObject("/QuadPoints")] = ArrayObject(
- [FloatObject(value) for value in quad_points]
- )
+ annotation[NameObject("/QuadPoints")] = ArrayObject([FloatObject(value) for value in quad_points])
if flags:
annotation[NameObject("/F")] = NumberObject(flags)
annotations.append(writer._add_object(annotation))
@@ -316,15 +320,11 @@ def _build_rotated_cropped_link_pdf() -> bytes:
{
NameObject("/Type"): NameObject("/Annot"),
NameObject("/Subtype"): NameObject("/Link"),
- NameObject("/Rect"): ArrayObject(
- [FloatObject(10), FloatObject(20)]
- ),
+ NameObject("/Rect"): ArrayObject([FloatObject(10), FloatObject(20)]),
NameObject("/A"): DictionaryObject(
{
NameObject("/S"): NameObject("/URI"),
- NameObject("/URI"): TextStringObject(
- "https://broken.example.com"
- ),
+ NameObject("/URI"): TextStringObject("https://broken.example.com"),
}
),
}
@@ -560,6 +560,119 @@ def test_pdf_document_does_not_expose_legacy_compat_hooks() -> None:
assert pdf_document.PDFDocument._pdf_doc.fset is None
+ ("rotation", "expected"),
+ [
+ (0, (10.0, 150.0, 30.0, 170.0)),
+ (90, (30.0, 10.0, 50.0, 30.0)),
+ (180, (70.0, 30.0, 90.0, 50.0)),
+ (270, (150.0, 70.0, 170.0, 90.0)),
+ ],
+)
+def test_char_visual_bbox_from_pdfium_applies_page_rotation(
+ rotation: int,
+ expected: tuple[float, float, float, float],
+) -> None:
+ """验证 tight char box 按非零 CropBox 和四种页面旋转转换。"""
+ assert (
+ pdf_document._char_visual_bbox_from_pdfium(
+ 20.0,
+ 40.0,
+ 50.0,
+ 70.0,
+ (10.0, 20.0, 110.0, 220.0),
+ rotation,
+ )
+ == expected
+ )
+
+
+def test_extract_page_char_extended_geometry_isolates_single_char_failures(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证 tight/origin 单字符失败或非法值不会影响同页其余字符。"""
+
+ class _FakeTextPage:
+ raw = object()
+
+ chars = [
+ {
+ "char": text,
+ "bbox": Bbox([float(index), 0.0, float(index + 1), 1.0]),
+ "rotation": 0.0,
+ "font": {},
+ "char_idx": index,
+ }
+ for index, text in enumerate("AB")
+ ]
+
+ def fake_get_char_box(
+ _textpage: object,
+ index: int,
+ left: Any,
+ right: Any,
+ bottom: Any,
+ top: Any,
+ ) -> bool:
+ """只为第一个字符返回合法 tight bbox。"""
+ if index != 0:
+ return False
+ left.value, right.value, bottom.value, top.value = 10.0, 15.0, 180.0, 190.0
+ return True
+
+ def fake_get_char_origin(
+ _textpage: object,
+ index: int,
+ origin_x: Any,
+ origin_y: Any,
+ ) -> bool:
+ """第二个字符返回非有限 origin,验证其被单独丢弃。"""
+ origin_x.value = 10.0 + index
+ origin_y.value = 180.0 if index == 0 else float("nan")
+ return True
+
+ monkeypatch.setattr(pdf_document.pdfium_c, "FPDFText_GetCharBox", fake_get_char_box)
+ monkeypatch.setattr(pdf_document.pdfium_c, "FPDFText_GetCharOrigin", fake_get_char_origin)
+
+ tight_bboxes, origins = pdf_document._extract_page_char_extended_geometry(
+ _FakeTextPage(), # type: ignore[arg-type]
+ chars, # type: ignore[arg-type]
+ (0.0, 0.0, 100.0, 200.0),
+ 0,
+ )
+
+ assert tight_bboxes == {0: (10.0, 10.0, 15.0, 20.0)}
+ assert origins == {0: (10.0, 20.0)}
+
+
+def test_get_page_chars_with_geometry_preserves_legacy_char_output() -> None:
+ """验证扩展读取不会改变既有字符文本、索引或 loose bbox。"""
+ output = BytesIO()
+ canvas = Canvas(output, pagesize=(120, 80))
+ canvas.drawString(10, 50, "Geometry A2")
+ canvas.save()
+
+ with pdf_document.PDFDocument(output.getvalue()) as document:
+ legacy_chars = document.get_page_chars(0)
+ geometry = document.get_page_chars_with_geometry(0)
+
+ def snapshot(chars: list[dict[str, Any]]) -> list[tuple[str, int, tuple[float, ...]]]:
+ """生成忽略第三方 bbox 容器类型的稳定字符快照。"""
+ return [
+ (
+ str(char.get("char", "")),
+ int(char.get("char_idx", -1)),
+ tuple(float(value) for value in char["bbox"]),
+ )
+ for char in chars
+ ]
+
+ assert snapshot(geometry.chars) == snapshot(legacy_chars) # type: ignore[arg-type]
+ visible_indices = {int(char["char_idx"]) for char in geometry.chars if str(char.get("char", "")).strip()}
+ assert visible_indices <= geometry.tight_bboxes.keys()
+ assert visible_indices <= geometry.origins.keys()
+
+
def test_restore_pdfium_surrogate_pairs_recovers_supplementary_unicode(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -586,12 +699,12 @@ def test_restore_pdfium_surrogate_pairs_recovers_supplementary_unicode(
"font": {},
"char_idx": char_idx,
}
- for char_idx, text in enumerate(["A", "\uFFFD", "\uFFFD", "\uFFFD", "\ud835", "B"])
+ for char_idx, text in enumerate(["A", "\ufffd", "\ufffd", "\ufffd", "\ud835", "B"])
]
restored = pdf_document._restore_pdfium_surrogate_pairs(chars, _FakeTextPage())
- assert [char["char"] for char in restored] == ["A", "𝜃", "\uFFFD", "\uFFFD", "B"]
+ assert [char["char"] for char in restored] == ["A", "𝜃", "\ufffd", "\ufffd", "B"]
assert [char["char_idx"] for char in restored] == [0, 1, 3, 4, 5]
diff --git a/tests/unittest/test_pdf_native_script_detection.py b/tests/unittest/test_pdf_native_script_detection.py
index 928f2f14..e422706c 100644
--- a/tests/unittest/test_pdf_native_script_detection.py
+++ b/tests/unittest/test_pdf_native_script_detection.py
@@ -1,6 +1,8 @@
from __future__ import annotations
import math
+import statistics
+from dataclasses import dataclass
from pathlib import Path
import pytest
@@ -8,30 +10,47 @@ from pdftext.schema import Bbox, Char
from mineru.backend.analysis.pdf.text import native
from mineru.backend.analysis.pdf.text.models import _AnalyzeSpan
-from mineru.model.flash.pdf.document import PDFDocument
+from mineru.model.flash.pdf.document import PDFDocument, get_lines_from_chars
from mineru.model.flash.pdf.text_styles import PDF_NATIVE_SCRIPT_MARKUP_KEY
-from mineru.types import ContentType
+from mineru.types import BBox, ContentType
_PROJECT_ROOT = Path(__file__).resolve().parents[2]
_DEMO_PDF_DIR = _PROJECT_ROOT / "demo" / "pdfs"
+_ZH_2_PDF = _DEMO_PDF_DIR / "中文论文2.pdf"
_FIXTURE_PDF_DIR = Path(__file__).resolve().parent / "pdfs"
_PDF_CONTROL_CHARS = {"\r", "\n", "\x02", "\ufffe", "\uffff"}
-def _lines_chars_containing(pdf_path: Path, page_index: int, probe: str) -> list[list[Char]]:
+@dataclass(frozen=True, slots=True)
+class _ScriptFixture:
+ """保存测试字符及对应 tight/origin side maps。"""
+
+ chars: list[Char]
+ tight_bboxes: dict[int, BBox]
+ origins: dict[int, tuple[float, float]]
+
+
+def _lines_chars_containing(pdf_path: Path, page_index: int, probe: str) -> list[_ScriptFixture]:
"""从真实 PDF 指定页中返回全部包含探针的物理行字符。"""
with PDFDocument(str(pdf_path)) as document:
+ geometry = document.get_page_chars_with_geometry(page_index)
matching_lines = []
- for line in document.get_page_lines(page_index):
+ for line in get_lines_from_chars(geometry.chars):
line_text = "".join(span["text"] for span in line["spans"])
line_text = "".join(char for char in line_text if char not in _PDF_CONTROL_CHARS)
if probe in line_text:
- matching_lines.append([char for span in line["spans"] for char in span.get("chars", [])])
+ matching_lines.append(
+ _ScriptFixture(
+ chars=[char for span in line["spans"] for char in span.get("chars", [])],
+ tight_bboxes=geometry.tight_bboxes,
+ origins=geometry.origins,
+ )
+ )
return matching_lines
-def _line_chars_containing(pdf_path: Path, page_index: int, probe: str) -> list[Char]:
+def _line_chars_containing(pdf_path: Path, page_index: int, probe: str) -> _ScriptFixture:
"""从真实 PDF 指定页中返回唯一包含探针的物理行字符。"""
matching_lines = _lines_chars_containing(pdf_path, page_index, probe)
@@ -39,28 +58,98 @@ def _line_chars_containing(pdf_path: Path, page_index: int, probe: str) -> list[
return matching_lines[0]
-def _contiguous_chars_containing(pdf_path: Path, page_index: int, probe: str) -> list[Char]:
+def _contiguous_chars_containing(pdf_path: Path, page_index: int, probe: str) -> _ScriptFixture:
"""忽略 PDF 控制字符后截取唯一连续探针,覆盖视觉同行但内部带换行的文本。"""
with PDFDocument(str(pdf_path)) as document:
- visible_chars = [
- char for char in document[page_index].get_chars() if str(char.get("char", "")) not in _PDF_CONTROL_CHARS
- ]
+ geometry = document.get_page_chars_with_geometry(page_index)
+ visible_chars = [char for char in geometry.chars if str(char.get("char", "")) not in _PDF_CONTROL_CHARS]
page_text = "".join(str(char.get("char", "")) for char in visible_chars)
start_index = page_text.find(probe)
assert start_index >= 0, (pdf_path, page_index, probe)
assert page_text.find(probe, start_index + 1) < 0, (pdf_path, page_index, probe)
- return visible_chars[start_index : start_index + len(probe)]
+ return _ScriptFixture(
+ chars=visible_chars[start_index : start_index + len(probe)],
+ tight_bboxes=geometry.tight_bboxes,
+ origins=geometry.origins,
+ )
+
+
+def _synthetic_fixture(
+ chars: list[Char],
+ *,
+ tight_heights: dict[int, float] | None = None,
+ origin_ys: dict[int, float] | None = None,
+) -> _ScriptFixture:
+ """从 loose 测试字符构造可覆盖 tight 高度和 origin 的几何 fixture。"""
+ tight_heights = tight_heights or {}
+ origin_ys = origin_ys or {}
+ tight_bboxes = {}
+ origins = {}
+ for char in chars:
+ char_idx = int(char["char_idx"])
+ bbox = tuple(float(item) for item in char["bbox"])
+ center_x = (bbox[0] + bbox[2]) / 2
+ center_y = (bbox[1] + bbox[3]) / 2
+ tight_height = tight_heights.get(char_idx, bbox[3] - bbox[1])
+ tight_bboxes[char_idx] = (
+ bbox[0],
+ center_y - tight_height / 2,
+ bbox[2],
+ center_y + tight_height / 2,
+ )
+ origins[char_idx] = (center_x, origin_ys.get(char_idx, center_y))
+ return _ScriptFixture(
+ chars=chars,
+ tight_bboxes=tight_bboxes,
+ origins=origins,
+ )
-def _render_chars(chars: list[Char]) -> str:
+def _tight_only_span_bbox(fixture: _ScriptFixture) -> BBox:
+ """构造真实 tight 字形可命中、异常 loose 字体框完全无法命中的窄 Span。"""
+ tight_boxes = [fixture.tight_bboxes[int(char["char_idx"])] for char in fixture.chars]
+ center_y = statistics.median((bbox[1] + bbox[3]) / 2 for bbox in tight_boxes)
+ x0 = min(bbox[0] for bbox in tight_boxes) - 0.5
+ x1 = max(bbox[2] for bbox in tight_boxes) + 0.5
+ for quarter_points in range(16, 161):
+ height = quarter_points / 4
+ span_bbox = (x0, center_y - height / 2, x1, center_y + height / 2)
+ tight_matches = [
+ native.calculate_char_in_span(
+ tight_bbox,
+ span_bbox,
+ str(char["char"]),
+ )
+ for char, tight_bbox in zip(fixture.chars, tight_boxes)
+ ]
+ loose_matches = [
+ native.calculate_char_in_span(
+ tuple(float(value) for value in char["bbox"]),
+ span_bbox,
+ str(char["char"]),
+ )
+ for char in fixture.chars
+ ]
+ if all(tight_matches) and not any(loose_matches):
+ return span_bbox
+ raise AssertionError("未找到可复现 loose 字体框偏移的 tight-only Span")
+
+
+def _render_chars(value: list[Char] | _ScriptFixture) -> str:
"""使用生产 chars_to_content 路径重建字符内容和上下标标签。"""
+ fixture = value if isinstance(value, _ScriptFixture) else _synthetic_fixture(value)
+ chars = fixture.chars
span = _AnalyzeSpan(
type=ContentType.TEXT,
bbox=(0.0, 0.0, 1.0, 1.0),
metadata={"chars": chars},
)
- native.chars_to_content(span)
+ native.chars_to_content(
+ span,
+ tight_bboxes=fixture.tight_bboxes,
+ origins=fixture.origins,
+ )
return span.content
@@ -125,6 +214,164 @@ def test_span_fill_restores_19_degree_sheared_text(
assert native._get_chars_for_span_fill([body, sheared]) == [body, sheared]
+def _fillable_span(bbox: tuple[float, float, float, float]) -> _AnalyzeSpan:
+ """构造已初始化字符容器的可回填文本 Span。"""
+ return _AnalyzeSpan(
+ type=ContentType.TEXT,
+ bbox=bbox,
+ metadata={
+ "chars": [],
+ "height": bbox[3] - bbox[1],
+ "width": bbox[2] - bbox[0],
+ },
+ )
+
+
+def test_span_fill_prefers_tight_bbox_over_inflated_loose_bbox() -> None:
+ """验证异常 loose 中心落入下一行时仍按 tight bbox 归属正确行。"""
+ first = _fillable_span((10.0, 10.0, 80.0, 20.0))
+ second = _fillable_span((10.0, 22.0, 80.0, 32.0))
+ chars = [
+ {
+ "char": text,
+ "bbox": Bbox([12.0 + index * 6.0, 13.0, 18.0 + index * 6.0, 35.0]),
+ "rotation": 0.0,
+ "font": {},
+ "char_idx": index,
+ }
+ for index, text in enumerate("gpySource")
+ ]
+ tight_bboxes = {index: (12.0 + index * 6.0, 12.0, 18.0 + index * 6.0, 19.0) for index in range(len(chars))}
+ origins = {index: (15.0 + index * 6.0, 19.0) for index in range(len(chars))}
+
+ native.fill_char_in_spans(
+ [first, second],
+ chars, # type: ignore[arg-type]
+ 10.0,
+ tight_bboxes=tight_bboxes,
+ origins=origins,
+ )
+
+ assert first.content == "gpySource"
+ assert second.content == ""
+
+
+ ("page_index", "probe"),
+ [
+ pytest.param(0, "providing", id="page-1-providing"),
+ pytest.param(10, "Source", id="page-11-source"),
+ pytest.param(10, "Hypothesis", id="page-11-hypothesis"),
+ pytest.param(10, "Reference", id="page-11-reference"),
+ pytest.param(10, "BLEU", id="page-11-bleu"),
+ pytest.param(10, "ROUGE", id="page-11-rouge"),
+ pytest.param(16, "generalisation", id="page-17-generalisation"),
+ ],
+)
+def test_zh2_tight_bbox_restores_words_rejected_by_loose_bbox(
+ page_index: int,
+ probe: str,
+) -> None:
+ """验证中文论文2真实字体框中 loose 全部失配时 tight-first 仍恢复完整英文词。"""
+ fixture = _contiguous_chars_containing(_ZH_2_PDF, page_index, probe)
+ span_bbox = _tight_only_span_bbox(fixture)
+ loose_matches = [
+ native.calculate_char_in_span(
+ tuple(float(value) for value in char["bbox"]),
+ span_bbox,
+ str(char["char"]),
+ )
+ for char in fixture.chars
+ ]
+ span = _fillable_span(span_bbox)
+
+ native.fill_char_in_spans(
+ [span],
+ fixture.chars,
+ span_bbox[3] - span_bbox[1],
+ tight_bboxes=fixture.tight_bboxes,
+ origins=fixture.origins,
+ )
+
+ assert not any(loose_matches)
+ assert span.content == probe
+
+
+def test_span_fill_uses_loose_bbox_when_tight_punctuation_does_not_match() -> None:
+ """验证 tight 标点未命中时继续使用原首尾标点 loose 回退。"""
+ span = _fillable_span((10.0, 10.0, 30.0, 20.0))
+ char = {
+ "char": ".",
+ "bbox": Bbox([27.0, 12.0, 31.0, 18.0]),
+ "rotation": 0.0,
+ "font": {},
+ "char_idx": 0,
+ }
+
+ native.fill_char_in_spans(
+ [span],
+ [char], # type: ignore[list-item]
+ 10.0,
+ tight_bboxes={0: (40.0, 12.0, 41.0, 18.0)},
+ origins={0: (27.0, 18.0)},
+ )
+
+ assert span.content == "."
+
+
+def test_span_fill_attaches_whitespace_to_tight_owned_neighbors() -> None:
+ """验证空格跟随两侧 tight 字符进入同一 Span,而不是留在旧的重叠 Span。"""
+ first = _fillable_span((0.0, 0.0, 12.0, 20.0))
+ closer = _fillable_span((0.0, 8.0, 12.0, 16.0))
+ chars = [
+ _script_char(0, "A", height=14.0, center_y=10.0),
+ _script_char(1, " ", height=6.0, center_y=6.0),
+ _script_char(2, "C", height=14.0, center_y=10.0),
+ ]
+ chars[0]["bbox"] = Bbox([0.0, 3.0, 5.0, 17.0])
+ chars[1]["bbox"] = Bbox([4.8, 6.0, 4.8, 6.0])
+ chars[2]["bbox"] = Bbox([5.0, 3.0, 10.0, 17.0])
+
+ native.fill_char_in_spans(
+ [first, closer],
+ chars,
+ 8.0,
+ tight_bboxes={
+ 0: (0.0, 10.0, 5.0, 14.0),
+ 1: (8.0, 10.0, 9.0, 14.0),
+ 2: (5.0, 10.0, 10.0, 14.0),
+ },
+ origins={index: (float(index), 14.0) for index in range(3)},
+ )
+
+ assert first.content == ""
+ assert closer.content == "A C"
+
+
+def test_span_fill_chooses_closest_tight_candidate_before_span_order() -> None:
+ """验证 tight bbox 同时命中重叠 Span 时按中心距离而非列表顺序归属。"""
+ farther = _fillable_span((10.0, 8.0, 30.0, 20.0))
+ closer = _fillable_span((10.0, 11.0, 30.0, 19.0))
+ char = {
+ "char": "A",
+ "bbox": Bbox([15.0, 8.0, 20.0, 24.0]),
+ "rotation": 0.0,
+ "font": {},
+ "char_idx": 0,
+ }
+
+ native.fill_char_in_spans(
+ [farther, closer],
+ [char], # type: ignore[list-item]
+ 10.0,
+ tight_bboxes={0: (15.0, 13.0, 20.0, 17.0)},
+ origins={0: (15.0, 17.0)},
+ )
+
+ assert farther.content == ""
+ assert closer.content == "A"
+
+
def test_weak_offset_component_without_seed_stays_body() -> None:
"""验证只有连续级弱偏移、没有高置信证据的组件不会产生标签。"""
chars = [
@@ -135,6 +382,57 @@ def test_weak_offset_component_without_seed_stays_body() -> None:
assert _render_chars(chars) == "Ax"
+def test_mixed_font_run_with_weak_dual_bbox_displacement_stays_body() -> None:
+ """验证字体框高度突变但 tight/origin 中心偏移不足时仍保持正文。"""
+ chars = [
+ _script_char(0, "中", height=10.0, center_y=10.0, font_name="CJK"),
+ _script_char(1, "S", height=20.0, center_y=12.4, font_name="Latin"),
+ _script_char(2, "o", height=20.0, center_y=12.4, font_name="Latin"),
+ ]
+ fixture = _ScriptFixture(
+ chars=chars,
+ tight_bboxes={
+ 0: (0.0, 5.0, 1.0, 15.0),
+ 1: (1.0, 8.8, 2.0, 13.8),
+ 2: (2.0, 8.8, 3.0, 13.8),
+ },
+ origins={0: (0.0, 10.0), 1: (1.0, 11.2), 2: (2.0, 11.2)},
+ )
+
+ assert _render_chars(fixture) == "中So"
+
+
+def test_isolated_punctuation_with_opposed_origin_stays_body() -> None:
+ """验证标点的 origin 与 bbox 中心方向冲突时不会独立成为角标种子。"""
+ chars = [
+ _script_char(0, "A", height=10.0, center_y=10.0),
+ _script_char(1, ":", height=5.0, center_y=13.0),
+ _script_char(2, "B", height=10.0, center_y=10.0),
+ ]
+ fixture = _ScriptFixture(
+ chars=chars,
+ tight_bboxes={
+ 0: (0.0, 5.0, 1.0, 15.0),
+ 1: (1.0, 11.0, 2.0, 15.0),
+ 2: (2.0, 5.0, 3.0, 15.0),
+ },
+ origins={0: (0.0, 10.0), 1: (1.0, 8.0), 2: (2.0, 10.0)},
+ )
+
+ assert _render_chars(fixture) == "A:B"
+
+
+def test_strong_isolated_symbol_with_three_consistent_signals_is_script() -> None:
+ """验证三类几何均强位移的孤立符号仍可独立识别为角标。"""
+ chars = [
+ _script_char(0, "A", height=10.0, center_y=10.0),
+ _script_char(1, "*", height=5.0, center_y=6.0),
+ _script_char(2, "B", height=10.0, center_y=10.0),
+ ]
+
+ assert _render_chars(chars) == "A<sup>*</sup>B"
+
+
def test_strong_geometry_seed_absorbs_same_side_punctuation() -> None:
"""验证强几何种子会把同侧连续标点纳入同一个上标组件。"""
chars = [
@@ -169,14 +467,43 @@ def test_script_markup_records_detector_ownership() -> None:
},
)
- native.chars_to_content(script_span)
- native.chars_to_content(body_span)
+ script_fixture = _synthetic_fixture(script_span.metadata["chars"])
+ body_fixture = _synthetic_fixture(body_span.metadata["chars"])
+ native.chars_to_content(
+ script_span,
+ tight_bboxes=script_fixture.tight_bboxes,
+ origins=script_fixture.origins,
+ )
+ native.chars_to_content(
+ body_span,
+ tight_bboxes=body_fixture.tight_bboxes,
+ origins=body_fixture.origins,
+ )
assert script_span.content == "A<sup>2</sup>"
assert script_span.metadata[PDF_NATIVE_SCRIPT_MARKUP_KEY] is True
assert PDF_NATIVE_SCRIPT_MARKUP_KEY not in body_span.metadata
+def test_missing_extended_geometry_keeps_all_characters_body() -> None:
+ """验证缺少 tight/origin 时宁可不标 style,也不恢复字体或文本猜测。"""
+ span = _AnalyzeSpan(
+ type=ContentType.TEXT,
+ bbox=(0.0, 0.0, 1.0, 1.0),
+ metadata={
+ "chars": [
+ _script_char(0, "R", height=10.0, center_y=10.0, font_name="Base"),
+ _script_char(1, "2", height=7.0, center_y=7.0, font_name="Suffix"),
+ ]
+ },
+ )
+
+ native.chars_to_content(span)
+
+ assert span.content == "R2"
+ assert PDF_NATIVE_SCRIPT_MARKUP_KEY not in span.metadata
+
+
def test_overlapping_spacing_ogonek_composes_demo2_author_name() -> None:
"""验证 demo2 原生字符流中与 e 重叠的 spacing ogonek 合成为 ę。"""
content = _render_pdf_line(_DEMO_PDF_DIR / "demo2.pdf", 0, "Kowalczuk")
@@ -197,8 +524,8 @@ def test_non_overlapping_spacing_ogonek_remains_literal() -> None:
assert [char["char"] for char in merged] == ["˛", "e"]
-def test_font_suffix_seed_keeps_its_base_character_body() -> None:
- """验证局部字体后缀只标记后缀,受保护的基字符不能被组件吸收。"""
+def test_tight_geometry_keeps_same_size_loose_base_character_body() -> None:
+ """验证 loose 高度接近时仍只根据 tight/origin 标记后缀。"""
chars = [
_script_char(0, "9", height=20.0, center_y=12.0),
_script_char(1, " ", height=0.0, center_y=12.0),
@@ -206,7 +533,13 @@ def test_font_suffix_seed_keeps_its_base_character_body() -> None:
_script_char(3, "2", height=10.5, center_y=8.5, font_name="Suffix"),
]
- assert _render_chars(chars) == "9 R<sup>2</sup>"
+ fixture = _synthetic_fixture(
+ chars,
+ tight_heights={3: 7.0},
+ origin_ys={2: 10.0, 3: 8.5},
+ )
+
+ assert _render_chars(fixture) == "9 R<sup>2</sup>"
@pytest.mark.parametrize(
@@ -242,8 +575,8 @@ def test_cjk_font_boundary_does_not_seed_script_component(
assert _render_chars(chars) == expected
-def test_shifted_brackets_seed_the_complete_reference_component() -> None:
- """验证成对缩小括号会把内部数字整体作为结构上标证据。"""
+def test_shifted_reference_geometry_marks_the_complete_component() -> None:
+ """验证不读取括号语义也会把同基线引用整体标记为上标。"""
chars = [
_script_char(0, "依", height=10.0, center_y=10.0),
_script_char(1, "[", height=7.0, center_y=7.0),
@@ -252,7 +585,13 @@ def test_shifted_brackets_seed_the_complete_reference_component() -> None:
_script_char(4, "。", height=10.0, center_y=10.0),
]
- assert _render_chars(chars) == "依<sup>[1]</sup>。"
+ fixture = _synthetic_fixture(
+ chars,
+ tight_heights={1: 6.0, 2: 6.5, 3: 6.0},
+ origin_ys={0: 10.0, 1: 7.0, 2: 7.0, 3: 7.0, 4: 10.0},
+ )
+
+ assert _render_chars(fixture) == "依<sup>[1]</sup>。"
@pytest.mark.parametrize(
@@ -300,6 +639,34 @@ def test_shifted_brackets_seed_the_complete_reference_component() -> None:
("H<sub>2</sub>-antagonist",),
id="medical-subscript",
),
+ pytest.param(
+ "2407.00079v4_origi-10.pdf",
+ 0,
+ "7: Tqueue ←",
+ ("T<sub>queue</sub>",),
+ id="algorithm-variable-subscript",
+ ),
+ pytest.param(
+ "demo2.pdf",
+ 1,
+ "where ∆g(p, q) is",
+ ("∆<sub>g</sub>(p, q)", "∆<sub>c</sub>(p, q)"),
+ id="delta-subscripts",
+ ),
+ pytest.param(
+ "demo3.pdf",
+ 4,
+ "same as BERTBASE and BERTLARGE",
+ ("BERT<sub>BASE</sub>", "BERT<sub>LARGE</sub>"),
+ id="model-name-subscripts",
+ ),
+ pytest.param(
+ "demo4.pdf",
+ 1,
+ "body mass index (BMI) were 71.75 kg and 25.3 kg/m2",
+ ("kg/m<sup>2</sup>",),
+ id="unit-superscript",
+ ),
pytest.param(
"中文论文.pdf",
0,
@@ -335,6 +702,13 @@ def test_shifted_brackets_seed_the_complete_reference_component() -> None:
("Stacking 模型(R<sup>2</sup>",),
id="same-size-font-suffix-after-tall-digits",
),
+ pytest.param(
+ "中文论文.pdf",
+ 1,
+ "扎兰屯段边坡,经烘干后测得干密度为1. 72 g⋅cm-3",
+ ("g⋅cm<sup>-3</sup>",),
+ id="cjk-unit-superscript",
+ ),
],
)
def test_real_pdf_scripts_keep_confirmed_markup(
@@ -393,6 +767,61 @@ def test_chinese_reference_line_only_marks_the_reference() -> None:
assert "<sub>" not in content
+ ("pdf_name", "page_index", "probe", "expected"),
+ [
+ pytest.param(
+ "mixed_elements_pages_03_06.pdf",
+ 0,
+ "0.26 µm (Fig. 1a)",
+ "0.26 µm (Fig. 1a)",
+ id="plain-micrometer-unit",
+ ),
+ pytest.param(
+ "demo2.pdf",
+ 2,
+ ") to O(ω).",
+ ") to O(ω).",
+ id="plain-complexity-notation",
+ ),
+ ],
+)
+def test_real_pdf_plain_text_does_not_gain_script_markup(
+ pdf_name: str,
+ page_index: int,
+ probe: str,
+ expected: str,
+) -> None:
+ """验证字体框或 glyph 形状差异不会给普通单位和复杂度记号加角标。"""
+ content = _render_pdf_line(_DEMO_PDF_DIR / pdf_name, page_index, probe)
+
+ assert expected in content
+ assert "<sup>" not in content and "<sub>" not in content
+
+
+ ("page_index", "probe", "expected"),
+ [
+ pytest.param(0, "providing", "providing", id="page-1-english-abstract"),
+ pytest.param(10, "Source", "Source", id="page-11-source"),
+ pytest.param(10, "Hypothesis", "Hypothesis", id="page-11-hypothesis"),
+ pytest.param(10, "Reference", "Reference", id="page-11-reference"),
+ pytest.param(10, "如 BLEU 和 ROUGE", "BLEU 和 ROUGE", id="page-11-metrics"),
+ pytest.param(16, "generalisation", "generalisation", id="page-17-reference"),
+ ],
+)
+def test_zh2_normal_english_runs_do_not_gain_script_markup(
+ page_index: int,
+ probe: str,
+ expected: str,
+) -> None:
+ """验证中文论文2中受字体框影响的普通英文 run 不会被误判成上下标。"""
+ content = _render_pdf_line(_ZH_2_PDF, page_index, probe)
+
+ assert expected in content
+ assert "<sup>" not in content and "<sub>" not in content
+
+
@pytest.mark.parametrize(
("probe", "minimum_font_count"),
[
@@ -418,7 +847,7 @@ def test_synthetic_cjk_plain_text_does_not_gain_script_tags(
probe,
)
contents = [_render_chars(chars) for chars in matching_lines]
- font_names = {str((char.get("font") or {}).get("name", "")) for chars in matching_lines for char in chars}
+ font_names = {str((char.get("font") or {}).get("name", "")) for fixture in matching_lines for char in fixture.chars}
assert contents
assert len(font_names) >= minimum_font_count
@@ -430,13 +859,23 @@ def test_rotated_powerpoint_page_keeps_all_plain_text_on_baseline() -> None:
pdf_path = _FIXTURE_PDF_DIR / "metabolic_pathway_page_3.pdf"
with PDFDocument(str(pdf_path)) as document:
page = document[0]
- page_chars = page.get_chars()
- lines = document.get_page_lines(0)
-
- rendered_lines = [_render_chars([char for span in line["spans"] for char in span.get("chars", [])]) for line in lines]
+ page_rotation = page.rotation
+ geometry = page.get_chars_with_geometry()
+ lines = get_lines_from_chars(geometry.chars)
+
+ rendered_lines = [
+ _render_chars(
+ _ScriptFixture(
+ chars=[char for span in line["spans"] for char in span.get("chars", [])],
+ tight_bboxes=geometry.tight_bboxes,
+ origins=geometry.origins,
+ )
+ )
+ for line in lines
+ ]
- assert page.rotation == 90
- assert any((char.get("font") or {}).get("name") == "CalifornianFB-Reg" for char in page_chars)
+ assert page_rotation == 90
+ assert any((char.get("font") or {}).get("name") == "CalifornianFB-Reg" for char in geometry.chars)
assert len(rendered_lines) == 33
assert rendered_lines[0] == "Energy Metabolism"
assert all("<sup>" not in content and "<sub>" not in content for content in rendered_lines)
diff --git a/tests/unittest/test_pdf_text_styles.py b/tests/unittest/test_pdf_text_styles.py
index 0ae7761d..b06099c3 100644
--- a/tests/unittest/test_pdf_text_styles.py
+++ b/tests/unittest/test_pdf_text_styles.py
@@ -27,7 +27,7 @@ from mineru.types import (
ModelJson,
PageInfo,
)
-from mineru.model.flash.pdf.document import PDFDocument, PDFLinkAnnotation
+from mineru.model.flash.pdf.document import PDFDocument, PDFLinkAnnotation, PDFPageTextGeometry
from mineru.model.flash.pdf.text_styles import (
PDF_FONT_FORCE_BOLD_FLAG,
PDF_FONT_ITALIC_FLAG,
@@ -2027,6 +2027,11 @@ def test_hybrid_txt_reuses_loaded_chars_and_applies_styles(
"""验证 Medium/High/XHigh 复用 chars,并应用允许的组合样式。"""
page_chars = [{"char": "d", "bbox": (10.0, 10.0, 16.0, 20.0), "char_idx": 0}]
+ page_text_geometry = PDFPageTextGeometry(
+ chars=page_chars, # type: ignore[arg-type]
+ tight_bboxes={0: (10.0, 10.0, 16.0, 20.0)},
+ origins={0: (10.0, 20.0)},
+ )
style_lines = [
PDFTextStyleLine(
(10.0, 10.0, 52.0, 20.0),
@@ -2049,8 +2054,8 @@ def test_hybrid_txt_reuses_loaded_chars_and_applies_styles(
0,
)
]
- build_styles = MagicMock(return_value=(page_chars, [], style_lines, link_lines))
- observed_chars: list[object] = []
+ build_styles = MagicMock(return_value=(page_text_geometry, [], style_lines, link_lines))
+ observed_geometry: list[object] = []
def fake_fill_native(
_pdf_page: object,
@@ -2059,11 +2064,11 @@ def test_hybrid_txt_reuses_loaded_chars_and_applies_styles(
_scale: object,
_page_size: object,
*,
- page_chars: object,
+ page_text_geometry: object,
) -> list[_AnalyzeSpan]:
- """记录传入原生回填的 chars,并返回稳定文本 span。"""
+ """记录传入原生回填的字符几何,并返回稳定文本 span。"""
- observed_chars.append(page_chars)
+ observed_geometry.append(page_text_geometry)
return [
_AnalyzeSpan(
type=ContentType.TEXT,
@@ -2118,7 +2123,7 @@ def test_hybrid_txt_reuses_loaded_chars_and_applies_styles(
MagicMock(),
)
- assert observed_chars == [page_chars]
+ assert observed_geometry == [page_text_geometry]
assert _span_snapshot(model_list[0][0]["content"]) == (
'<hyperlink><text style="bold,strikethrough">deleted</text><url>https://hybrid.example.test</url></hyperlink>'
)
@@ -2149,7 +2154,7 @@ def test_hybrid_txt_efforts_apply_dehyphenated_links(
monkeypatch.setattr(
text_content,
"build_pdf_native_visual_lines_and_styles",
- lambda *_args, **_kwargs: ([], [], [], link_lines),
+ lambda *_args, **_kwargs: (PDFPageTextGeometry([], {}, {}), [], [], link_lines),
)
monkeypatch.setattr(
text_content,
@@ -2377,3 +2382,4 @@ def test_native_span_fill_does_not_read_preloaded_page_chars_twice() -> None:
assert result == [span]
assert span.content == "deleted"
pdf_page.get_chars.assert_not_called()
+ pdf_page.get_chars_with_geometry.assert_not_called()