Skip to content

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

fix: unify native PDF script detection across efforts

myhloli5394960cf91b
diff --git a/mineru/backend/analysis/pdf/text/content.py b/mineru/backend/analysis/pdf/text/content.py
index d81dbb45..01ec8aa5 100644
--- a/mineru/backend/analysis/pdf/text/content.py
+++ b/mineru/backend/analysis/pdf/text/content.py
@@ -16,8 +16,10 @@ from .....model.flash.pdf.document import PDFPage, PDFPageTextGeometry, get_line
from .....model.flash.pdf.text_styles import (
PDF_NATIVE_SCRIPT_MARKUP_KEY,
PDFTextLinkLine,
+ PDFTextScriptLine,
PDFTextStyleLine,
apply_pdf_text_links,
+ apply_pdf_text_scripts,
apply_pdf_text_styles,
materialize_pdf_inline_spans,
)
@@ -143,6 +145,51 @@ def _build_page_text_formula_spans(
return page_spans
+def _get_page_inline_formula_regions(
+ page_inline_formula_list: list[dict[str, Any]],
+ page_size: tuple[float, float],
+ render_scale: float,
+) -> list[BBox]:
+ """把当前页 layout/MFR 行内公式统一转换成页面 point bbox。"""
+
+ return [
+ bbox
+ for formula in page_inline_formula_list
+ if (bbox := _sidecar_bbox_to_page_bbox(formula.get("bbox"), page_size, render_scale)) is not None
+ ]
+
+
+def _get_page_table_regions(
+ page_model_list: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[BBox]:
+ """把当前页模型表格 bbox 转成脚本行合并使用的页面 point 区域。"""
+
+ page_width, page_height = page_size
+ regions: list[BBox] = []
+ for block in page_model_list:
+ if block.get("type") != BlockType.TABLE:
+ continue
+ raw_bbox = block.get("bbox")
+ if not isinstance(raw_bbox, (list, tuple)) or len(raw_bbox) != 4:
+ continue
+ try:
+ bbox = tuple(float(value) for value in raw_bbox)
+ except (TypeError, ValueError):
+ continue
+ if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
+ continue
+ if all(0.0 <= value <= 1.0 for value in bbox):
+ bbox = (
+ bbox[0] * page_width,
+ bbox[1] * page_height,
+ bbox[2] * page_width,
+ bbox[3] * page_height,
+ )
+ regions.append(bbox)
+ return regions
+
+
def _fill_native_pdf_text_spans(
pdf_page: PDFPage,
page_spans: list[_AnalyzeSpan],
@@ -151,6 +198,7 @@ def _fill_native_pdf_text_spans(
page_size: tuple[float, float],
*,
page_text_geometry: PDFPageTextGeometry | None = None,
+ detect_scripts: bool = True,
) -> list[_AnalyzeSpan]:
"""复用原生 PDF 字符回填逻辑,并允许共享同页删除线检测读取的字符。"""
page_width, page_height = page_size
@@ -165,6 +213,7 @@ def _fill_native_pdf_text_spans(
page_chars=page_text_geometry.chars if page_text_geometry is not None else None,
tight_bboxes=page_text_geometry.tight_bboxes if page_text_geometry is not None else None,
origins=page_text_geometry.origins if page_text_geometry is not None else None,
+ detect_scripts=detect_scripts,
)
@@ -322,6 +371,7 @@ def _fill_window_block_content_and_lines(
inline_formula_list: list[list[dict[str, Any]]],
ocr_res_list: list[list[dict[str, Any]]],
parse_mode: Literal["txt", "ocr"],
+ effort: Literal["flash", "medium", "high", "xhigh"],
ocr_det_type: set[str],
local_model_context: HybridLocalModelContext,
page_text_geometries: list[PDFPageTextGeometry | None] | None = None,
@@ -339,6 +389,7 @@ def _fill_window_block_content_and_lines(
if len(set(page_counts.values())) != 1:
raise ValueError(f"Hybrid block content page count mismatch: {page_counts}")
+ use_shared_script_sidecar = parse_mode == "txt" and effort in {"medium", "high", "xhigh"}
target_block_types = set(ocr_det_type) | TITLE_BLOCK_TYPES | {BlockType.TEXT}
page_block_line_results: list[
tuple[
@@ -347,6 +398,7 @@ def _fill_window_block_content_and_lines(
tuple[float, float],
list[PDFTextStyleLine],
list[PDFTextLinkLine],
+ list[PDFTextScriptLine],
]
] = []
for page_idx, (image_dict, pdf_page, page_model_list, page_inline_formula_list, page_ocr_res_list) in enumerate(
@@ -368,8 +420,18 @@ def _fill_window_block_content_and_lines(
page_size,
render_scale,
)
+ inline_math_regions = _get_page_inline_formula_regions(
+ page_inline_formula_list,
+ page_size,
+ render_scale,
+ )
+ table_regions = _get_page_table_regions(
+ page_model_list,
+ page_size,
+ )
style_lines: list[PDFTextStyleLine] = []
link_lines: list[PDFTextLinkLine] = []
+ script_lines: list[PDFTextScriptLine] = []
if parse_mode == "txt":
page_text_geometry = page_text_geometries[page_idx] if page_text_geometries is not None else None
try:
@@ -386,9 +448,12 @@ def _fill_window_block_content_and_lines(
_line_items,
style_lines,
link_lines,
+ script_lines,
) = build_pdf_native_visual_lines_and_styles(
pdf_page,
page_text_geometry=page_text_geometry,
+ inline_math_regions=inline_math_regions,
+ table_regions=table_regions,
)
if page_text_geometries is not None:
page_text_geometries[page_idx] = page_text_geometry
@@ -399,6 +464,7 @@ def _fill_window_block_content_and_lines(
render_scale,
page_size,
page_text_geometry=page_text_geometry,
+ detect_scripts=not use_shared_script_sidecar,
)
block_lines = _group_page_spans_by_block(
@@ -414,13 +480,14 @@ def _fill_window_block_content_and_lines(
page_size,
style_lines,
link_lines,
+ script_lines,
)
)
if parse_mode == "txt":
_apply_window_post_ocr(
local_model_context,
- [block_lines for _, block_lines, _, _style_lines, _link_lines in page_block_line_results],
+ [block_lines for _, block_lines, _, _style_lines, _link_lines, _script_lines in page_block_line_results],
)
for (
@@ -429,6 +496,7 @@ def _fill_window_block_content_and_lines(
page_size,
style_lines,
link_lines,
+ script_lines,
) in page_block_line_results:
_apply_block_content_and_line_metadata(
page_model_list,
@@ -445,6 +513,11 @@ def _fill_window_block_content_and_lines(
style_lines,
page_size,
)
+ apply_pdf_text_scripts(
+ page_model_list,
+ script_lines,
+ page_size,
+ )
materialize_pdf_inline_spans(page_model_list)
return model_list
diff --git a/mineru/backend/analysis/pdf/text/native.py b/mineru/backend/analysis/pdf/text/native.py
index 159dd388..74405349 100644
--- a/mineru/backend/analysis/pdf/text/native.py
+++ b/mineru/backend/analysis/pdf/text/native.py
@@ -82,6 +82,7 @@ def txt_spans_extract(
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,
+ detect_scripts: bool = True,
) -> list[_AnalyzeSpan]:
"""从 PDF 原生字符中提取文本 Span,并允许复用调用方已读取的页面字符。"""
page_char_count = None
@@ -164,6 +165,7 @@ def txt_spans_extract(
median_span_height,
tight_bboxes=tight_bboxes,
origins=origins,
+ detect_scripts=detect_scripts,
)
return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)
@@ -451,6 +453,7 @@ def fill_char_in_spans(
*,
tight_bboxes: dict[int, BBox] | None = None,
origins: dict[int, tuple[float, float]] | None = None,
+ detect_scripts: bool = True,
) -> list[_AnalyzeSpan]:
"""以 tight-first、loose-fallback 将字符分配到 Span,并返回待 OCR Span。"""
spans = sorted(spans, key=lambda x: x.bbox[1])
@@ -551,6 +554,7 @@ def fill_char_in_spans(
span,
tight_bboxes=tight_bboxes,
origins=origins,
+ detect_scripts=detect_scripts,
)
# 有的span中虽然没有字但有一两个空的占位符,用宽高和content长度过滤
if should_post_ocr_private_use and span.content:
@@ -860,6 +864,7 @@ def chars_to_content(
*,
tight_bboxes: dict[int, BBox] | None = None,
origins: dict[int, tuple[float, float]] | None = None,
+ detect_scripts: bool = True,
) -> None:
"""将 Span 内字符重建为文本,并合并连续的上标、下标片段。"""
span.metadata.pop(PDF_NATIVE_SCRIPT_MARKUP_KEY, None)
@@ -876,12 +881,14 @@ def chars_to_content(
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,
- tight_bboxes=tight_bboxes or {},
- origins=origins or {},
- protected_body_indices=protected_body_indices,
- )
+ script_roles: list[_ScriptRole] = ["body"] * len(chars)
+ if detect_scripts:
+ 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 34bdf237..43154084 100644
--- a/mineru/backend/analysis/pdf/text/styles.py
+++ b/mineru/backend/analysis/pdf/text/styles.py
@@ -8,10 +8,48 @@ from typing import Any, Sequence
from .....model.flash.pdf.document import PDFPage, PDFPageTextGeometry, get_lines_from_chars
from .....model.flash.pdf.text_styles import (
PDFTextLinkLine,
+ PDFTextScriptLine,
PDFTextStyleLine,
detect_pdf_text_link_lines,
+ detect_pdf_text_script_lines,
detect_pdf_text_style_lines,
)
+from .....types import BBox
+
+
+def _script_range_center_in_regions(
+ bbox: BBox,
+ regions: Sequence[BBox],
+) -> bool:
+ """判断脚本证据中心是否落入由 layout 确认的行内公式区域。"""
+
+ center_x = (bbox[0] + bbox[2]) / 2.0
+ center_y = (bbox[1] + bbox[3]) / 2.0
+ return any(region[0] <= center_x <= region[2] and region[1] <= center_y <= region[3] for region in regions)
+
+
+def _exclude_layout_formula_script_ranges(
+ lines: list[PDFTextScriptLine],
+ regions: Sequence[BBox],
+) -> list[PDFTextScriptLine]:
+ """从 Hybrid TXT 脚本 sidecar 中剔除已由 layout/MFR 拥有的公式字符。"""
+
+ if not regions:
+ return lines
+ return [
+ PDFTextScriptLine(
+ bbox=line.bbox,
+ text=line.text,
+ script_ranges=tuple(
+ script_range
+ for script_range in line.script_ranges
+ if not _script_range_center_in_regions(script_range.bbox, regions)
+ ),
+ source_index=line.source_index,
+ angle=line.angle,
+ )
+ for line in lines
+ ]
def build_pdf_native_visual_lines_and_styles(
@@ -19,16 +57,23 @@ def build_pdf_native_visual_lines_and_styles(
*,
page_text_geometry: PDFPageTextGeometry | None = None,
supported_angles: Sequence[float] = (0.0,),
+ inline_math_regions: Sequence[BBox] = (),
+ table_regions: Sequence[BBox] = (),
) -> tuple[
PDFPageTextGeometry,
list[Any],
list[PDFTextStyleLine],
list[PDFTextLinkLine],
+ list[PDFTextScriptLine],
]:
- """一次读取当前页字符,构造视觉 run、文本样式和超链接证据。"""
+ """一次读取当前页字符,构造视觉 run、普通样式、链接和脚本证据。"""
# 延迟导入避免 Hybrid 模块初始化时提前加载完整 Flash PDF 流水线。
from .....model.flash.pdf.native_text import _build_native_line_items
+ from .....model.flash.pdf.line_merging import (
+ _merge_overlapping_inline_text_clusters,
+ _merge_same_baseline_text_lines,
+ )
geometry = page_text_geometry if page_text_geometry is not None else pdf_page.get_chars_with_geometry()
chars = geometry.chars
@@ -38,15 +83,45 @@ def build_pdf_native_visual_lines_and_styles(
page_rotation=pdf_page.rotation,
supported_angles=supported_angles,
)
+ resolved_inline_math_regions = [tuple(float(value) for value in region) for region in inline_math_regions]
+ resolved_table_regions = [tuple(float(value) for value in region) for region in table_regions]
+ drawing_lines = pdf_page.get_drawing_lines()
style_lines = detect_pdf_text_style_lines(
line_items,
- pdf_page.get_drawing_lines(),
+ drawing_lines,
)
link_lines = detect_pdf_text_link_lines(
line_items,
pdf_page.get_link_annotations(),
)
- return geometry, line_items, style_lines, link_lines
+ script_line_items = _merge_same_baseline_text_lines(
+ list(line_items),
+ tuple(float(value) for value in pdf_page.size),
+ resolved_table_regions,
+ )
+ script_line_items = _merge_overlapping_inline_text_clusters(
+ script_line_items,
+ tuple(float(value) for value in pdf_page.size),
+ resolved_table_regions,
+ )
+ script_line_items = _merge_same_baseline_text_lines(
+ script_line_items,
+ tuple(float(value) for value in pdf_page.size),
+ resolved_table_regions,
+ )
+ script_lines = detect_pdf_text_script_lines(
+ script_line_items,
+ tuple(float(value) for value in pdf_page.size),
+ geometry.tight_bboxes,
+ geometry.origins,
+ all_chars=chars,
+ drawing_lines=drawing_lines,
+ )
+ script_lines = _exclude_layout_formula_script_ranges(
+ script_lines,
+ resolved_inline_math_regions,
+ )
+ return geometry, line_items, style_lines, link_lines, script_lines
__all__ = ["build_pdf_native_visual_lines_and_styles"]
diff --git a/mineru/backend/analysis/pdf/window.py b/mineru/backend/analysis/pdf/window.py
index 3599af08..f1ac1c00 100644
--- a/mineru/backend/analysis/pdf/window.py
+++ b/mineru/backend/analysis/pdf/window.py
@@ -169,6 +169,7 @@ def _process_flash_ocr(
empty_formula_list,
ocr_res_list,
"ocr",
+ "flash",
PIPELINE_DET_TYPE,
local_model_context,
)
@@ -271,6 +272,7 @@ def _process_text_and_formulas(
inline_formula_list,
ocr_res_list,
parse_mode,
+ effort,
ocr_det_type,
local_model_context,
page_text_geometries,
@@ -316,7 +318,7 @@ def process_pdf_windows(
_log_processing_window(window, page_count, len(images_pil_list))
page_text_geometries: list[PDFPageTextGeometry | None] | None = (
[None] * len(window_pages)
- if not flash_txt_mode and parse_mode == "txt" and effort in {"medium", "high"}
+ if not flash_txt_mode and parse_mode == "txt" and effort in {"medium", "high", "xhigh"}
else None
)
diff --git a/mineru/model/flash/pdf/text_styles.py b/mineru/model/flash/pdf/text_styles.py
index 1d4cb0b4..da5841f6 100644
--- a/mineru/model/flash/pdf/text_styles.py
+++ b/mineru/model/flash/pdf/text_styles.py
@@ -1256,12 +1256,52 @@ def _fraction_member_indices(
for char_idx, bbox in aligned
if bbox[1] >= rule_y - 0.2 * scale and bbox[1] - rule_y <= 1.75 * scale
]
+ # 超过局部公式尺度的长横线更像脚注/段落分隔线,不用于分式成员抑制。
+ if width > 8.0 * scale:
+ continue
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 _strong_structural_script_roles(
+ chars: list[dict[str, Any]],
+ tight_bboxes: dict[int, BBox],
+ origins: dict[int, tuple[float, float]],
+) -> dict[int, ScriptRole]:
+ """提取可在恢复公式区域中保留的引用和邻接 base 强脚本证据。"""
+
+ roles = classify_char_script_roles(
+ chars,
+ tight_bboxes=tight_bboxes,
+ origins=origins,
+ )
+ strong_roles: dict[int, ScriptRole] = {}
+ for index in _citation_script_indices(chars, roles):
+ if roles[index] != "body":
+ strong_roles[index] = roles[index]
+ for index, role in enumerate(roles):
+ if role != "sup" or not _is_math_identifier_char(_script_char_text(chars[index])):
+ continue
+ base_height = _token_tight_height(chars[index - 1], tight_bboxes) if index > 0 else 0.0
+ script_height = _token_tight_height(chars[index], tight_bboxes)
+ if base_height <= 0 or script_height > 0.8 * base_height:
+ continue
+ next_index = _nearest_nonspace_index(chars, index, 1)
+ if next_index is not None and _is_math_script_token_char(_script_char_text(chars[next_index])):
+ continue
+ if _has_adjacent_math_base(
+ chars,
+ index,
+ roles,
+ tight_bboxes,
+ origins,
+ ):
+ strong_roles[index] = role
+ return strong_roles
+
+
def _classify_script_runs(
chars: list[dict[str, Any]],
local_tight_bboxes: dict[int, BBox],
@@ -1375,10 +1415,15 @@ def _script_line_char_roles(
local_origins,
memberships,
)
+ strong_structural_roles = _strong_structural_script_roles(
+ local_chars,
+ local_tight_bboxes,
+ local_origins,
+ )
if bool(getattr(line, "compact_formula_cluster", False)) or (
bool(getattr(line, "restored_inline_cluster", False)) and bool(regions)
):
- roles = ["body"] * len(roles)
+ roles = [strong_structural_roles.get(index, "body") for index in range(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:
@@ -1844,6 +1889,87 @@ def _assign_lines_to_blocks(
return assignments
+def _assign_script_lines_to_blocks(
+ blocks: list[dict[str, Any]],
+ lines: Sequence[PDFTextScriptLine],
+ page_size: tuple[float, float],
+) -> dict[int, list[PDFTextScriptLine]]:
+ """保留整行主归属,并为无法投影的脚本区间补充 tight bbox 备用归属。"""
+
+ target_bboxes = {
+ block_index: block_bbox
+ for block_index, block in enumerate(blocks)
+ if block.get("type") in PDF_NATURAL_TEXT_STYLE_BLOCK_TYPES
+ and isinstance(block.get("content"), str)
+ and (block_bbox := _block_bbox_to_page_bbox(block.get("bbox"), page_size)) is not None
+ }
+ target_projected = {
+ block_index: _project_content_chars(str(blocks[block_index]["content"])) for block_index in target_bboxes
+ }
+ primary_assignments = _assign_lines_to_blocks(blocks, lines, page_size)
+ assignments: dict[int, list[PDFTextScriptLine]] = {
+ block_index: [line for line in block_lines if isinstance(line, PDFTextScriptLine)]
+ for block_index, block_lines in primary_assignments.items()
+ }
+ primary_block_by_line = {id(line): block_index for block_index, block_lines in assignments.items() for line in block_lines}
+ fallback_ranges: dict[tuple[int, int], list[PDFTextScriptRange]] = {}
+ for line_index, line in enumerate(lines):
+ for script_range in line.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,
+ )
+ primary_block_index = primary_block_by_line.get(id(line))
+ if primary_block_index is not None and _match_script_line_ranges(
+ target_projected[primary_block_index],
+ evidence_line,
+ ):
+ continue
+ matches = [
+ (
+ block_index,
+ _line_block_score(script_range.bbox, block_bbox),
+ )
+ for block_index, block_bbox in target_bboxes.items()
+ if block_index != primary_block_index
+ and _match_script_line_ranges(
+ target_projected[block_index],
+ evidence_line,
+ )
+ if (
+ block_bbox[0] <= (script_range.bbox[0] + script_range.bbox[2]) / 2 <= block_bbox[2]
+ and block_bbox[1] <= (script_range.bbox[1] + script_range.bbox[3]) / 2 <= block_bbox[3]
+ )
+ or _bbox_overlap_ratio(script_range.bbox, block_bbox) >= 0.5
+ ]
+ if not matches:
+ continue
+ block_index, _score = max(matches, key=lambda item: (*item[1], -item[0]))
+ fallback_ranges.setdefault((block_index, line_index), []).append(script_range)
+ for (block_index, line_index), script_ranges in fallback_ranges.items():
+ line = lines[line_index]
+ assignments.setdefault(block_index, []).append(
+ PDFTextScriptLine(
+ bbox=line.bbox,
+ text=line.text,
+ script_ranges=tuple(script_ranges),
+ source_index=line.source_index,
+ angle=line.angle,
+ )
+ )
+ for block_lines in assignments.values():
+ block_lines.sort(key=lambda line: (line.source_index, line.bbox[1], line.bbox[0]))
+ return assignments
+
+
def _filter_line_styles_for_block(
lines: Sequence[PDFTextStyleLine],
block_type: Any,
@@ -2187,6 +2313,51 @@ def _match_style_ranges(
return _merge_style_ranges(output)
+def _match_script_line_ranges(
+ projected: Sequence[_ProjectedChar],
+ line: PDFTextStyleLine,
+) -> list[PDFTextStyleRange]:
+ """独立投影单条脚本行,避免其它视觉行推进 cursor 后吞掉短脚本。"""
+
+ projected_text = "".join(token.value for token in projected)
+ exact_occurrences = _all_occurrences(projected_text, line.text, 0)
+ if len(exact_occurrences) == 1:
+ line_start = exact_occurrences[0]
+ return [
+ PDFTextStyleRange(
+ line_start + style_range.start,
+ line_start + style_range.end,
+ style_range.styles,
+ )
+ for style_range in line.style_ranges
+ ]
+ formula_match = _match_line_across_formula_gaps(
+ line.text,
+ projected,
+ 0,
+ )
+ if formula_match is not None:
+ return _ranges_from_line_projection(line, formula_match)
+ output: list[PDFTextStyleRange] = []
+ for style_range in line.style_ranges:
+ position = _resolve_fallback_occurrence(
+ projected_text,
+ line,
+ style_range,
+ 0,
+ )
+ if position is None:
+ continue
+ output.append(
+ PDFTextStyleRange(
+ position,
+ position + style_range.end - style_range.start,
+ style_range.styles,
+ )
+ )
+ return _merge_style_ranges(output)
+
+
def _merge_style_ranges(ranges: Sequence[PDFTextStyleRange]) -> list[PDFTextStyleRange]:
"""把重叠样式取并集,并合并相邻且样式集合相同的区间。"""
@@ -2763,7 +2934,7 @@ def _record_materialized_script_ranges(
),
source_index=line.source_index,
)
- matched = _match_style_ranges(projected, [evidence_line])
+ matched = _match_script_line_ranges(projected, evidence_line)
if len(matched) != 1:
continue
mapped = matched[0]
@@ -2802,7 +2973,7 @@ def apply_pdf_text_scripts(
materialized_diagnostics: list[dict[str, Any]] | None = None,
) -> None:
"""把 Flash 上下标 sidecar 投影到最终自然语言 block,并清理公式私有区域。"""
- assignments = _assign_lines_to_blocks(blocks, lines, page_size)
+ assignments = _assign_script_lines_to_blocks(blocks, lines, page_size)
for block_index, block_lines in assignments.items():
block = blocks[block_index]
regions = [
@@ -2837,9 +3008,20 @@ def apply_pdf_text_scripts(
)
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)
+ if not isinstance(content, str) or not content:
+ continue
+ projected = _project_content_chars(content)
+ combined_ranges = _merge_style_ranges(
+ [
+ *_match_style_ranges(projected, projected_lines),
+ *(
+ matched_range
+ for projected_line in projected_lines
+ for matched_range in _match_script_line_ranges(projected, projected_line)
+ ),
+ ]
+ )
+ if materialized_diagnostics is not None:
for line in block_lines:
_record_materialized_script_ranges(
content,
@@ -2850,7 +3032,16 @@ def apply_pdf_text_scripts(
eligible_ranges.get(id(line), ()),
materialized_diagnostics,
)
- apply_pdf_text_styles([block], projected_lines, page_size)
+ intervals = _raw_style_intervals(content, projected, combined_ranges)
+ if 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,
+ ],
+ )
for block in blocks:
block.pop("_inline_math_regions", None)
diff --git a/tests/unittest/test_flash_pdf_scripts.py b/tests/unittest/test_flash_pdf_scripts.py
index c576795a..656ded2a 100644
--- a/tests/unittest/test_flash_pdf_scripts.py
+++ b/tests/unittest/test_flash_pdf_scripts.py
@@ -127,6 +127,25 @@ _NO_SCRIPT_SOURCE_EXPECTATIONS = {
}
}
+_GENERAL_RECOVERY_EXPECTATIONS = {
+ "demo3.pdf": {
+ (4, 51): (("2", "superscript"),),
+ (4, 163): (("3", "superscript"),),
+ (8, 48): (("5", "superscript"),),
+ },
+ "中文论文.pdf": {
+ (3, 95): (("2", "superscript"),),
+ },
+ "中文论文2.pdf": {
+ (0, 41): (("[2]", "superscript"), ("[3]", "superscript")),
+ (2, 97): (("[12]", "superscript"),),
+ (3, 14): (("[17]", "superscript"),),
+ (3, 83): (("[30]", "superscript"),),
+ (3, 87): (("[31]", "superscript"), ("[32]", "superscript"), ("[33]", "superscript")),
+ (13, 70): (("[41]", "superscript"),),
+ },
+}
+
def _origin_from_upright(
origin: tuple[float, float],
@@ -365,6 +384,92 @@ def test_flash_fraction_bar_suppresses_stacked_script_candidate() -> None:
assert filtered.script_ranges == ()
+def test_flash_long_text_separator_does_not_suppress_leading_note_marker() -> None:
+ """验证长脚注分隔线两侧的正文不会被误判成局部分式。"""
+
+ page_size = (100.0, 100.0)
+ below_chars: list[Char] = []
+ tight_bboxes: dict[int, BBox] = {}
+ origins: dict[int, tuple[float, float]] = {}
+ for index, text in enumerate("2Word"):
+ left = 10.0 + index * 7.0
+ bbox = (left, 43.0, left + (4.0 if index == 0 else 6.0), 47.0 if index == 0 else 51.0)
+ below_chars.append({"char": text, "char_idx": index, "bbox": Bbox(list(bbox)), "rotation": 0.0, "font": {}})
+ tight_bboxes[index] = bbox
+ origins[index] = (left, bbox[3])
+ above_chars: list[Char] = []
+ for offset, text in enumerate("data", start=len(below_chars)):
+ left = 10.0 + (offset - len(below_chars)) * 7.0
+ bbox = (left, 28.0, left + 6.0, 34.0)
+ above_chars.append({"char": text, "char_idx": offset, "bbox": Bbox(list(bbox)), "rotation": 0.0, "font": {}})
+ tight_bboxes[offset] = bbox
+ origins[offset] = (left, 34.0)
+ line = _LineItem(
+ text="2Word",
+ bbox=(10.0, 43.0, 44.0, 51.0),
+ angle=0,
+ source_index=0,
+ chars=below_chars,
+ )
+
+ script_line = detect_pdf_text_script_lines(
+ [line],
+ page_size,
+ tight_bboxes,
+ origins,
+ all_chars=[*above_chars, *below_chars],
+ drawing_lines=[_AxisLine((5.0, 39.8, 65.0, 40.2), 0.4, "horizontal")],
+ )[0]
+
+ assert [(item.start, item.end, item.style) for item in script_line.script_ranges] == [(0, 1, "superscript")]
+
+
+ ("text", "script_start", "expected_text"),
+ [
+ pytest.param("R2", 1, "2", id="adjacent-base"),
+ pytest.param("A[2]", 1, "[2]", id="numeric-citation"),
+ ],
+)
+def test_flash_restored_formula_line_preserves_strong_structural_scripts(
+ text: str,
+ script_start: int,
+ expected_text: str,
+) -> None:
+ """验证恢复公式行只退让弱 token,并保留局部几何稳定的强脚本结构。"""
+
+ chars: list[Char] = []
+ tight_bboxes: dict[int, BBox] = {}
+ origins: dict[int, tuple[float, float]] = {}
+ for index, char_text in enumerate(text):
+ left = 10.0 + index * 7.0
+ bbox = (left, 40.0, left + 6.0, 50.0) if index < script_start else (left, 34.0, left + 4.0, 40.0)
+ chars.append({"char": char_text, "char_idx": index, "bbox": Bbox(list(bbox)), "rotation": 0.0, "font": {}})
+ tight_bboxes[index] = bbox
+ origins[index] = (left, bbox[3])
+ line_bbox = (10.0, 34.0, 10.0 + len(text) * 7.0, 50.0)
+ line = _LineItem(
+ text=text,
+ bbox=line_bbox,
+ angle=0,
+ source_index=0,
+ chars=chars,
+ restored_inline_cluster=True,
+ inline_math_regions=[line_bbox],
+ )
+
+ script_line = detect_pdf_text_script_lines(
+ [line],
+ (100.0, 100.0),
+ tight_bboxes,
+ origins,
+ )[0]
+
+ assert [(script_line.text[item.start : item.end], item.style) for item in script_line.script_ranges] == [
+ (expected_text, "superscript")
+ ]
+
+
@pytest.mark.parametrize("text", ["Bm", "r1"])
def test_flash_formula_region_marks_only_the_index(text: str) -> None:
"""验证公式内部 B_m 与 r_1 只标记下移索引,不把整个 token 标成下标。"""
@@ -451,6 +556,33 @@ def test_flash_script_projection_does_not_leak_to_same_text() -> None:
]
+def test_flash_script_projection_ignores_unrelated_line_cursor() -> None:
+ """验证无关短行不会推进共享 cursor 并吞掉后续完整引用脚本。"""
+
+ blocks = [{"type": "text", "bbox": [0.0, 0.0, 1.0, 1.0], "content": "[12]"}]
+ lines = [
+ PDFTextScriptLine(
+ bbox=(10.0, 10.0, 20.0, 20.0),
+ text="[",
+ script_ranges=(PDFTextScriptRange(0, 1, "superscript", (10.0, 10.0, 12.0, 15.0), 1, False),),
+ source_index=0,
+ angle=0,
+ ),
+ PDFTextScriptLine(
+ bbox=(10.0, 10.0, 40.0, 20.0),
+ text="[12]",
+ script_ranges=(PDFTextScriptRange(0, 4, "superscript", (10.0, 10.0, 30.0, 15.0), 1, False),),
+ source_index=1,
+ angle=0,
+ ),
+ ]
+
+ apply_pdf_text_scripts(blocks, lines, (100.0, 100.0))
+ materialize_pdf_inline_spans(blocks)
+
+ assert blocks[0]["content"] == [{"type": "text", "content": "[12]", "styles": ["superscript"]}]
+
+
def test_flash_script_projection_combines_hyperlink() -> None:
"""验证超链接与上下标区间共同物化时保持子 Span 顺序和 URL。"""
blocks = [
@@ -640,6 +772,23 @@ def test_user_reviewed_unicode_math_tokens_stay_body(pdf_name: str) -> None:
assert not any(item["source_index"] == source_index for item in diagnostics[page_index]["materialized_ranges"])
[email protected]("pdf_name", tuple(_GENERAL_RECOVERY_EXPECTATIONS))
+def test_general_flash_script_recovery_candidates_materialize(pdf_name: str) -> None:
+ """验证脚注、邻接 base 与数字引用通过通用几何规则检测并物化。"""
+
+ diagnostics = _flash_script_diagnostics(pdf_name)
+ for (page_index, source_index), expected in _GENERAL_RECOVERY_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[item.start : item.end], item.style) for item 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)
+
+
def test_chinese_paper_page_12_recovers_numbered_formula_regions() -> None:
"""验证栏顶公式 6、7、8 被完整认领为 equation,且不吸收相邻正文。"""
diagnostics: list[dict[str, Any]] = []
diff --git a/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.py
index 2e8d2739..dca7ce40 100644
--- a/tests/unittest/test_pdf_analyze_block_content.py
+++ b/tests/unittest/test_pdf_analyze_block_content.py
@@ -183,6 +183,11 @@ def test_doc_analyze_converts_vlm_results_before_downstream_processing(
assert type(window_model_list) is list
assert all(type(page) is list for page in window_model_list)
assert all(type(block) is dict for page in window_model_list for block in page)
+ if parse_mode == "txt":
+ assert isinstance(_page_text_geometries, list)
+ assert len(_page_text_geometries) == 1
+ else:
+ assert _page_text_geometries is None
return window_model_list
xhigh_normalizer = MagicMock(wraps=layout._normalize_xhigh_vlm_blocks)
@@ -443,7 +448,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: (PDFPageTextGeometry([], {}, {}), [], [], []),
+ lambda *_args, **_kwargs: (PDFPageTextGeometry([], {}, {}), [], [], [], []),
)
monkeypatch.setattr(
text_content,
@@ -466,6 +471,7 @@ def test_fill_window_batches_txt_post_ocr_before_page_content(monkeypatch: pytes
[[], []],
[[], []],
"txt",
+ "medium",
{BlockType.TEXT},
local_model_context,
)
@@ -491,6 +497,7 @@ def test_fill_window_ocr_mode_does_not_run_txt_post_ocr(monkeypatch: pytest.Monk
[[]],
[[]],
"ocr",
+ "medium",
{BlockType.TEXT},
local_model_context,
)
diff --git a/tests/unittest/test_pdf_text_styles.py b/tests/unittest/test_pdf_text_styles.py
index b06099c3..1cfb789b 100644
--- a/tests/unittest/test_pdf_text_styles.py
+++ b/tests/unittest/test_pdf_text_styles.py
@@ -13,6 +13,7 @@ from zipfile import ZipFile
import pytest
from mineru.backend.analysis.pdf.text import content as text_content
+from mineru.backend.analysis.pdf.text import styles as text_style_enrichment
from mineru.backend.analysis.pdf.text.models import _AnalyzeLine, _AnalyzeSpan
from mineru.backend.analysis.pdf.text.native import txt_spans_extract
from mineru.backend.postprocess.pages import model_json_to_pages
@@ -34,6 +35,8 @@ from mineru.model.flash.pdf.text_styles import (
PDF_NATIVE_SCRIPT_MARKUP_KEY,
PDFTextLinkLine,
PDFTextLinkRange,
+ PDFTextScriptLine,
+ PDFTextScriptRange,
PDFTextStyleLine,
PDFTextStyleRange,
apply_pdf_text_links as _apply_pdf_text_links,
@@ -2054,7 +2057,7 @@ def test_hybrid_txt_reuses_loaded_chars_and_applies_styles(
0,
)
]
- build_styles = MagicMock(return_value=(page_text_geometry, [], style_lines, link_lines))
+ build_styles = MagicMock(return_value=(page_text_geometry, [], style_lines, link_lines, []))
observed_geometry: list[object] = []
def fake_fill_native(
@@ -2065,10 +2068,12 @@ def test_hybrid_txt_reuses_loaded_chars_and_applies_styles(
_page_size: object,
*,
page_text_geometry: object,
+ detect_scripts: bool,
) -> list[_AnalyzeSpan]:
"""记录传入原生回填的字符几何,并返回稳定文本 span。"""
observed_geometry.append(page_text_geometry)
+ assert detect_scripts is False
return [
_AnalyzeSpan(
type=ContentType.TEXT,
@@ -2119,6 +2124,7 @@ def test_hybrid_txt_reuses_loaded_chars_and_applies_styles(
[[]],
[[]],
"txt",
+ "medium",
{BlockType.TEXT},
MagicMock(),
)
@@ -2154,7 +2160,7 @@ def test_hybrid_txt_efforts_apply_dehyphenated_links(
monkeypatch.setattr(
text_content,
"build_pdf_native_visual_lines_and_styles",
- lambda *_args, **_kwargs: (PDFPageTextGeometry([], {}, {}), [], [], link_lines),
+ lambda *_args, **_kwargs: (PDFPageTextGeometry([], {}, {}), [], [], link_lines, []),
)
monkeypatch.setattr(
text_content,
@@ -2216,6 +2222,7 @@ def test_hybrid_txt_efforts_apply_dehyphenated_links(
[[]],
[[]],
"txt",
+ effort,
{BlockType.TEXT},
MagicMock(),
)
@@ -2223,6 +2230,89 @@ def test_hybrid_txt_efforts_apply_dehyphenated_links(
assert _span_snapshot(model_list[0][0]["content"]) == (f"<hyperlink>international<url>{target}</url></hyperlink>")
[email protected]("effort", ["medium", "high", "xhigh"])
+def test_hybrid_txt_efforts_apply_shared_script_sidecar(
+ monkeypatch: pytest.MonkeyPatch,
+ effort: str,
+) -> None:
+ """验证 Medium、High 与 XHigh 的 TXT 文本统一应用整行脚本 sidecar。"""
+
+ page_geometry = PDFPageTextGeometry([], {}, {})
+ script_line = PDFTextScriptLine(
+ bbox=(10.0, 10.0, 30.0, 20.0),
+ text="x2",
+ script_ranges=(PDFTextScriptRange(1, 2, "superscript", (20.0, 10.0, 25.0, 15.0), 1, False),),
+ source_index=0,
+ angle=0,
+ )
+ build_evidence = MagicMock(return_value=(page_geometry, [], [], [], [script_line]))
+ monkeypatch.setattr(text_content, "build_pdf_native_visual_lines_and_styles", build_evidence)
+ monkeypatch.setattr(text_content, "_build_page_text_formula_spans", lambda *_args: [])
+
+ def fake_fill_native(*_args: object, detect_scripts: bool, **_kwargs: object) -> list[_AnalyzeSpan]:
+ """确认 Hybrid TXT 不再使用 layout span 内的旧脚本分类。"""
+
+ assert detect_scripts is False
+ return [_AnalyzeSpan(type=ContentType.TEXT, bbox=(10.0, 10.0, 30.0, 20.0), content="x2", score=1.0)]
+
+ monkeypatch.setattr(text_content, "_fill_native_pdf_text_spans", fake_fill_native)
+ monkeypatch.setattr(
+ text_content,
+ "_group_page_spans_by_block",
+ lambda *_args: {
+ 0: [
+ _AnalyzeLine(
+ bbox=(10.0, 10.0, 30.0, 20.0),
+ spans=[_AnalyzeSpan(type=ContentType.TEXT, bbox=(10.0, 10.0, 30.0, 20.0), content="x2", score=1.0)],
+ )
+ ]
+ },
+ )
+ monkeypatch.setattr(text_content, "_apply_window_post_ocr", lambda *_args: None)
+ pdf_page = MagicMock(size=(100.0, 100.0))
+ pdf_page.get_char_count.return_value = 2
+ model_list = [[{"type": BlockType.TEXT, "bbox": [0.1, 0.1, 0.3, 0.2], "content": ""}]]
+
+ text_content._fill_window_block_content_and_lines(
+ [{"img_pil": object(), "scale": 1.0}],
+ [pdf_page],
+ model_list,
+ [[]],
+ [[]],
+ "txt",
+ effort, # type: ignore[arg-type]
+ {BlockType.TEXT},
+ MagicMock(),
+ )
+
+ assert model_list[0][0]["content"] == [
+ {"type": "text", "content": "x"},
+ {"type": "text", "content": "2", "styles": ["superscript"]},
+ ]
+
+
+def test_hybrid_layout_formula_regions_hard_exclude_script_ranges() -> None:
+ """验证 Hybrid TXT 只保留 layout 行内公式 bbox 外的脚本证据。"""
+
+ line = PDFTextScriptLine(
+ bbox=(0.0, 0.0, 40.0, 20.0),
+ text="x2y3",
+ script_ranges=(
+ PDFTextScriptRange(1, 2, "superscript", (10.0, 2.0, 15.0, 8.0), 2, True),
+ PDFTextScriptRange(3, 4, "subscript", (30.0, 12.0, 35.0, 18.0), 2, False),
+ ),
+ source_index=0,
+ angle=0,
+ )
+
+ filtered = text_style_enrichment._exclude_layout_formula_script_ranges(
+ [line],
+ [(8.0, 0.0, 18.0, 10.0)],
+ )
+
+ assert [(item.start, item.end, item.style) for item in filtered[0].script_ranges] == [(3, 4, "subscript")]
+
+
def test_ocr_path_does_not_collect_or_apply_pdf_styles(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -2274,6 +2364,7 @@ def test_ocr_path_does_not_collect_or_apply_pdf_styles(
[[]],
[[]],
"ocr",
+ "medium",
{BlockType.TEXT},
MagicMock(),
)
@@ -2340,6 +2431,7 @@ def test_high_char_count_txt_path_skips_pdf_text_enrichment(
[[]],
[[]],
"txt",
+ "medium",
{BlockType.TEXT},
MagicMock(),
)