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: implement native script markup detection and handling for superscripts and subscripts
myhloli52c31ffe709e
diff --git a/mineru/backend/analysis/pdf/text/content.py b/mineru/backend/analysis/pdf/text/content.pyindex cd22b2c5..1167c629 100644--- a/mineru/backend/analysis/pdf/text/content.py+++ b/mineru/backend/analysis/pdf/text/content.py@@ -16,6 +16,7 @@ from .....model.ocr.image import rotate_vertical_crop_if_neededfrom .....model.ocr.results import OcrConfidencefrom .....model.flash.pdf.document import PDFPage, get_lines_from_charsfrom .....model.flash.pdf.text_styles import (+ PDF_NATIVE_SCRIPT_MARKUP_KEY,PDFTextLinkLine,PDFTextStyleLine,apply_pdf_text_links,@@ -268,6 +269,15 @@ def _lines_to_block_content(lines: list[_AnalyzeLine], block_type: str) -> str:)+def _lines_have_native_script_markup(lines: list[_AnalyzeLine]) -> bool:+ """判断组行结果是否实际包含 detector-owned 上下标标签。"""+ return any(+ span.metadata.get(PDF_NATIVE_SCRIPT_MARKUP_KEY) is True and ("<sup>" in span.content or "<sub>" in span.content)+ for line in lines+ for span in line.spans+ )++def _build_ocr_det_line_items(lines: list[_AnalyzeLine], page_size: tuple[float, float]) -> list[dict[str, Any]]:"""将 Analyze 私有行转换为归一化行框。"""line_items = []@@ -298,6 +308,8 @@ def _apply_block_content_and_line_metadata(has_nonempty_content = bool(block_content.strip()) if isinstance(block_content, str) else bool(block_content)if not has_nonempty_content:block_item["content"] = _lines_to_block_content(lines, block_type)+ if _lines_have_native_script_markup(lines):+ block_item[PDF_NATIVE_SCRIPT_MARKUP_KEY] = Trueif block_type in LINE_METADATA_BLOCK_TYPES:block_item["lines"] = _build_ocr_det_line_items(lines, page_size)diff --git a/mineru/backend/analysis/pdf/text/native.py b/mineru/backend/analysis/pdf/text/native.pyindex 8aae32c5..1c4aa217 100644--- a/mineru/backend/analysis/pdf/text/native.py+++ b/mineru/backend/analysis/pdf/text/native.py@@ -9,7 +9,7 @@ import reimport statisticsimport unicodedatafrom dataclasses import dataclass-from typing import Any, Callable, Literal+from typing import Any, Callable, Literal, castimport cv2import numpy as np@@ -19,6 +19,7 @@ from pdftext.schema import Charfrom .....types import BBox, BlockType, ContentTypefrom .....utils.image import calculate_contrastfrom .....model.flash.pdf.document import PDFPage, get_lines_from_chars+from .....model.flash.pdf.text_styles import PDF_NATIVE_SCRIPT_MARKUP_KEYfrom ..images import get_crop_imgfrom .....utils.geometry import calculate_overlap_area_in_bbox1_area_ratiofrom .models import _AnalyzeSpan@@ -33,6 +34,23 @@ POST_OCR_FALLBACK_CONTENT_KEY = "_post_ocr_fallback_content"POST_OCR_FALLBACK_SCORE_KEY = "_post_ocr_fallback_score"POST_OCR_REASON_KEY = "_post_ocr_reason"POST_OCR_REASON_PRIVATE_USE_TEXT = "private_use_text"+SPACING_DIACRITIC_MIN_OVERLAP_RATIO = 0.5+_SPACING_DIACRITIC_TO_COMBINING = {+ "`": "\u0300",+ "^": "\u0302",+ "¨": "\u0308",+ "¯": "\u0304",+ "´": "\u0301",+ "¸": "\u0327",+ "ˆ": "\u0302",+ "ˇ": "\u030c",+ "˘": "\u0306",+ "˙": "\u0307",+ "˚": "\u030a",+ "˛": "\u0328",+ "˜": "\u0303",+ "˝": "\u030b",+}def __replace_ligatures(text: str) -> str:@@ -207,8 +225,7 @@ def _get_chars_for_span_fill(page_chars: list[Char] | dict[str, list[Char]]) ->char_rotation = float(char.get("rotation", 0))if (not _is_supported_rotation(char_rotation)- and _rotation_distance_degrees(char_rotation, line_rotation)- <= SPAN_FILL_LOCAL_ROTATION_MAX_DEGREES+ and _rotation_distance_degrees(char_rotation, line_rotation) <= SPAN_FILL_LOCAL_ROTATION_MAX_DEGREES):fill_char_keys.add(_get_char_fill_key(char))@@ -635,9 +652,7 @@ def _estimate_script_body_band(features: list[_ScriptCharFeature]) -> _ScriptBodreturn Nonebody_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- ]+ full_height_anchors = [feature for feature in anchors if feature.height >= body_height * SCRIPT_BODY_FULL_HEIGHT_RATIO]if not full_height_anchors:return Nonereturn _ScriptBodyBand(@@ -655,10 +670,7 @@ def _is_script_identifier_char(text: str) -> bool:if not text.isalpha():return Falseunicode_name = unicodedata.name(text, "")- return not any(- marker in unicode_name- for marker in ("CJK", "HIRAGANA", "KATAKANA", "HANGUL", "BOPOMOFO")- )+ return not any(marker in unicode_name for marker in ("CJK", "HIRAGANA", "KATAKANA", "HANGUL", "BOPOMOFO"))def _estimate_main_font_body_band(features: list[_ScriptCharFeature]) -> _ScriptBodyBand | None:@@ -667,9 +679,7 @@ def _estimate_main_font_body_band(features: list[_ScriptCharFeature]) -> _Scriptif not voters:return None- font_counts: dict[tuple[Any, Any], int] = collections.Counter(- feature.font_signature for feature in voters- )+ 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)@@ -679,9 +689,7 @@ def _estimate_main_font_body_band(features: list[_ScriptCharFeature]) -> _Script)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- ]+ 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,@@ -703,10 +711,7 @@ def _get_structure_script_role(open_offset = open_feature.center_y - body_band.center_yclose_offset = close_feature.center_y - body_band.center_yminimum_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- ):+ if open_offset * close_offset <= 0 or min(abs(open_offset), abs(close_offset)) < minimum_offset:return Nonereturn _get_script_role((open_offset + close_offset) / 2)@@ -720,8 +725,10 @@ def _is_numeric_square_reference(if features[open_index].text not in SCRIPT_NUMERIC_REFERENCE_OPENERS:return Falseinner_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+ 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))@@ -907,14 +914,78 @@ def _wrap_script_runs(role_text_parts: list[tuple[str, str]]) -> str:return "".join(wrapped_parts)+def _axis_overlap_ratio(first_bbox: Any, second_bbox: Any, start_index: int, end_index: int) -> float:+ """计算两个字符框在指定坐标轴上相对较短边的重叠比例。"""+ try:+ first_start = float(first_bbox[start_index])+ first_end = float(first_bbox[end_index])+ second_start = float(second_bbox[start_index])+ second_end = float(second_bbox[end_index])+ except (IndexError, TypeError, ValueError):+ return 0.0+ denominator = min(first_end - first_start, second_end - second_start)+ if denominator <= 0:+ return 0.0+ overlap = max(0.0, min(first_end, second_end) - max(first_start, second_start))+ return overlap / denominator+++def _compose_overlapping_spacing_diacritic(base: Char, modifier: Char) -> Char | None:+ """把与字母 bbox 重叠的 spacing diacritic 规范化为单一 NFC 字符。"""+ base_text = str(base.get("char", ""))+ modifier_text = str(modifier.get("char", ""))+ combining = _SPACING_DIACRITIC_TO_COMBINING.get(modifier_text)+ if (+ len(base_text) != 1+ or combining is None+ or not unicodedata.category(base_text).startswith("L")+ or _axis_overlap_ratio(base.get("bbox"), modifier.get("bbox"), 0, 2) < SPACING_DIACRITIC_MIN_OVERLAP_RATIO+ or _axis_overlap_ratio(base.get("bbox"), modifier.get("bbox"), 1, 3) < SPACING_DIACRITIC_MIN_OVERLAP_RATIO+ ):+ return None+ composed = unicodedata.normalize("NFC", f"{base_text}{combining}")+ if len(composed) != 1 or composed == base_text:+ return None+ merged = dict(base)+ merged["char"] = composed+ base_index = base.get("char_idx")+ modifier_index = modifier.get("char_idx")+ if isinstance(base_index, int) and isinstance(modifier_index, int):+ merged["char_idx"] = min(base_index, modifier_index)+ return cast(Char, merged)+++def _merge_overlapping_spacing_diacritics(chars: list[Char]) -> list[Char]:+ """合并字符流中位于基字符前后且几何重叠的 spacing diacritic。"""+ merged_chars: list[Char] = []+ cursor = 0+ while cursor < len(chars):+ current = chars[cursor]+ following = chars[cursor + 1] if cursor + 1 < len(chars) else None+ merged: Char | None = None+ if following is not None and str(current.get("char", "")) in _SPACING_DIACRITIC_TO_COMBINING:+ merged = _compose_overlapping_spacing_diacritic(following, current)+ elif following is not None and str(following.get("char", "")) in _SPACING_DIACRITIC_TO_COMBINING:+ merged = _compose_overlapping_spacing_diacritic(current, following)+ if merged is not None:+ merged_chars.append(merged)+ cursor += 2+ continue+ merged_chars.append(current)+ cursor += 1+ return merged_chars++def chars_to_content(span: _AnalyzeSpan) -> None:"""将 Span 内字符重建为文本,并合并连续的上标、下标片段。"""+ span.metadata.pop(PDF_NATIVE_SCRIPT_MARKUP_KEY, None)# 检查span中的char是否为空if len(span.metadata["chars"]) != 0:chars = span.metadata["chars"]# 大多数情况下 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)char_metrics = _get_char_bbox_metrics_list(chars)# Calculate the width of each character@@ -946,5 +1017,7 @@ def chars_to_content(span: _AnalyzeSpan) -> None:content = __replace_unicode(content)content = __replace_ligatures(content)span.content = content.strip()+ if any(role in {"sup", "sub"} and text for role, text in role_text_parts):+ span.metadata[PDF_NATIVE_SCRIPT_MARKUP_KEY] = Truedel span.metadata["chars"]diff --git a/mineru/model/flash/pdf/text_styles.py b/mineru/model/flash/pdf/text_styles.pyindex 9ac6097b..c7723a8d 100644--- a/mineru/model/flash/pdf/text_styles.py+++ b/mineru/model/flash/pdf/text_styles.py@@ -41,6 +41,8 @@ PDF_LINK_CHAR_OVERLAP_THRESHOLD = 0.5PDFTextStyle = Literal["bold", "italic", "underline", "strikethrough"]_PDF_LINK_INTERVALS_KEY = "_inline_link_intervals"_PDF_STYLE_INTERVALS_KEY = "_inline_style_intervals"+PDF_NATIVE_SCRIPT_MARKUP_KEY = "_pdf_native_script_markup"+_NATIVE_SCRIPT_TAG_RE = re.compile(r"<(?P<closing>/)?(?P<tag>sup|sub)>")_PDF_INLINE_SPAN_BLOCK_TYPES = {BlockType.TEXT,BlockType.REF_TEXT,@@ -217,6 +219,14 @@ class _RawStyleInterval:styles: tuple[PDFTextStyle, ...]+@dataclass(frozen=True, slots=True)+class _NativeScriptMarkup:+ """保存 detector-owned 上下标标签边界及对应原文样式区间。"""++ marker_ranges: tuple[tuple[int, int], ...]+ style_intervals: tuple[tuple[int, int, str], ...]++@dataclass(frozen=True, slots=True)class _MatchedLinkRange:"""保存已经对齐到 block 可比较文本的链接区间与物理行身份。"""@@ -1799,10 +1809,37 @@ def apply_pdf_text_styles(block[_PDF_STYLE_INTERVALS_KEY] = intervals+def _parse_native_script_markup(content: str) -> _NativeScriptMarkup | None:+ """严格解析 detector-owned 平坦 sup/sub 标签;畸形或嵌套结构返回 None。"""+ marker_ranges: list[tuple[int, int]] = []+ style_intervals: list[tuple[int, int, str]] = []+ active: tuple[str, int] | None = None+ for match in _NATIVE_SCRIPT_TAG_RE.finditer(content):+ marker_ranges.append((match.start(), match.end()))+ style = "superscript" if match.group("tag") == "sup" else "subscript"+ if match.group("closing") is None:+ if active is not None:+ return None+ active = (style, match.end())+ continue+ if active is None or active[0] != style:+ return None+ if active[1] < match.start():+ style_intervals.append((active[1], match.start(), style))+ active = None+ if active is not None or not marker_ranges:+ return None+ return _NativeScriptMarkup(+ marker_ranges=tuple(marker_ranges),+ style_intervals=tuple(style_intervals),+ )++def materialize_pdf_inline_spans(blocks: list[dict[str, Any]]) -> None:"""把 PDF 原文、样式区间、链接区间和行内公式一次性物化为 Span。"""formula_pattern = re.compile(r"\\\((?P<latex>.*?)\\\)", re.DOTALL)for block in blocks:+ owns_native_script_markup = block.pop(PDF_NATIVE_SCRIPT_MARKUP_KEY, False) is Trueif block.get("type") not in _PDF_INLINE_SPAN_BLOCK_TYPES:continuecontent = block.get("content")@@ -1810,10 +1847,17 @@ def materialize_pdf_inline_spans(blocks: list[dict[str, Any]]) -> None:style_intervals = block.pop(_PDF_STYLE_INTERVALS_KEY, [])if not isinstance(content, str):continue+ native_scripts = _parse_native_script_markup(content) if owns_native_script_markup else None+ marker_ranges = native_scripts.marker_ranges if native_scripts is not None else ()+ script_intervals = native_scripts.style_intervals if native_scripts is not None else ()formulas = list(formula_pattern.finditer(content))boundaries = {0, len(content)}for interval in [*link_intervals, *style_intervals]:boundaries.update((interval.start, interval.end))+ for start, end in marker_ranges:+ boundaries.update((start, end))+ for start, end, _style in script_intervals:+ boundaries.update((start, end))for formula in formulas:boundaries.update((formula.start(), formula.end()))ordered = sorted(value for value in boundaries if 0 <= value <= len(content))@@ -1821,6 +1865,8 @@ def materialize_pdf_inline_spans(blocks: list[dict[str, Any]]) -> None:for start, end in zip(ordered, ordered[1:]):if start >= end:continue+ if any(marker_start <= start and end <= marker_end for marker_start, marker_end in marker_ranges):+ continueformula = next((item for item in formulas if item.start() == start and item.end() == end), None)if formula is not None:append_equation_span(spans, formula.group("latex"))@@ -1834,23 +1880,29 @@ def materialize_pdf_inline_spans(blocks: list[dict[str, Any]]) -> None:if interval.start <= start and end <= interval.endfor style in interval.styles)+ script_styles = tuple(+ style+ for interval_start, interval_end, style in script_intervals+ if interval_start <= start and end <= interval_end+ )+ combined_styles = tuple(dict.fromkeys((*styles, *script_styles)))link = next((interval for interval in link_intervals if interval.start <= start and end <= interval.end),None,)if link is None:- if styles and text.strip():+ if combined_styles and text.strip():leading_length = len(text) - len(text.lstrip())trailing_length = len(text) - len(text.rstrip())core_end = len(text) - trailing_length if trailing_length else len(text)append_text_span(spans, text[:leading_length])- append_text_span(spans, text[leading_length:core_end], styles)+ append_text_span(spans, text[leading_length:core_end], combined_styles)append_text_span(spans, text[core_end:])else:- append_text_span(spans, text, styles)+ append_text_span(spans, text, combined_styles)continuechildren: list[dict[str, Any]] = []- append_text_span(children, text, (style for style in styles if style != "underline"))+ append_text_span(children, text, (style for style in combined_styles if style != "underline"))if spans and spans[-1].get("type") == "hyperlink" and spans[-1].get("url") == link.target:existing = spans[-1].get("content")if isinstance(existing, list):@@ -1861,6 +1913,7 @@ def materialize_pdf_inline_spans(blocks: list[dict[str, Any]]) -> None:__all__ = [+ "PDF_NATIVE_SCRIPT_MARKUP_KEY","PDF_FONT_FORCE_BOLD_FLAG","PDF_FONT_ITALIC_FLAG","PDFTextLinkLine",diff --git a/mineru/render/_internal/pdf/inline.py b/mineru/render/_internal/pdf/inline.pyindex 9c84df21..192c497c 100644--- a/mineru/render/_internal/pdf/inline.py+++ b/mineru/render/_internal/pdf/inline.py@@ -17,7 +17,7 @@ from reportlab.platypus.paraparser import ParaParserfrom ....types import CodeInlineSpan, EquationInlineSpan, HyperlinkSpan, InlineSpan, TextSpanfrom .formula import FormulaRenderer, InlineFormulaImage, PdfFormulaError-from .styles import ACCENT_COLOR, HAN_FONT, JAPANESE_FONT, KOREAN_FONT, MONO_FONT+from .styles import ACCENT_COLOR, HAN_FONT, JAPANESE_FONT, KOREAN_FONT, MONO_FONT, UNICODE_FALLBACK_FONT_BOOKMARK_SAFE_RE = re.compile(r"[^A-Za-z0-9_]+")_BOOKMARK_MAX_LENGTH = 80@@ -313,7 +313,7 @@ def _resolve_link_target(url: str, anchors: PdfAnchorRegistry) -> str | None:def _font_for_character(character: str) -> str | None:- """按 Unicode 区段为中日韩及其它非 Latin 字符选择标准 CID 字体。"""+ """为中日韩字符选择 CID 字体,并为非 WinAnsi 字符选择 Unicode 回退。"""codepoint = ord(character)if 0x3040 <= codepoint <= 0x30FF or 0x31F0 <= codepoint <= 0x31FF or 0xFF66 <= codepoint <= 0xFF9D:return JAPANESE_FONT@@ -325,9 +325,13 @@ def _font_for_character(character: str) -> str | None:or 0x4E00 <= codepoint <= 0x9FFFor 0xF900 <= codepoint <= 0xFAFFor 0xFF00 <= codepoint <= 0xFF65- or codepoint >= 0x10000+ or 0x20000 <= codepoint <= 0x2FA1F):return HAN_FONT+ try:+ character.encode("cp1252")+ except UnicodeEncodeError:+ return UNICODE_FALLBACK_FONTreturn Nonediff --git a/mineru/render/_internal/pdf/styles.py b/mineru/render/_internal/pdf/styles.pyindex d80a83e8..9ae3b516 100644--- a/mineru/render/_internal/pdf/styles.py+++ b/mineru/render/_internal/pdf/styles.py@@ -4,6 +4,7 @@from __future__ import annotationsfrom dataclasses import dataclass+from importlib import resourcesfrom threading import RLockfrom reportlab.lib import colors@@ -11,6 +12,7 @@ from reportlab.lib.enums import TA_CENTER, TA_LEFTfrom reportlab.lib.styles import ParagraphStylefrom reportlab.lib.units import mmfrom reportlab.pdfbase import cidfonts, pdfmetrics+from reportlab.pdfbase.ttfonts import TTFontPAGE_MARGIN = 20 * mmBODY_FONT = "Helvetica"@@ -19,6 +21,7 @@ MONO_FONT = "Courier"HAN_FONT = "STSong-Light"JAPANESE_FONT = "HeiseiMin-W3"KOREAN_FONT = "HYSMyeongJo-Medium"+UNICODE_FALLBACK_FONT = "MinerU-DejaVuSans"ACCENT_COLOR = colors.HexColor("#0b6fc2")BACKGROUND_COLOR = colors.HexColor("#ffffff")@@ -53,7 +56,7 @@ class PdfStyleSet:def build_pdf_styles() -> PdfStyleSet:"""注册标准 CID 字体并构造无外部字体依赖的打印样式集。"""- _register_cid_fonts()+ _register_pdf_fonts()body = ParagraphStyle("MinerU PDF Body",fontName=BODY_FONT,@@ -165,13 +168,23 @@ def build_pdf_styles() -> PdfStyleSet:)-def _register_cid_fonts() -> None:- """在进程级 ReportLab registry 中幂等注册中日韩标准 CID 字体。"""+def _register_pdf_fonts() -> None:+ """幂等注册中日韩 CID 字体与 ziafont 自带 Unicode 回退字体。"""with _FONT_LOCK:registered = set(pdfmetrics.getRegisteredFontNames())for font_name in (HAN_FONT, JAPANESE_FONT, KOREAN_FONT):if font_name not in registered:pdfmetrics.registerFont(cidfonts.UnicodeCIDFont(font_name))+ if UNICODE_FALLBACK_FONT not in registered:+ font_path = resources.files("ziafont").joinpath("fonts", "DejaVuSans.ttf")+ pdfmetrics.registerFont(TTFont(UNICODE_FALLBACK_FONT, str(font_path)))+ pdfmetrics.registerFontFamily(+ UNICODE_FALLBACK_FONT,+ normal=UNICODE_FALLBACK_FONT,+ bold=UNICODE_FALLBACK_FONT,+ italic=UNICODE_FALLBACK_FONT,+ boldItalic=UNICODE_FALLBACK_FONT,+ )__all__ = [@@ -189,5 +202,6 @@ __all__ = ["PdfStyleSet","SURFACE_COLOR","TEXT_COLOR",+ "UNICODE_FALLBACK_FONT","build_pdf_styles",]diff --git a/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.pyindex d9896710..4f5cccaa 100644--- a/tests/unittest/test_pdf_analyze_block_content.py+++ b/tests/unittest/test_pdf_analyze_block_content.py@@ -18,6 +18,7 @@ from mineru.backend.analysis.pdf.text.native import (POST_OCR_FALLBACK_CONTENT_KEY,POST_OCR_FALLBACK_SCORE_KEY,)+from mineru.model.flash.pdf.text_styles import PDF_NATIVE_SCRIPT_MARKUP_KEY, materialize_pdf_inline_spansfrom mineru.types import BlockType, ContentType, MiddleJson, ModelJsonfrom _span_test_utils import inline, inline_text@@ -645,3 +646,36 @@ def test_existing_text_content_is_preserved_while_lines_are_refreshed() -> None:assert block["content"] == "existing content"assert block["lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]+++def test_native_script_ownership_propagates_only_when_content_is_filled() -> None:+ """验证原生脚本标记只随空 block 回填,并在 MiddleJson 边界前被消费。"""+ owned_line = _AnalyzeLine(+ bbox=(0.0, 0.0, 100.0, 1.0),+ spans=[+ _AnalyzeSpan(+ type=ContentType.TEXT,+ bbox=(0.0, 0.0, 100.0, 1.0),+ content="A<sup>2</sup>",+ metadata={PDF_NATIVE_SCRIPT_MARKUP_KEY: True},+ )+ ],+ )+ filled_block = {"type": BlockType.TEXT, "content": ""}+ existing_block = {"type": BlockType.TEXT, "content": "literal <sup>text</sup>"}++ text_content._apply_block_content_and_line_metadata(+ [filled_block, existing_block],+ {0: [owned_line], 1: [owned_line]},+ (100.0, 100.0),+ )++ assert filled_block[PDF_NATIVE_SCRIPT_MARKUP_KEY] is True+ assert PDF_NATIVE_SCRIPT_MARKUP_KEY not in existing_block++ materialize_pdf_inline_spans([filled_block, existing_block])++ assert inline_text(filled_block["content"]) == "A2"+ assert filled_block["content"][1]["styles"] == ["superscript"]+ assert inline_text(existing_block["content"]) == "literal <sup>text</sup>"+ assert PDF_NATIVE_SCRIPT_MARKUP_KEY not in filled_blockdiff --git a/tests/unittest/test_pdf_native_script_detection.py b/tests/unittest/test_pdf_native_script_detection.pyindex fff552ae..928f2f14 100644--- a/tests/unittest/test_pdf_native_script_detection.py+++ b/tests/unittest/test_pdf_native_script_detection.py@@ -8,8 +8,9 @@ from pdftext.schema import Bbox, Charfrom mineru.backend.analysis.pdf.text import nativefrom mineru.backend.analysis.pdf.text.models import _AnalyzeSpan-from mineru.types import ContentTypefrom mineru.model.flash.pdf.document import PDFDocument+from mineru.model.flash.pdf.text_styles import PDF_NATIVE_SCRIPT_MARKUP_KEY+from mineru.types import ContentType_PROJECT_ROOT = Path(__file__).resolve().parents[2]@@ -26,9 +27,7 @@ def _lines_chars_containing(pdf_path: Path, page_index: int, probe: str) -> listline_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([char for span in line["spans"] for char in span.get("chars", [])])return matching_lines@@ -147,6 +146,57 @@ def test_strong_geometry_seed_absorbs_same_side_punctuation() -> None:assert _render_chars(chars) == "A<sup>2,</sup>"+def test_script_markup_records_detector_ownership() -> None:+ """验证只有脚本检测实际生成标签时才写入私有 ownership 标记。"""+ script_span = _AnalyzeSpan(+ type=ContentType.TEXT,+ bbox=(0.0, 0.0, 1.0, 1.0),+ metadata={+ "chars": [+ _script_char(0, "A", height=10.0, center_y=10.0),+ _script_char(1, "2", height=7.0, center_y=7.0),+ ]+ },+ )+ body_span = _AnalyzeSpan(+ type=ContentType.TEXT,+ bbox=(0.0, 0.0, 1.0, 1.0),+ metadata={+ "chars": [+ _script_char(0, "A", height=10.0, center_y=10.0),+ _script_char(1, "B", height=10.0, center_y=10.0),+ ]+ },+ )++ native.chars_to_content(script_span)+ native.chars_to_content(body_span)++ 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_overlapping_spacing_ogonek_composes_demo2_author_name() -> None:+ """验证 demo2 原生字符流中与 e 重叠的 spacing ogonek 合成为 ę。"""+ content = _render_pdf_line(_DEMO_PDF_DIR / "demo2.pdf", 0, "Kowalczuk")++ assert content.startswith("Jędrzej Kowalczuk")+ assert "\u02db" not in content+++def test_non_overlapping_spacing_ogonek_remains_literal() -> None:+ """验证没有几何重叠的 spacing ogonek 不会被字符规范化误合并。"""+ chars = [+ _script_char(0, "˛", height=10.0, center_y=10.0),+ _script_char(1, "e", height=10.0, center_y=10.0),+ ]++ merged = native._merge_overlapping_spacing_diacritics(chars)++ assert [char["char"] for char in merged] == ["˛", "e"]++def test_font_suffix_seed_keeps_its_base_character_body() -> None:"""验证局部字体后缀只标记后缀,受保护的基字符不能被组件吸收。"""chars = [@@ -368,11 +418,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 chars in matching_lines for char in chars}assert contentsassert len(font_names) >= minimum_font_count@@ -387,10 +433,7 @@ def test_rotated_powerpoint_page_keeps_all_plain_text_on_baseline() -> None: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- ]+ rendered_lines = [_render_chars([char for span in line["spans"] for char in span.get("chars", [])]) for line in lines]assert page.rotation == 90assert any((char.get("font") or {}).get("name") == "CalifornianFB-Reg" for char in page_chars)diff --git a/tests/unittest/test_pdf_render.py b/tests/unittest/test_pdf_render.pyindex 1c86a651..3cc75794 100644--- a/tests/unittest/test_pdf_render.py+++ b/tests/unittest/test_pdf_render.py@@ -144,6 +144,31 @@ def test_pdf_renders_inline_and_display_formulas_as_vector_paths_with_links() ->assert b" m" in stream and (b" c" in stream or b" l" in stream)+def test_pdf_unicode_fallback_and_script_styles_avoid_black_squares() -> None:+ """验证 Latin Extended、独立重音、希腊文和西里尔文使用确定性字体回退。"""+ middle = _middle(+ _page(+ 0,+ TextBlock(+ type="text",+ index=0,+ content=[+ {"type": "text", "content": "Jędrzej J˛edrzej λ Ж 中文 x"},+ {"type": "text", "content": "2", "styles": ["superscript"]},+ ],+ ),+ )+ )++ reader = _reader(render_pdf(middle))+ text = _page_text(reader, 0)+ stream = reader.pages[0].get_contents().get_data()++ assert "Jędrzej J˛edrzej λ Ж 中文 x2" in text.replace("\n", "")+ assert "■" not in text+ assert b" Ts" in stream++def test_pdf_formula_failures_fall_back_to_visible_latex(monkeypatch: pytest.MonkeyPatch) -> None:"""验证 ZiaMath 失败时行内与行间公式均保留可见 LaTeX。"""original_render = FormulaRenderer.renderdiff --git a/tests/unittest/test_pdf_text_styles.py b/tests/unittest/test_pdf_text_styles.pyindex 4da53b78..0ae7761d 100644--- a/tests/unittest/test_pdf_text_styles.py+++ b/tests/unittest/test_pdf_text_styles.py@@ -31,6 +31,7 @@ from mineru.model.flash.pdf.document import PDFDocument, PDFLinkAnnotationfrom mineru.model.flash.pdf.text_styles import (PDF_FONT_FORCE_BOLD_FLAG,PDF_FONT_ITALIC_FLAG,+ PDF_NATIVE_SCRIPT_MARKUP_KEY,PDFTextLinkLine,PDFTextLinkRange,PDFTextStyleLine,@@ -1533,6 +1534,86 @@ def test_applies_style_inside_superscript_without_crossing_tags() -> None:assert _span_snapshot(blocks[0]["content"]) == ('value <sup><text style="strikethrough">deleted</text></sup> tail')+ ("tag", "style"),+ [+ ("sup", "superscript"),+ ("sub", "subscript"),+ ],+)+def test_materializes_owned_script_markup(tag: str, style: str) -> None:+ """验证 producer-owned 上标与下标标签都转换为结构化 TextSpan 样式。"""+ block = {+ "type": BlockType.TEXT,+ "content": f"A<{tag}>2</{tag}>B",+ PDF_NATIVE_SCRIPT_MARKUP_KEY: True,+ }++ materialize_pdf_inline_spans([block])++ assert _span_snapshot(block["content"]) == f'A<text style="{style}">2</text>B'+ assert PDF_NATIVE_SCRIPT_MARKUP_KEY not in block+++def test_materializes_owned_superscript_with_style_and_hyperlink() -> None:+ """验证 producer-owned 上标会与删除线和链接语义共同物化。"""+ target = "https://script.example.test"+ blocks = [+ {+ "type": BlockType.TEXT,+ "bbox": [0.0, 0.0, 1.0, 1.0],+ "content": "value <sup>ref</sup> tail",+ PDF_NATIVE_SCRIPT_MARKUP_KEY: True,+ }+ ]+ link_lines = [+ PDFTextLinkLine(+ (10.0, 10.0, 90.0, 20.0),+ "valuereftail",+ (PDFTextLinkRange(5, 8, target),),+ 0,+ )+ ]+ style_lines = [+ PDFTextStyleLine(+ (10.0, 10.0, 90.0, 20.0),+ "valuereftail",+ (PDFTextStyleRange(5, 8, ("strikethrough",)),),+ 0,+ )+ ]++ apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))+ apply_pdf_text_styles(blocks, style_lines, (100.0, 100.0))++ assert _span_snapshot(blocks[0]["content"]) == (+ f'value <hyperlink><text style="strikethrough,superscript">ref</text><url>{target}</url></hyperlink> tail'+ )+ assert PDF_NATIVE_SCRIPT_MARKUP_KEY not in blocks[0]+++ "content",+ [+ "A<sup>B</sub>",+ "A<sup><sub>B</sub></sup>",+ "A<sup>B",+ ],+)+def test_malformed_owned_script_markup_remains_literal(content: str) -> None:+ """验证不平衡或嵌套的 producer-owned 标签按普通字面文本回退。"""+ block = {+ "type": BlockType.TEXT,+ "content": content,+ PDF_NATIVE_SCRIPT_MARKUP_KEY: True,+ }++ materialize_pdf_inline_spans([block])++ assert inline_text(block["content"]) == content+ assert PDF_NATIVE_SCRIPT_MARKUP_KEY not in block++def test_filters_italic_before_merging_overlapping_style_ranges() -> None:"""验证过滤斜体后仍正确合并粗体、下划线与删除线区间。"""