Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: enhance script role classification and add comprehensive testing for script components
myhloli14303b5893ac
diff --git a/mineru/backend/analysis/pdf/text/native.py b/mineru/backend/analysis/pdf/text/native.pyindex 05aaa591..db21b085 100644--- a/mineru/backend/analysis/pdf/text/native.py+++ b/mineru/backend/analysis/pdf/text/native.py@@ -7,7 +7,9 @@ import collectionsimport mathimport reimport statistics-from typing import Any, Callable+import unicodedata+from dataclasses import dataclass+from typing import Any, Callable, Literalimport cv2import numpy as np@@ -397,10 +399,55 @@ LINE_START_FLAG = ()Span_Height_Ratio = 0.33 # 字符的中轴和span的中轴高度差不能超过1/3span高度-SCRIPT_BODY_HEIGHT_RATIO = 0.9-SCRIPT_CENTER_TOLERANCE_RATIO = 0.15+# 正文带阈值:只允许接近最大高度的字符参与正文基线估计。+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_COMPONENT_MIN_OFFSET_RATIO = 0.08+SCRIPT_COMPONENT_MAX_HEIGHT_RATIO = 1.1+SCRIPT_BRACKET_PAIRS = {"[": "]", "[": "]", "(": ")", "(": ")"}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]+ is_valid: bool+ is_body_anchor: bool+++@dataclass(frozen=True, slots=True)+class _ScriptBodyBand:+ """表示当前 span 的正文中心线和参考高度。"""++ center_y: float+ height: float+++@dataclass(frozen=True, slots=True)+class _ScriptSeed:+ """表示可让连续组件成立的高置信证据区间及其角色。"""++ start: int+ end: int+ role: _ScriptMarkRole+ evidence: _ScriptEvidenceKind+ protected_body_indices: frozenset[int] = frozenset()+def _is_private_use_char(char: str) -> bool:"""判断单个字符是否落在 Unicode 私用区,用于识别字体映射异常。"""@@ -533,46 +580,207 @@ def _is_valid_script_reference_char(char: Char, metrics: dict[str, float]) -> boreturn metrics["height"] > 1 and metrics["width"] > 0-def _get_body_axis(chars: list[Char], char_metrics: list[dict[str, float]]) -> dict[str, float] | None:- """根据同一 span 内最大高度字符簇估计正文中心线和正文高度。"""- valid_metrics = [metrics for char, metrics in zip(chars, char_metrics) if _is_valid_script_reference_char(char, metrics)]- if not valid_metrics:+def _get_script_role(offset: float) -> _ScriptMarkRole:+ """把相对正文中心的纵向偏移转换为上标或下标角色。"""+ return "sub" if offset > 0 else "sup"+++def _build_script_features(+ chars: list[Char],+ char_metrics: list[dict[str, float]],+) -> list[_ScriptCharFeature]:+ """一次性构造字符几何、字体和正文锚点特征。"""+ features = []+ for index, (char, metrics) in enumerate(zip(chars, char_metrics)):+ text = str(char.get("char", ""))+ font = char.get("font") or {}+ is_valid = _is_valid_script_reference_char(char, metrics)+ features.append(+ _ScriptCharFeature(+ index=index,+ text=text,+ height=metrics["height"],+ center_y=metrics["center_y"],+ font_signature=(font.get("name"), font.get("flags")),+ is_valid=is_valid,+ is_body_anchor=is_valid and text.isalnum(),+ )+ )+ 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- max_height = max(metrics["height"] for metrics in valid_metrics)- body_metrics = [metrics for metrics in valid_metrics if metrics["height"] >= max_height * SCRIPT_BODY_HEIGHT_RATIO]- if not body_metrics:+ 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 _collect_script_seeds(+ features: list[_ScriptCharFeature],+ body_band: _ScriptBodyBand,+) -> list[_ScriptSeed]:+ """统一收集强几何、局部字体和成对结构三类上下标证据。"""+ seeds: list[_ScriptSeed] = []+ claimed_indices: set[int] = set()++ 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",+ )+ )+ claimed_indices.add(feature.index)++ for index in range(1, len(features)):+ 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 feature.font_signature == previous_feature.font_signature+ or feature.height > previous_feature.height * SCRIPT_COMPONENT_MAX_HEIGHT_RATIO+ ):+ continue- return {- "center_y": statistics.median(metrics["center_y"] for metrics in body_metrics),- "height": statistics.median(metrics["height"] for metrics in body_metrics),- }+ 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]] = []+ for feature in features:+ if feature.text in SCRIPT_BRACKET_PAIRS:+ bracket_stack.append((feature.index, feature.text))+ continue+ if not bracket_stack or feature.text != SCRIPT_BRACKET_PAIRS[bracket_stack[-1][1]]:+ continue+ open_index, _open_text = bracket_stack.pop()+ open_feature = features[open_index]+ if not open_feature.is_valid or not feature.is_valid:+ continue+ if (+ open_feature.height > body_band.height * SCRIPT_GEOMETRY_MAX_HEIGHT_RATIO+ or feature.height > body_band.height * SCRIPT_GEOMETRY_MAX_HEIGHT_RATIO+ ):+ continue-def _classify_char_script_roles(chars: list[Char], char_metrics: list[dict[str, float]]) -> list[str]:- """按正文主带判断每个字符属于正文、上标或下标。"""- body_axis = _get_body_axis(chars, char_metrics)- if body_axis is None or body_axis["height"] <= 0:- return ["body"] * len(chars)+ open_offset = open_feature.center_y - body_band.center_y+ close_offset = 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+ ):+ continue- tolerance = body_axis["height"] * SCRIPT_CENTER_TOLERANCE_RATIO- roles = []- for char, metrics in zip(chars, char_metrics):- if not _is_valid_script_reference_char(char, metrics):- roles.append("body")+ seeds.append(+ _ScriptSeed(+ start=open_index,+ end=feature.index,+ role=_get_script_role((open_offset + close_offset) / 2),+ evidence="structure",+ )+ )+ return seeds+++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])+ continue+ if (+ feature.index in protected_body_indices+ or not feature.is_valid+ or feature.text.isspace()+ or feature.height > maximum_height+ ):+ candidate_roles.append(None)continue- char_center_y = metrics["center_y"]- if char_center_y < body_axis["center_y"] - tolerance:- roles.append("sup")- elif char_center_y > body_axis["center_y"] + tolerance:- roles.append("sub")+ offset = feature.center_y - body_band.center_y+ if abs(offset) < minimum_offset:+ candidate_roles.append(None)else:- roles.append("body")+ candidate_roles.append(_get_script_role(offset))++ 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_endreturn 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:diff --git a/tests/unittest/pdfs/metabolic_pathway_page_3.pdf b/tests/unittest/pdfs/metabolic_pathway_page_3.pdfnew file mode 100644index 00000000..8fef0ea3Binary files /dev/null and b/tests/unittest/pdfs/metabolic_pathway_page_3.pdf differdiff --git a/tests/unittest/test_pdf_native_script_detection.py b/tests/unittest/test_pdf_native_script_detection.pynew file mode 100644index 00000000..de0387c7--- /dev/null+++ b/tests/unittest/test_pdf_native_script_detection.py@@ -0,0 +1,280 @@+from __future__ import annotations++from pathlib import Path++import pytest+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.types import ContentType+from mineru.utils.pdf_document import PDFDocument+++_PROJECT_ROOT = Path(__file__).resolve().parents[2]+_DEMO_PDF_DIR = _PROJECT_ROOT / "demo" / "pdfs"+_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]]:+ """从真实 PDF 指定页中返回全部包含探针的物理行字符。"""+ with PDFDocument(str(pdf_path)) as document:+ matching_lines = []+ for line in document.get_page_lines(page_index):+ 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", [])]+ )+ return matching_lines+++def _line_chars_containing(pdf_path: Path, page_index: int, probe: str) -> list[Char]:+ """从真实 PDF 指定页中返回唯一包含探针的物理行字符。"""+ matching_lines = _lines_chars_containing(pdf_path, page_index, probe)++ assert len(matching_lines) == 1, (pdf_path, page_index, probe, len(matching_lines))+ return matching_lines[0]+++def _contiguous_chars_containing(pdf_path: Path, page_index: int, probe: str) -> list[Char]:+ """忽略 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+ ]++ 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)]+++def _render_chars(chars: list[Char]) -> str:+ """使用生产 chars_to_content 路径重建字符内容和上下标标签。"""+ span = _AnalyzeSpan(+ type=ContentType.TEXT,+ bbox=(0.0, 0.0, 1.0, 1.0),+ metadata={"chars": chars},+ )+ native.chars_to_content(span)+ return span.content+++def _render_pdf_line(pdf_path: Path, page_index: int, probe: str) -> str:+ """定位真实 PDF 物理行并使用生产逻辑返回重建文本。"""+ return _render_chars(_line_chars_containing(pdf_path, page_index, probe))+++def _script_char(+ index: int,+ text: str,+ *,+ height: float,+ center_y: float,+ font_name: str = "Body",+) -> Char:+ """构造最小字符几何,用于验证组件证据和边界不变量。"""+ return {+ "bbox": Bbox(+ [+ float(index),+ center_y - height / 2,+ float(index + 1),+ center_y + height / 2,+ ]+ ),+ "char": text,+ "rotation": 0.0,+ "font": {"name": font_name, "flags": 0, "size": 1.0, "weight": 400},+ "char_idx": index,+ }+++def test_weak_offset_component_without_seed_stays_body() -> None:+ """验证只有连续级弱偏移、没有高置信证据的组件不会产生标签。"""+ chars = [+ _script_char(0, "A", height=10.0, center_y=10.0),+ _script_char(1, "x", height=9.0, center_y=10.9),+ ]++ assert _render_chars(chars) == "Ax"+++def test_strong_geometry_seed_absorbs_same_side_punctuation() -> None:+ """验证强几何种子会把同侧连续标点纳入同一个上标组件。"""+ chars = [+ _script_char(0, "A", height=10.0, center_y=10.0),+ _script_char(1, "2", height=7.0, center_y=7.0),+ _script_char(2, ",", height=9.0, center_y=8.5),+ ]++ assert _render_chars(chars) == "A<sup>2,</sup>"+++def test_font_suffix_seed_keeps_its_base_character_body() -> None:+ """验证局部字体后缀只标记后缀,受保护的基字符不能被组件吸收。"""+ chars = [+ _script_char(0, "9", height=20.0, center_y=12.0),+ _script_char(1, " ", height=0.0, center_y=12.0),+ _script_char(2, "R", height=11.0, center_y=10.0, font_name="Base"),+ _script_char(3, "2", height=10.5, center_y=8.5, font_name="Suffix"),+ ]++ assert _render_chars(chars) == "9 R<sup>2</sup>"+++def test_shifted_brackets_seed_the_complete_reference_component() -> None:+ """验证成对缩小括号会把内部数字整体作为结构上标证据。"""+ chars = [+ _script_char(0, "依", height=10.0, center_y=10.0),+ _script_char(1, "[", height=7.0, center_y=7.0),+ _script_char(2, "1", height=10.2, center_y=7.5, font_name="Reference"),+ _script_char(3, "]", height=7.0, center_y=7.0),+ _script_char(4, "。", height=10.0, center_y=10.0),+ ]++ assert _render_chars(chars) == "依<sup>[1]</sup>。"+++ ("pdf_name", "page_index", "probe", "expected_fragments"),+ [+ pytest.param(+ "demo1.pdf",+ 0,+ "Patrick N.J. Lanea,c,*",+ ("Lane<sup>a,c,*</sup>", "Best<sup>b,c,d</sup>"),+ id="author-affiliations",+ ),+ pytest.param(+ "demo3.pdf",+ 1,+ "where segi",+ ("seg<sub>i</sub>",),+ id="variable-subscript",+ ),+ pytest.param(+ "demo4.pdf",+ 0,+ "Innate [18F]",+ ("[<sup>18</sup>F]",),+ id="isotope-superscript",+ ),+ pytest.param(+ "mixed_elements_pages_03_06.pdf",+ 0,+ "vacuum of 10–3 Pa",+ ("10<sup>–3</sup> Pa",),+ id="negative-exponent",+ ),+ pytest.param(+ "mixed_elements_pages_03_06.pdf",+ 0,+ "to consist of ScFeGe2",+ ("ScFeGe<sub>2</sub>", "Sc<sub>4</sub>Fe<sub>4</sub>Ge<sub>6.6</sub>"),+ id="chemical-subscripts",+ ),+ pytest.param(+ "mixed_elements_pages_11_15.pdf",+ 0,+ "H2-antagonist",+ ("H<sub>2</sub>-antagonist",),+ id="medical-subscript",+ ),+ pytest.param(+ "中文论文.pdf",+ 0,+ "其中,季节等[1]",+ ("季节等<sup>[1]</sup>",),+ id="chinese-reference",+ ),+ pytest.param(+ "中文论文.pdf",+ 0,+ "利用决定系数(R2",+ ("决定系数(R<sup>2</sup>",),+ id="same-size-font-suffix",+ ),+ pytest.param(+ "中文论文.pdf",+ 0,+ "Voting 模型的性能略低于 Stacking 模型(R2",+ ("Stacking 模型(R<sup>2</sup>",),+ id="same-size-font-suffix-after-tall-digits",+ ),+ ],+)+def test_real_pdf_scripts_keep_confirmed_markup(+ pdf_name: str,+ page_index: int,+ probe: str,+ expected_fragments: tuple[str, ...],+) -> None:+ """验证已有输出中经页面视觉确认的真实上下标继续保留。"""+ content = _render_pdf_line(_DEMO_PDF_DIR / pdf_name, page_index, probe)++ assert all(expected_fragment in content for expected_fragment in expected_fragments)+++def test_chinese_reference_line_only_marks_the_reference() -> None:+ """验证短行中数字引用占优时,正文“依据”和句号不会反向误判为下标。"""+ chars = _contiguous_chars_containing(+ _DEMO_PDF_DIR / "中文论文.pdf",+ 1,+ "依据[14-17]。",+ )++ content = _render_chars(chars)++ assert content == "依据<sup>[14-17]</sup>。"+ assert "<sub>" not in content+++ ("page_index", "probe"),+ [+ pytest.param(4, "• 技术支持工程师", id="bullet-text"),+ pytest.param(5, "• Acuity Toolkit", id="mixed-font-bullet-text"),+ pytest.param(6, "• Ubuntu 16.04", id="version-bullet-text"),+ pytest.param(+ 10,+ "Vivante_acuity_toolkit_binary_6.6.1_20220329_ubuntu20.04.tgz",+ id="filename-descender",+ ),+ ],+)+def test_npu_plain_text_does_not_gain_script_tags(page_index: int, probe: str) -> None:+ """验证项目符号、混合字体和文件名降部字符不会驱动整行上下标误判。"""+ matching_lines = _lines_chars_containing(+ _DEMO_PDF_DIR / "NPU_开发环境部署_参考指南.pdf",+ page_index,+ probe,+ )+ contents = [_render_chars(chars) for chars in matching_lines]++ assert contents+ assert all("<sup>" not in content and "<sub>" not in content for content in contents)+++def test_rotated_powerpoint_page_keeps_all_plain_text_on_baseline() -> None:+ """验证 PowerPoint 旋转页的紧字形框不会把普通升部和降部误判为上下标。"""+ 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+ ]++ assert page.rotation == 90+ assert any((char.get("font") or {}).get("name") == "CalifornianFB-Reg" for char in page_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)