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: replace line boundary resolution with merge function for text normalization
myhlolifc96f7ed26d4
diff --git a/mineru/backend/analysis/pdf/normalization.py b/mineru/backend/analysis/pdf/normalization.pyindex 542cfb05..0b3d7c7f 100644--- a/mineru/backend/analysis/pdf/normalization.py+++ b/mineru/backend/analysis/pdf/normalization.py@@ -4,6 +4,8 @@from __future__ import annotationsimport math+import re+from collections.abc import Callablefrom typing import Anyfrom mineru.types import BBox, BlockType, RAW_PHONETIC@@ -19,6 +21,8 @@ from .constants import ()from .geometry import _bbox_to_pixel_bbox+_URL_ELEMENT_PATTERN = re.compile(r"<url>.*?</url>", re.IGNORECASE | re.DOTALL)+def _collect_layout_doc_title_bboxes(layout_res: list[dict[str, Any]], page_size: tuple[int, int]) -> list[BBox]:"""只收集layout小模型输出的doc_title框,忽略paragraph_title等其他类型。"""@@ -89,8 +93,25 @@ def _is_valid_pdf_text_block(block: dict[str, Any]) -> bool:return True-def _normalize_natural_language_content(content: str) -> str:- """将自然语言中的全角字母和数字转为半角,同时原样保留行内公式片段。"""+def _transform_outside_url_elements(+ content: str,+ transform: Callable[[str], str],+) -> str:+ """仅转换 hyperlink 可见内容,原样保留结构化 URL 标签及其正文。"""++ parts: list[str] = []+ cursor = 0+ for match in _URL_ELEMENT_PATTERN.finditer(content):+ parts.append(transform(content[cursor : match.start()]))+ parts.append(match.group(0))+ cursor = match.end()+ parts.append(transform(content[cursor:]))+ return "".join(parts)+++def _normalize_natural_language_fragment(content: str) -> str:+ """规范自然语言片段中的全角字符,同时原样保留行内公式片段。"""+normalized_parts: list[str] = []cursor = 0formula_markers = (("\\(", "\\)"), ("<eq>", "</eq>"))@@ -117,6 +138,27 @@ def _normalize_natural_language_content(content: str) -> str:return "".join(normalized_parts)+def _normalize_natural_language_content(content: str) -> str:+ """规范自然语言可见文本,但不改写 hyperlink 的 URL 目标。"""++ return _transform_outside_url_elements(+ content,+ _normalize_natural_language_fragment,+ )+++def _normalize_inline_formula_markup(content: str) -> str:+ """只在 URL 标签外把反斜杠圆括号公式转换为 eq 标签。"""++ return _transform_outside_url_elements(+ content,+ lambda value: _INLINE_FORMULA_PATTERN.sub(+ lambda match: f"<eq>{match.group(1)}</eq>",+ value,+ ),+ )++def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:"""清理 PDF block 元数据、规范公式,并过滤正文或行框无效的文本块。"""for page_idx, page_model_list in enumerate(model_list):@@ -142,10 +184,7 @@ def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:continueif block.get("type") in NATURAL_LANGUAGE_CONTENT_BLOCK_TYPES:content = _normalize_natural_language_content(content)- block["content"] = _INLINE_FORMULA_PATTERN.sub(- lambda match: f"<eq>{match.group(1)}</eq>",- content,- )+ block["content"] = _normalize_inline_formula_markup(content)page_model_list[:] = [blockfor block in page_model_listdiff --git a/mineru/backend/analysis/pdf/tables.py b/mineru/backend/analysis/pdf/tables.pyindex 8591276b..b55697da 100644--- a/mineru/backend/analysis/pdf/tables.py+++ b/mineru/backend/analysis/pdf/tables.py@@ -21,7 +21,7 @@ from mineru.utils.bbox_utils import ()from mineru.utils.ocr_utils import mask_formula_regions_for_ocr_detfrom mineru.utils.pdf_document import PDFPage, get_lines_from_chars-from mineru.utils.pdf_text_styles import PDFTextStyleLine+from mineru.utils.pdf_text_styles import PDFTextLinkLine, PDFTextStyleLinefrom mineru.utils.spatial_text import project_ocr_table_text, project_pdf_table_textfrom .constants import (@@ -83,20 +83,24 @@ def _visual_line_items_to_spans(line_items: list[Any]) -> list[_AnalyzeSpan]:def _build_pdf_text_visual_run_data(pdf_page: PDFPage,-) -> tuple[list[_AnalyzeSpan], list[PDFTextStyleLine]]:- """一次构造 Low/TXT 视觉 span 和同页水平文本样式证据。"""+) -> tuple[list[_AnalyzeSpan], list[PDFTextStyleLine], list[PDFTextLinkLine]]:+ """一次构造 Low/TXT 视觉 span、文本样式和超链接证据。"""- _page_chars, line_items, style_lines = build_pdf_native_visual_lines_and_styles(- pdf_page,- supported_angles=_LOW_TXT_VISUAL_RUN_ANGLES,+ _page_chars, line_items, style_lines, link_lines = (+ build_pdf_native_visual_lines_and_styles(+ pdf_page,+ supported_angles=_LOW_TXT_VISUAL_RUN_ANGLES,+ ))- return _visual_line_items_to_spans(line_items), style_lines+ return _visual_line_items_to_spans(line_items), style_lines, link_linesdef _build_pdf_text_visual_run_spans(pdf_page: PDFPage) -> list[_AnalyzeSpan]:"""将 Low/TXT 原生粗行按 Flash 字符间隙拆成可独立分配的视觉 run。"""- page_spans, _style_lines = _build_pdf_text_visual_run_data(pdf_page)+ page_spans, _style_lines, _link_lines = _build_pdf_text_visual_run_data(+ pdf_page+ )return page_spansdiff --git a/mineru/backend/analysis/pdf/text/content.py b/mineru/backend/analysis/pdf/text/content.pyindex 73ad77ca..0c5b2b76 100644--- a/mineru/backend/analysis/pdf/text/content.py+++ b/mineru/backend/analysis/pdf/text/content.py@@ -15,10 +15,12 @@ from mineru.utils.language import detect_langfrom mineru.utils.ocr_utils import OcrConfidence, rotate_vertical_crop_if_neededfrom mineru.utils.pdf_document import PDFPage, get_lines_from_charsfrom mineru.utils.pdf_text_styles import (+ PDFTextLinkLine,PDFTextStyleLine,+ apply_pdf_text_links,apply_pdf_text_styles,)-from mineru.utils.text_utils import resolve_text_line_boundary+from mineru.utils.text_utils import merge_text_line_contentsfrom ..constants import (CODE_CONTENT_BLOCK_TYPES,@@ -258,15 +260,10 @@ def _lines_to_block_content(lines: list[_AnalyzeLine], block_type: str) -> str:content for parts in content_lines for span_type, content in parts if span_type == ContentType.TEXT)block_language = detect_lang(text_for_language)- content_parts = [rendered_lines[0]]- for line_idx in range(1, len(rendered_lines)):- content_parts[-1], separator = resolve_text_line_boundary(- content_parts[-1],- block_language=block_language,- next_content=rendered_lines[line_idx],- )- content_parts.extend([separator, rendered_lines[line_idx]])- return "".join(content_parts).strip()+ return merge_text_line_contents(+ rendered_lines,+ block_language=block_language,+ )def _build_ocr_det_line_items(lines: list[_AnalyzeLine], page_size: tuple[float, float]) -> list[dict[str, Any]]:@@ -332,6 +329,7 @@ def _fill_window_block_content_and_lines(dict[int, list[_AnalyzeLine]],tuple[float, float],list[PDFTextStyleLine],+ list[PDFTextLinkLine],]] = []for image_dict, pdf_page, page_model_list, page_inline_formula_list, page_ocr_res_list in zip(@@ -351,6 +349,7 @@ def _fill_window_block_content_and_lines(render_scale,)style_lines: list[PDFTextStyleLine] = []+ link_lines: list[PDFTextLinkLine] = []if parse_mode == "txt":page_chars = Nonetry:@@ -362,8 +361,10 @@ 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 = build_pdf_native_visual_lines_and_styles(- pdf_page,+ page_chars, _line_items, style_lines, link_lines = (+ build_pdf_native_visual_lines_and_styles(+ pdf_page,+ ))page_spans = _fill_native_pdf_text_spans(pdf_page,@@ -381,7 +382,13 @@ def _fill_window_block_content_and_lines(target_block_types,)page_block_line_results.append(- (page_model_list, block_lines, page_size, style_lines)+ (+ page_model_list,+ block_lines,+ page_size,+ style_lines,+ link_lines,+ ))if parse_mode == "txt":@@ -389,16 +396,27 @@ def _fill_window_block_content_and_lines(local_model_context,[block_lines- for _, block_lines, _, _style_lines in page_block_line_results+ for _, block_lines, _, _style_lines, _link_lines in page_block_line_results],)- for page_model_list, block_lines, page_size, style_lines in page_block_line_results:+ for (+ page_model_list,+ block_lines,+ page_size,+ style_lines,+ link_lines,+ ) in page_block_line_results:_apply_block_content_and_line_metadata(page_model_list,block_lines,page_size,)+ apply_pdf_text_links(+ page_model_list,+ link_lines,+ page_size,+ )apply_pdf_text_styles(page_model_list,style_lines,diff --git a/mineru/backend/analysis/pdf/text/styles.py b/mineru/backend/analysis/pdf/text/styles.pyindex ea140194..968a1a81 100644--- a/mineru/backend/analysis/pdf/text/styles.py+++ b/mineru/backend/analysis/pdf/text/styles.py@@ -1,5 +1,5 @@# Copyright (c) Opendatalab. All rights reserved.-"""Hybrid TXT 路径复用的 PDF 原生文本样式准备入口。"""+"""Hybrid TXT 路径复用的 PDF 原生文本富化准备入口。"""from __future__ import annotations@@ -9,7 +9,9 @@ from pdftext.schema import Charfrom mineru.utils.pdf_document import PDFPage, get_lines_from_charsfrom mineru.utils.pdf_text_styles import (+ PDFTextLinkLine,PDFTextStyleLine,+ detect_pdf_text_link_lines,detect_pdf_text_style_lines,)@@ -19,8 +21,13 @@ def build_pdf_native_visual_lines_and_styles(*,page_chars: list[Char] | None = None,supported_angles: Sequence[float] = (0.0,),-) -> tuple[list[Char], list[Any], list[PDFTextStyleLine]]:- """一次读取当前页字符,构造视觉 run 及其水平文本样式证据。"""+) -> tuple[+ list[Char],+ list[Any],+ list[PDFTextStyleLine],+ list[PDFTextLinkLine],+]:+ """一次读取当前页字符,构造视觉 run、文本样式和超链接证据。"""# 延迟导入避免 Hybrid 模块初始化时提前加载完整 Flash PDF 流水线。from mineru.model.flash.native_pdf.native_text import _build_native_line_items@@ -36,7 +43,11 @@ def build_pdf_native_visual_lines_and_styles(line_items,pdf_page.get_drawing_lines(),)- return chars, line_items, style_lines+ link_lines = detect_pdf_text_link_lines(+ line_items,+ pdf_page.get_link_annotations(),+ )+ return chars, line_items, style_lines, link_lines__all__ = ["build_pdf_native_visual_lines_and_styles"]diff --git a/mineru/backend/analysis/pdf/window.py b/mineru/backend/analysis/pdf/window.pyindex e45dec52..01c75dbe 100644--- a/mineru/backend/analysis/pdf/window.py+++ b/mineru/backend/analysis/pdf/window.py@@ -14,7 +14,7 @@ from mineru.types import RAW_FORMULA_NUMBER, BlockTypefrom mineru.utils.config_reader import get_processing_window_sizefrom mineru.utils.pdf_document import PDFDocument, PDFPagefrom mineru.utils.pdf_image_tools import load_images_from_pdf_bytes_range-from mineru.utils.pdf_text_styles import apply_pdf_text_styles+from mineru.utils.pdf_text_styles import apply_pdf_text_links, apply_pdf_text_stylesfrom mineru.utils.spatial_text import project_pdf_spatial_textfrom .constants import (@@ -190,7 +190,9 @@ def _process_low_text(target_block_types = set(PIPELINE_DET_TYPE) | TITLE_BLOCK_TYPES | {BlockType.TEXT}for pdf_page, page_model_list in zip(pdf_pages, model_list):page_size = tuple(float(value) for value in pdf_page.size)- page_spans, style_lines = _build_pdf_text_visual_run_data(pdf_page)+ page_spans, style_lines, link_lines = _build_pdf_text_visual_run_data(+ pdf_page+ )block_lines = _group_page_spans_by_block(page_model_list,page_spans,@@ -202,6 +204,11 @@ def _process_low_text(block_lines,page_size,)+ apply_pdf_text_links(+ page_model_list,+ link_lines,+ page_size,+ )apply_pdf_text_styles(page_model_list,style_lines,diff --git a/mineru/backend/postprocess/paragraphs.py b/mineru/backend/postprocess/paragraphs.pyindex 9a6c65af..4ab0834a 100644--- a/mineru/backend/postprocess/paragraphs.py+++ b/mineru/backend/postprocess/paragraphs.py@@ -1,7 +1,9 @@# Copyright (c) Opendatalab. All rights reserved."""PDF 段落延续关系的 raw model-list 后处理。"""+import htmlimport math+import refrom typing import Any, TypeAliasfrom ...types import PAGE_AUXILIARY_BLOCK_TYPES, BlockType@@ -30,6 +32,14 @@ VERTICAL_LINE_IN_BLOCK_THRESHOLD = 0.8SINGLE_LINE_LOOKAHEAD_LIMIT = 5SINGLE_LINE_MIN_ALIGNED_LOOKAHEAD = 3SINGLE_LINE_THICKNESS_RATIO_MAX = 1.5+_INLINE_URL_ELEMENT_RE = re.compile(+ r"<url>.*?</url>",+ re.IGNORECASE | re.DOTALL,+)+_KNOWN_INLINE_TAG_RE = re.compile(+ r"</?(?:eq|text|hyperlink|sup|sub|strong|b|em|i|s|u)(?:\s[^<>]*?)?>",+ re.IGNORECASE,+)BlockDict: TypeAlias = dict[str, Any]CalculationBBox: TypeAlias = tuple[int, int, int, int]@@ -291,9 +301,14 @@ def _metric_line_bboxes(block: BlockDict) -> list[CalculationBBox]:def _normalized_text_content(block: BlockDict) -> str:- """读取并去除 text block 内容首尾空白,非字符串内容按无文本处理。"""+ """读取 text block 可见文本,排除富文本标签和 hyperlink URL 目标。"""+content = block.get("content")- return content.strip() if isinstance(content, str) else ""+ if not isinstance(content, str):+ return ""+ content = _INLINE_URL_ELEMENT_RE.sub("", content)+ content = _KNOWN_INLINE_TAG_RE.sub("", content)+ return html.unescape(content).strip()def _bbox_union(line_bboxes: list[CalculationBBox]) -> CalculationBBox:diff --git a/mineru/model/flash/native_pdf/pipeline.py b/mineru/model/flash/native_pdf/pipeline.pyindex 9393e6e8..785a291d 100644--- a/mineru/model/flash/native_pdf/pipeline.py+++ b/mineru/model/flash/native_pdf/pipeline.py@@ -11,8 +11,11 @@ from typing import Anyfrom mineru.model.flash.xycut import sort_entriesfrom mineru.utils.pdf_document import PDFDocument, PDFImageInfo, get_lines_from_charsfrom mineru.utils.pdf_text_styles import (+ PDFTextLinkLine,PDFTextStyleLine,+ apply_pdf_text_links,apply_pdf_text_styles,+ detect_pdf_text_link_lines,detect_pdf_text_style_lines,)@@ -207,6 +210,7 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]page_sources: list[_PageSource] = []page_style_lines: list[list[PDFTextStyleLine]] = []+ page_link_lines: list[list[PDFTextLinkLine]] = []for page_idx in range(pdf_doc.page_count):page_size = page_sizes[page_idx]chars = pdf_doc.get_page_chars(page_idx)@@ -219,6 +223,12 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]page_style_lines.append(detect_pdf_text_style_lines(lines, drawing_lines))+ page_link_lines.append(+ detect_pdf_text_link_lines(+ lines,+ pdf_doc.get_page_link_annotations(page_idx),+ )+ )source = _PageSource(page_size=page_size,lines=lines,@@ -269,12 +279,14 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]])for page_index, prepared in enumerate(prepared_pages)]- for page_blocks, style_lines, page_size in zip(+ for page_blocks, style_lines, link_lines, page_size in zip(finalized_pages,page_style_lines,+ page_link_lines,page_sizes,strict=True,):+ apply_pdf_text_links(page_blocks, link_lines, page_size)apply_pdf_text_styles(page_blocks, style_lines, page_size)return finalized_pagesdiff --git a/mineru/model/flash/native_pdf/tables.py b/mineru/model/flash/native_pdf/tables.pyindex c758da38..f0681c9f 100644--- a/mineru/model/flash/native_pdf/tables.py+++ b/mineru/model/flash/native_pdf/tables.py@@ -11,7 +11,7 @@ from typing import Any, Literalfrom loguru import logger-from mineru.utils.text_utils import resolve_text_line_boundary+from mineru.utils.text_utils import merge_text_line_contentsfrom mineru.utils.spatial_text import project_pdf_table_textfrom mineru.types import BBoxfrom mineru.utils.pdf_document import PDFPathInfo@@ -2162,16 +2162,10 @@ def _merge_table_annotation_content(line_texts: list[str]) -> str:block_language = detect_lang("".join(normalized_lines))except Exception:block_language = ""- content_parts = [normalized_lines[0]]- for current_line in normalized_lines[1:]:- processed_previous, separator = resolve_text_line_boundary(- content_parts[-1],- block_language=block_language,- next_content=current_line,- )- content_parts[-1] = processed_previous- content_parts.extend([separator, current_line])- return "".join(content_parts).strip()+ return merge_text_line_contents(+ normalized_lines,+ block_language=block_language,+ )def _table_body_materialization_bbox(diff --git a/mineru/model/flash/native_pdf/text_blocks.py b/mineru/model/flash/native_pdf/text_blocks.pyindex d33ab6c7..56c46ffc 100644--- a/mineru/model/flash/native_pdf/text_blocks.py+++ b/mineru/model/flash/native_pdf/text_blocks.py@@ -11,7 +11,7 @@ from typing import Any, Sequencefrom mineru.utils.text_utils import (is_hyphen_at_line_end,- resolve_text_line_boundary,+ merge_text_line_contents,)from mineru.types import BBoxfrom mineru.utils.language import detect_lang@@ -2707,13 +2707,7 @@ def _merge_text_line_content(line_texts: Sequence[str]) -> str:block_language = detect_lang("".join(normalized_lines))except Exception:block_language = ""- content_parts = [normalized_lines[0]]- for current_line in normalized_lines[1:]:- processed_previous, separator = resolve_text_line_boundary(- content_parts[-1],- block_language=block_language,- next_content=current_line,- )- content_parts[-1] = processed_previous- content_parts.extend([separator, current_line])- return "".join(content_parts).strip()+ return merge_text_line_contents(+ normalized_lines,+ block_language=block_language,+ )diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.pyindex 6f7fea98..826beec6 100644--- a/mineru/utils/pdf_document.py+++ b/mineru/utils/pdf_document.py@@ -10,6 +10,7 @@ from contextlib import contextmanagerfrom dataclasses import dataclassfrom io import BytesIOfrom typing import Any, Iterator, Literal, TypeAlias, cast+from urllib.parse import urlsplitimport numpy as npimport pypdfium2 as pdfium@@ -41,6 +42,7 @@ DRAWING_LINE_MIN_LENGTH = 1.0DRAWING_THIN_RECT_MAX_THICKNESS = 2.0DRAWING_THIN_RECT_MIN_ASPECT_RATIO = 4.0PDF_IMAGE_FINGERPRINT_MAX_RAW_BYTES = 16 * 1024 * 1024+_PDF_EXTERNAL_LINK_SCHEMES = frozenset({"http", "https", "mailto", "tel"})try:from pdftext.pdf.chars import PageChars@@ -77,6 +79,15 @@ class PDFDrawingLine:orientation: Literal["horizontal", "vertical"]+@dataclass(frozen=True)+class PDFLinkAnnotation:+ """PDF 外部 URI Link 注解,区域坐标使用页面左上原点的 PDF point。"""++ target: str+ bboxes: tuple[BBox, ...]+ source_index: int++@dataclass(frozen=True)class PDFPathInfo:"""PDF Path 的可见几何和绘制特征,bbox 使用页面左上原点坐标。"""@@ -133,6 +144,11 @@ class PDFPage:return self.pdf_doc.get_page_drawing_lines(self._idx)+ def get_link_annotations(self) -> list[PDFLinkAnnotation]:+ """读取当前页已规范到视觉页面坐标的外部 URI Link 注解。"""++ return self.pdf_doc.get_page_link_annotations(self._idx)+class PDFDocument:"""A PDF file loaded in memory, with lazy pypdfium2 access.@@ -412,6 +428,22 @@ class PDFDocument:form_handle=getattr(self._pdf_doc, "formenv", None),)+ def get_page_link_annotations(self, page_idx: int) -> list[PDFLinkAnnotation]:+ """提取可见且目标安全的外部 URI Link 注解。"""++ with self._open_page(page_idx) as page:+ page_bbox = _normalize_pdf_page_bbox(page.get_bbox())+ try:+ page_rotation = int(page.get_rotation()) % 360+ except Exception:+ page_rotation = 0+ return _extract_page_link_annotations(+ page,+ self._pdf_doc.raw,+ page_bbox,+ page_rotation,+ )+# ------------------------------------------------------------------ ## Classification# ------------------------------------------------------------------ #@@ -1251,6 +1283,251 @@ def _form_bbox_from_object(return visual_left, visual_top, visual_right, visual_bottom+def _validate_pdf_external_link_target(value: str) -> str | None:+ """校验 PDF URI Action,只保留显式且可安全输出的外部链接。"""++ target = value.strip()+ if not target or any(+ ord(char) < 0x20+ or ord(char) == 0x7F+ or 0xD800 <= ord(char) <= 0xDFFF+ for char in target+ ):+ return None+ try:+ parsed = urlsplit(target)+ except ValueError:+ return None+ scheme = parsed.scheme.lower()+ if scheme not in _PDF_EXTERNAL_LINK_SCHEMES:+ return None+ if scheme in {"http", "https"}:+ try:+ if not parsed.netloc or parsed.hostname is None:+ return None+ except ValueError:+ return None+ elif not parsed.path:+ return None+ return target+++def _get_pdfium_uri_path(raw_doc: Any, raw_action: Any) -> str | None:+ """按 PDFium 两阶段缓冲区协议读取 URI Action 的 UTF-8 目标。"""++ try:+ required = int(+ pdfium_c.FPDFAction_GetURIPath(+ raw_doc,+ raw_action,+ None,+ 0,+ )+ )+ except Exception:+ return None+ if required <= 1:+ return None+ try:+ buffer = ctypes.create_string_buffer(required)+ actual = int(+ pdfium_c.FPDFAction_GetURIPath(+ raw_doc,+ raw_action,+ buffer,+ required,+ )+ )+ except Exception:+ return None+ if actual <= 1 or actual > required:+ return None+ raw_value = bytes(buffer.raw[: actual - 1])+ try:+ return raw_value.decode("utf-8")+ except UnicodeDecodeError:+ return None+++def _pdf_link_annotation_is_visible(page: pdfium.PdfPage, raw_link: Any) -> bool:+ """读取 Link 注解可见性;损坏或显式隐藏的注解均不参与文本富化。"""++ raw_annot = None+ try:+ raw_annot = pdfium_c.FPDFLink_GetAnnot(page.raw, raw_link)+ if not raw_annot:+ return False+ flags = int(pdfium_c.FPDFAnnot_GetFlags(raw_annot))+ except Exception:+ return False+ finally:+ if raw_annot:+ try:+ pdfium_c.FPDFPage_CloseAnnot(raw_annot)+ except Exception:+ pass+ hidden_flags = (+ pdfium_c.FPDF_ANNOT_FLAG_INVISIBLE+ | pdfium_c.FPDF_ANNOT_FLAG_HIDDEN+ | pdfium_c.FPDF_ANNOT_FLAG_NOVIEW+ )+ return not bool(flags & hidden_flags)+++def _visual_bbox_from_pdf_points(+ points: list[tuple[float, float]],+ page_bbox: BBox,+ page_rotation: int,+) -> BBox | None:+ """把 PDF 底左坐标点集转换并裁剪为视觉页面左上坐标 bbox。"""++ if not points or not all(+ math.isfinite(coordinate)+ for point in points+ for coordinate in point+ ):+ return None+ visual_points = [+ _transform_drawing_point(point, page_bbox, page_rotation)+ for point in points+ ]+ page_width, page_height = _drawing_page_size(page_bbox, page_rotation)+ visual_bbox = (+ max(0.0, min(point[0] for point in visual_points)),+ max(0.0, min(point[1] for point in visual_points)),+ min(page_width, max(point[0] for point in visual_points)),+ min(page_height, max(point[1] for point in visual_points)),+ )+ if visual_bbox[2] <= visual_bbox[0] or visual_bbox[3] <= visual_bbox[1]:+ return None+ return visual_bbox+++def _pdf_link_region_bboxes(+ raw_link: Any,+ page_bbox: BBox,+ page_rotation: int,+) -> tuple[BBox, ...]:+ """优先读取 Link QuadPoints,并在缺失时回退到注解矩形。"""++ bboxes: list[BBox] = []+ try:+ quad_count = max(0, int(pdfium_c.FPDFLink_CountQuadPoints(raw_link)))+ except Exception:+ quad_count = 0+ for quad_index in range(quad_count):+ quad = pdfium_c.FS_QUADPOINTSF()+ try:+ ok = pdfium_c.FPDFLink_GetQuadPoints(+ raw_link,+ quad_index,+ ctypes.byref(quad),+ )+ except Exception:+ continue+ if not ok:+ continue+ bbox = _visual_bbox_from_pdf_points(+ [+ (float(quad.x1), float(quad.y1)),+ (float(quad.x2), float(quad.y2)),+ (float(quad.x3), float(quad.y3)),+ (float(quad.x4), float(quad.y4)),+ ],+ page_bbox,+ page_rotation,+ )+ if bbox is not None and bbox not in bboxes:+ bboxes.append(bbox)++ if not bboxes:+ rect = pdfium_c.FS_RECTF()+ try:+ ok = pdfium_c.FPDFLink_GetAnnotRect(raw_link, ctypes.byref(rect))+ except Exception:+ ok = False+ if ok:+ bbox = _visual_bbox_from_pdf_points(+ [+ (float(rect.left), float(rect.bottom)),+ (float(rect.left), float(rect.top)),+ (float(rect.right), float(rect.bottom)),+ (float(rect.right), float(rect.top)),+ ],+ page_bbox,+ page_rotation,+ )+ if bbox is not None:+ bboxes.append(bbox)+ return tuple(+ sorted(+ bboxes,+ key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]),+ )+ )+++def _extract_page_link_annotations(+ page: pdfium.PdfPage,+ raw_doc: Any,+ page_bbox: BBox,+ page_rotation: int,+) -> list[PDFLinkAnnotation]:+ """枚举页面外部 URI Link;单条损坏数据不会中断同页其他链接。"""++ annotations: list[PDFLinkAnnotation] = []+ position = ctypes.c_int(0)+ source_index = 0+ while True:+ raw_link = pdfium_c.FPDF_LINK()+ previous_position = int(position.value)+ try:+ found = pdfium_c.FPDFLink_Enumerate(+ page.raw,+ ctypes.byref(position),+ ctypes.byref(raw_link),+ )+ except Exception:+ break+ if not found:+ break+ current_source_index = source_index+ source_index += 1+ if int(position.value) <= previous_position:+ break+ try:+ if not raw_link or not _pdf_link_annotation_is_visible(page, raw_link):+ continue+ raw_action = pdfium_c.FPDFLink_GetAction(raw_link)+ if not raw_action or int(pdfium_c.FPDFAction_GetType(raw_action)) != pdfium_c.PDFACTION_URI:+ continue+ raw_target = _get_pdfium_uri_path(raw_doc, raw_action)+ target = (+ _validate_pdf_external_link_target(raw_target)+ if raw_target is not None+ else None+ )+ if target is None:+ continue+ bboxes = _pdf_link_region_bboxes(+ raw_link,+ page_bbox,+ page_rotation,+ )+ if not bboxes:+ continue+ annotations.append(+ PDFLinkAnnotation(+ target=target,+ bboxes=bboxes,+ source_index=current_source_index,+ )+ )+ except Exception:+ continue+ return annotations++def _get_annotation_string(raw_annot: Any, key: bytes) -> str | None:"""读取 PDFium 注释字典中的 UTF-16 字符串或名称,异常和空值统一返回 None。"""diff --git a/mineru/utils/pdf_text_styles.py b/mineru/utils/pdf_text_styles.pyindex 914b29d8..7ea88bc5 100644--- a/mineru/utils/pdf_text_styles.py+++ b/mineru/utils/pdf_text_styles.py@@ -1,17 +1,20 @@# Copyright (c) Opendatalab. All rights reserved.-"""从 PDF 原生字符与绘图线中恢复文本字体和装饰线样式。"""+"""从 PDF 原生字符、绘图线和 Link 注解恢复行内样式与超链接。"""from __future__ import annotations+import htmlimport mathimport reimport statisticsfrom dataclasses import dataclass-from typing import Any, Iterable, Literal, Sequence, cast+from typing import Any, Iterable, Literal, Sequence, TypeVar, castfrom loguru import loggerfrom mineru.types import BBox, BlockType, RAW_CAPTION, RAW_FOOTNOTE+from mineru.utils.pdf_document import PDFLinkAnnotation+from mineru.utils.text_utils import is_hyphen_at_line_endTEXT_DECORATION_MIN_LENGTH_HEIGHT_RATIO = 2.0@@ -26,6 +29,7 @@ PDF_FONT_ITALIC_FLAG = 1 << 6PDF_FONT_FORCE_BOLD_FLAG = 1 << 18PDF_BOLD_MIN_WEIGHT = 600.0PDF_BOLD_MIN_COMPARABLE_CHAR_COUNT = 2+PDF_LINK_CHAR_OVERLAP_THRESHOLD = 0.5PDFTextStyle = Literal["bold", "italic", "underline", "strikethrough"]PDFTextDecoration = Literal["underline", "strikethrough"]@@ -114,6 +118,32 @@ class PDFTextStyleLine:source_index: int+@dataclass(frozen=True, slots=True)+class PDFTextLinkRange:+ """保存可比较文本中的一个半开超链接区间。"""++ start: int+ end: int+ target: str+++@dataclass(frozen=True, slots=True)+class PDFTextLinkLine:+ """保存视觉文本 run 的几何、可比较文本和超链接区间。"""++ bbox: BBox+ text: str+ link_ranges: tuple[PDFTextLinkRange, ...]+ source_index: int+++PDFTextEvidenceLine = TypeVar(+ "PDFTextEvidenceLine",+ PDFTextStyleLine,+ PDFTextLinkLine,+)++@dataclass(frozen=True, slots=True)class _VisibleChar:"""保存参与文本装饰线几何判断的可见字符。"""@@ -157,6 +187,7 @@ class _ProjectedChar:raw_end: intexisting_styles: frozenset[PDFTextStyle]formula_gap_before: bool+ inside_hyperlink: bool@dataclass(frozen=True, slots=True)@@ -177,6 +208,26 @@ class _RawStyleInterval:styles: tuple[PDFTextStyle, ...]+@dataclass(frozen=True, slots=True)+class _MatchedLinkRange:+ """保存已经对齐到 block 可比较文本的链接区间与物理行身份。"""++ start: int+ end: int+ target: str+ source_index: int+++@dataclass(frozen=True, slots=True)+class _RawLinkInterval:+ """保存 model content 原字符串中的半开链接区间。"""++ start: int+ end: int+ target: str+ source_index: int++@dataclass(frozen=True, slots=True)class _LineProjectionMatch:"""保存物理行跨公式空洞对齐到 block 可比较文本的结果。"""@@ -700,6 +751,160 @@ def detect_pdf_text_style_lines()+def _bbox_intersection_area(first: BBox, second: BBox) -> float:+ """返回两个合法 bbox 的相交面积。"""++ width = max(0.0, min(first[2], second[2]) - max(first[0], second[0]))+ height = max(0.0, min(first[3], second[3]) - max(first[1], second[1]))+ return width * height+++def _link_region_hits_char(region: BBox, char_bbox: BBox) -> bool:+ """按字符中心或字符面积覆盖率判断 Link 区域是否命中字符。"""++ center_x = (char_bbox[0] + char_bbox[2]) / 2+ center_y = (char_bbox[1] + char_bbox[3]) / 2+ if (+ region[0] <= center_x <= region[2]+ and region[1] <= center_y <= region[3]+ ):+ return True+ char_area = max(+ 0.01,+ (char_bbox[2] - char_bbox[0]) * (char_bbox[3] - char_bbox[1]),+ )+ return (+ _bbox_intersection_area(region, char_bbox) / char_area+ >= PDF_LINK_CHAR_OVERLAP_THRESHOLD+ )+++def _link_targets_for_char(+ char_bbox: BBox,+ annotations: Sequence[PDFLinkAnnotation],+) -> set[str]:+ """返回命中字符的全部不同链接目标,供冲突检测使用。"""++ return {+ annotation.target+ for annotation in annotations+ if any(+ _link_region_hits_char(region, char_bbox)+ for region in annotation.bboxes+ )+ }+++def _compact_link_ranges(+ compact_targets: Sequence[str | None],+) -> tuple[PDFTextLinkRange, ...]:+ """把逐字符链接目标压缩为同目标连续区间。"""++ ranges: list[PDFTextLinkRange] = []+ active_start = 0+ active_target: str | None = None+ for offset, target in enumerate([*compact_targets, None]):+ if target == active_target:+ continue+ if active_target is not None:+ ranges.append(+ PDFTextLinkRange(+ start=active_start,+ end=offset,+ target=active_target,+ )+ )+ active_start = offset+ active_target = target+ return tuple(ranges)+++def _build_link_line_payload(+ line: Any,+ annotations: Sequence[PDFLinkAnnotation],+ fallback_source_index: int,+) -> PDFTextLinkLine | None:+ """把一个视觉文本 run 与 Link 区域相交结果转换为紧凑链接证据。"""++ try:+ angle = int(getattr(line, "angle", 0) or 0) % 360+ except (TypeError, ValueError):+ return None+ if angle not in {0, 90, 180, 270}:+ return None+ line_bbox = _coerce_bbox(getattr(line, "bbox", None))+ if line_bbox is None:+ return None+ nearby_annotations = [+ annotation+ for annotation in annotations+ if any(+ _bbox_intersection_area(line_bbox, region) > 0+ for region in annotation.bboxes+ )+ ]+ if not nearby_annotations:+ return None++ compact_parts: list[str] = []+ compact_targets: list[str | None] = []+ for char in _ordered_line_chars(line):+ fragment = _normalize_match_fragment(char.get("char"))+ if not fragment:+ continue+ char_bbox = _coerce_bbox(char.get("bbox"))+ targets = (+ _link_targets_for_char(char_bbox, nearby_annotations)+ if char_bbox is not None+ else set()+ )+ # 同一字符落入不同目标时不猜测 PDF 点击层级,保留为普通文本。+ target = next(iter(targets)) if len(targets) == 1 else None+ compact_parts.append(fragment)+ compact_targets.extend([target] * len(fragment))++ text = "".join(compact_parts)+ link_ranges = _compact_link_ranges(compact_targets)+ if not text or not link_ranges:+ return None+ try:+ source_index = int(getattr(line, "source_index", fallback_source_index))+ except (TypeError, ValueError):+ source_index = fallback_source_index+ return PDFTextLinkLine(+ bbox=line_bbox,+ text=text,+ link_ranges=link_ranges,+ source_index=source_index,+ )+++def detect_pdf_text_link_lines(+ lines: Sequence[Any],+ annotations: Sequence[PDFLinkAnnotation],+) -> list[PDFTextLinkLine]:+ """从视觉文本 run 与 PDF Link 注解生成字符级超链接证据。"""++ if not annotations:+ return []+ payloads = [+ payload+ for line_index, line in enumerate(lines)+ if (+ payload := _build_link_line_payload(+ line,+ annotations,+ line_index,+ )+ )+ is not None+ ]+ return sorted(+ payloads,+ key=lambda line: (line.source_index, line.bbox[1], line.bbox[0]),+ )++def _block_bbox_to_page_bbox(value: Any, page_size: tuple[float, float]) -> BBox | None:"""把 model-list 的归一化 bbox 转回页面 point,同时兼容已是绝对坐标的内部输入。"""@@ -741,9 +946,9 @@ def _line_block_score(line_bbox: BBox, block_bbox: BBox) -> tuple[float, float,def _assign_lines_to_blocks(blocks: list[dict[str, Any]],- lines: Sequence[PDFTextStyleLine],+ lines: Sequence[PDFTextEvidenceLine],page_size: tuple[float, float],-) -> dict[int, list[PDFTextStyleLine]]:+) -> dict[int, list[PDFTextEvidenceLine]]:"""把每个视觉文本行唯一分配给最匹配的自然语言 block。"""target_bboxes = {@@ -753,7 +958,7 @@ def _assign_lines_to_blocks(and isinstance(block.get("content"), str)and (block_bbox := _block_bbox_to_page_bbox(block.get("bbox"), page_size)) is not None}- assignments: dict[int, list[PDFTextStyleLine]] = {}+ assignments: dict[int, list[PDFTextEvidenceLine]] = {}for line in lines:matches = [(block_index, _line_block_score(line.bbox, block_bbox))@@ -769,7 +974,13 @@ def _assign_lines_to_blocks(block_index, _score = max(matches, key=lambda item: (*item[1], -item[0]))assignments.setdefault(block_index, []).append(line)for block_lines in assignments.values():- block_lines.sort(key=_style_line_reading_order_key)+ block_lines.sort(+ key=lambda line: (+ line.source_index,+ line.bbox[1],+ line.bbox[0],+ )+ )return assignments@@ -907,6 +1118,10 @@ def _project_content_chars(content: str) -> list[_ProjectedChar]:formula_gap_before=(pending_formula_gap and fragment_index == 0),+ inside_hyperlink=any(+ state.tag == "hyperlink"+ for state in stack+ ),))if fragment:@@ -1203,6 +1418,487 @@ def _merge_style_ranges(ranges: Sequence[PDFTextStyleRange]) -> list[PDFTextStylreturn merged+def _resolve_link_fallback_occurrence(+ content: str,+ line: PDFTextLinkLine,+ link_range: PDFTextLinkRange,+ start: int,+) -> int | None:+ """整行无法对齐时,用唯一标签或两侧精确上下文定位链接片段。"""++ target_text = line.text[link_range.start : link_range.end]+ occurrences = _all_occurrences(content, target_text, start)+ if not occurrences:+ return None+ if len(occurrences) == 1:+ return occurrences[0]++ left_context = line.text[max(0, link_range.start - 12) : link_range.start]+ right_context = line.text[link_range.end : link_range.end + 12]+ required_context_score = int(bool(left_context)) + int(bool(right_context))+ if required_context_score == 0:+ return None+ scored = [+ (+ int(+ bool(left_context)+ and content[max(0, position - len(left_context)) : position]+ == left_context+ )+ + int(+ bool(right_context)+ and content[+ position + len(target_text) :+ position + len(target_text) + len(right_context)+ ]+ == right_context+ ),+ position,+ )+ for position in occurrences+ ]+ best_score = max(score for score, _position in scored)+ best_positions = [+ position+ for score, position in scored+ if score == best_score+ ]+ return (+ best_positions[0]+ if best_score == required_context_score and len(best_positions) == 1+ else None+ )+++def _project_link_range_from_line_match(+ link_range: PDFTextLinkRange,+ match: _LineProjectionMatch,+ source_index: int,+) -> list[_MatchedLinkRange]:+ """按行字符投影映射链接区间,并在缺失字符处安全分段。"""++ output: list[_MatchedLinkRange] = []+ current_start: int | None = None+ previous_index: int | None = None+ for projected_index in match.source_to_projected[+ link_range.start : link_range.end+ ]:+ if projected_index is None:+ if current_start is not None and previous_index is not None:+ output.append(+ _MatchedLinkRange(+ current_start,+ previous_index + 1,+ link_range.target,+ source_index,+ )+ )+ current_start = None+ previous_index = None+ continue+ if (+ current_start is not None+ and previous_index is not None+ and projected_index != previous_index + 1+ ):+ output.append(+ _MatchedLinkRange(+ current_start,+ previous_index + 1,+ link_range.target,+ source_index,+ )+ )+ current_start = None+ if current_start is None:+ current_start = projected_index+ previous_index = projected_index+ if current_start is not None and previous_index is not None:+ output.append(+ _MatchedLinkRange(+ current_start,+ previous_index + 1,+ link_range.target,+ source_index,+ )+ )+ return output+++def _link_lines_form_dehyphenated_continuation(+ line: PDFTextLinkLine,+ next_line: PDFTextLinkLine | None,+) -> bool:+ """判断相邻同 href 链接行是否符合文本回填的英文断词规则。"""++ if (+ next_line is None+ or next_line.source_index != line.source_index + 1+ or not line.text+ or not next_line.text+ or not is_hyphen_at_line_end(line.text)+ or not next_line.text[0].islower()+ ):+ return False+ tail_targets = {+ link_range.target+ for link_range in line.link_ranges+ if link_range.start < link_range.end == len(line.text)+ }+ head_targets = {+ link_range.target+ for link_range in next_line.link_ranges+ if link_range.start == 0 < link_range.end+ }+ return bool(tail_targets.intersection(head_targets))+++def _match_link_line_without_terminal_hyphen(+ projected_text: str,+ line: PDFTextLinkLine,+ next_line: PDFTextLinkLine | None,+ start: int,+) -> _LineProjectionMatch | None:+ """在严格跨行条件下将已被 block 回填删除的行末断词符投影为空洞。"""++ if not _link_lines_form_dehyphenated_continuation(line, next_line):+ return None+ candidate = line.text[:-1]+ next_first_char = next_line.text[0] if next_line is not None else ""+ occurrences = [+ position+ for position in _all_occurrences(projected_text, candidate, start)+ if (+ position + len(candidate) < len(projected_text)+ and projected_text[position + len(candidate)] == next_first_char+ )+ ]+ if len(occurrences) != 1:+ logger.debug(+ "Skip ambiguous PDF hyperlink dehyphenation mapping: "+ f"line={line.text!r}, occurrences={len(occurrences)}"+ )+ return None+ position = occurrences[0]+ return _LineProjectionMatch(+ start=position,+ end=position + len(candidate),+ source_to_projected=(+ *range(position, position + len(candidate)),+ None,+ ),+ )+++def _merge_matched_link_ranges(+ ranges: Sequence[_MatchedLinkRange],+) -> list[_MatchedLinkRange]:+ """删除不同目标重叠区,并合并同一物理行内的同目标相邻区间。"""++ valid_ranges = [+ link_range+ for link_range in ranges+ if link_range.start < link_range.end and link_range.target+ ]+ if not valid_ranges:+ return []+ boundaries = sorted(+ {+ position+ for link_range in valid_ranges+ for position in (link_range.start, link_range.end)+ }+ )+ merged: list[_MatchedLinkRange] = []+ for start, end in zip(boundaries, boundaries[1:]):+ active = [+ link_range+ for link_range in valid_ranges+ if link_range.start < end and link_range.end > start+ ]+ targets = {link_range.target for link_range in active}+ if len(targets) != 1:+ continue+ target = next(iter(targets))+ source_index = min(+ link_range.source_index+ for link_range in active+ if link_range.target == target+ )+ if (+ merged+ and merged[-1].end == start+ and merged[-1].target == target+ and merged[-1].source_index == source_index+ ):+ merged[-1] = _MatchedLinkRange(+ merged[-1].start,+ end,+ target,+ source_index,+ )+ else:+ merged.append(+ _MatchedLinkRange(+ start,+ end,+ target,+ source_index,+ )+ )+ return merged+++def _match_link_ranges(+ projected: Sequence[_ProjectedChar],+ lines: Sequence[PDFTextLinkLine],+) -> list[_MatchedLinkRange]:+ """按物理行顺序把 Link 几何证据确定性对齐到 block 文本。"""++ projected_text = "".join(token.value for token in projected)+ output: list[_MatchedLinkRange] = []+ cursor = 0+ for line_index, line in enumerate(lines):+ next_line = lines[line_index + 1] if line_index + 1 < len(lines) else None+ line_start = projected_text.find(line.text, cursor)+ if line_start >= 0:+ output.extend(+ _MatchedLinkRange(+ line_start + link_range.start,+ line_start + link_range.end,+ link_range.target,+ line.source_index,+ )+ for link_range in line.link_ranges+ )+ cursor = line_start + len(line.text)+ continue+ formula_match = _match_line_across_formula_gaps(+ line.text,+ projected,+ cursor,+ )+ if formula_match is not None:+ for link_range in line.link_ranges:+ output.extend(+ _project_link_range_from_line_match(+ link_range,+ formula_match,+ line.source_index,+ )+ )+ cursor = formula_match.end+ continue++ dehyphenated_match = _match_link_line_without_terminal_hyphen(+ projected_text,+ line,+ next_line,+ cursor,+ )+ if dehyphenated_match is not None:+ for link_range in line.link_ranges:+ output.extend(+ _project_link_range_from_line_match(+ link_range,+ dehyphenated_match,+ line.source_index,+ )+ )+ cursor = dehyphenated_match.end+ continue++ skipped_ranges: list[PDFTextLinkRange] = []+ for link_range in line.link_ranges:+ position = _resolve_link_fallback_occurrence(+ projected_text,+ line,+ link_range,+ cursor,+ )+ if position is None:+ skipped_ranges.append(link_range)+ continue+ output.append(+ _MatchedLinkRange(+ position,+ position + link_range.end - link_range.start,+ link_range.target,+ line.source_index,+ )+ )+ cursor = position + link_range.end - link_range.start+ if skipped_ranges:+ logger.debug(+ "Skip ambiguous PDF hyperlink mapping: "+ f"line={line.text!r}, skipped={len(skipped_ranges)}, "+ f"samples={[(line.text[item.start:item.end], item.target) for item in skipped_ranges[:3]]!r}"+ )+ return _merge_matched_link_ranges(output)+++def _append_raw_link_interval(+ intervals: list[_RawLinkInterval],+ start: int | None,+ end: int,+ target: str,+ source_index: int,+) -> None:+ """向结果追加一个合法原字符串链接区间。"""++ if start is not None and start < end and target:+ intervals.append(+ _RawLinkInterval(+ start,+ end,+ target,+ source_index,+ )+ )+++def _raw_link_intervals(+ content: str,+ projected: Sequence[_ProjectedChar],+ ranges: Sequence[_MatchedLinkRange],+) -> list[_RawLinkInterval]:+ """把链接区间转换为不跨公式或已有 hyperlink 的原字符串区间。"""++ intervals: list[_RawLinkInterval] = []+ for link_range in ranges:+ current_start: int | None = None+ current_end = 0+ for token in projected[link_range.start : link_range.end]:+ if token.inside_hyperlink or (+ token.formula_gap_before and current_start is not None+ ):+ _append_raw_link_interval(+ intervals,+ current_start,+ current_end,+ link_range.target,+ link_range.source_index,+ )+ current_start = None+ if token.inside_hyperlink:+ continue+ if current_start is None:+ current_start = token.raw_start+ current_end = token.raw_end+ continue+ gap = content[current_end : token.raw_start]+ if token.raw_start <= current_end or not gap or gap.isspace():+ current_end = max(current_end, token.raw_end)+ else:+ _append_raw_link_interval(+ intervals,+ current_start,+ current_end,+ link_range.target,+ link_range.source_index,+ )+ current_start = token.raw_start+ current_end = token.raw_end+ _append_raw_link_interval(+ intervals,+ current_start,+ current_end,+ link_range.target,+ link_range.source_index,+ )+ return intervals+++def _raw_link_gap_is_boundary_only(gap: str) -> bool:+ """判断两个跨行链接片段之间是否只包含空白或非正文边界符号。"""++ if not gap:+ return True+ if _KNOWN_INLINE_TAG_RE.search(gap) or r"\(" in gap or r"\)" in gap:+ return False+ return not any(char.isalnum() for char in html.unescape(gap))+++def _merge_raw_link_intervals(+ content: str,+ intervals: Sequence[_RawLinkInterval],+) -> list[_RawLinkInterval]:+ """合并相邻物理行中同 href 的首尾链接片段,不跨越正文或公式。"""++ merged: list[_RawLinkInterval] = []+ for interval in sorted(+ intervals,+ key=lambda item: (item.start, item.end, item.source_index, item.target),+ ):+ if interval.start >= interval.end or not interval.target:+ continue+ if (+ merged+ and merged[-1].target == interval.target+ and interval.source_index == merged[-1].source_index + 1+ and interval.start >= merged[-1].end+ and _raw_link_gap_is_boundary_only(+ content[merged[-1].end : interval.start]+ )+ ):+ merged[-1] = _RawLinkInterval(+ merged[-1].start,+ interval.end,+ interval.target,+ interval.source_index,+ )+ else:+ merged.append(interval)+ return merged+++def _wrap_link_intervals(+ content: str,+ intervals: Sequence[_RawLinkInterval],+) -> str:+ """从右向左包装链接区间,并对 URL 标签正文执行实体转义。"""++ output = content+ for interval in sorted(+ intervals,+ key=lambda item: (item.start, item.end, item.target),+ reverse=True,+ ):+ escaped_target = html.escape(interval.target, quote=False)+ output = (+ f"{output[: interval.start]}<hyperlink>"+ f"{output[interval.start : interval.end]}"+ f"<url>{escaped_target}</url></hyperlink>"+ f"{output[interval.end :]}"+ )+ return output+++def apply_pdf_text_links(+ blocks: list[dict[str, Any]],+ lines: Sequence[PDFTextLinkLine],+ page_size: tuple[float, float],+) -> None:+ """把页面 Link 几何证据写入自然语言 block,歧义时保持原文。"""++ assignments = _assign_lines_to_blocks(blocks, lines, page_size)+ for block_index, block_lines in assignments.items():+ content = blocks[block_index].get("content")+ if not isinstance(content, str) or not content:+ continue+ projected = _project_content_chars(content)+ link_ranges = _match_link_ranges(projected, block_lines)+ if not link_ranges:+ continue+ intervals = _raw_link_intervals(content, projected, link_ranges)+ if intervals:+ intervals = _merge_raw_link_intervals(content, intervals)+ blocks[block_index]["content"] = _wrap_link_intervals(+ content,+ intervals,+ )++def _append_raw_style_interval(intervals: list[_RawStyleInterval],start: int | None,@@ -1349,9 +2045,13 @@ def apply_pdf_text_styles(__all__ = ["PDF_FONT_FORCE_BOLD_FLAG","PDF_FONT_ITALIC_FLAG",+ "PDFTextLinkLine",+ "PDFTextLinkRange","PDFTextStyle","PDFTextStyleLine","PDFTextStyleRange",+ "apply_pdf_text_links","apply_pdf_text_styles",+ "detect_pdf_text_link_lines","detect_pdf_text_style_lines",]diff --git a/mineru/utils/text_utils.py b/mineru/utils/text_utils.pyindex 9ab8baa2..37cb9771 100644--- a/mineru/utils/text_utils.py+++ b/mineru/utils/text_utils.py@@ -2,6 +2,7 @@"""跨模型共享的文本字符规范化与换行连接规则。"""import re+from collections.abc import Sequence# 中日韩文本的物理换行通常不需要插入额外空格,集中定义以供各后端和渲染器共享。CJK_LANGS = frozenset({"zh", "ja", "ko"})@@ -72,6 +73,31 @@ def resolve_text_line_boundary(return processed_content, ""+def merge_text_line_contents(+ line_contents: Sequence[str],+ *,+ block_language: str,+) -> str:+ """按累计文本上下文折叠物理行,支持跨越三行以上的 URL 连续拼接。"""++ normalized_lines = [+ str(content)+ for content in line_contents+ if str(content)+ ]+ if not normalized_lines:+ return ""+ merged_content = normalized_lines[0]+ for current_line in normalized_lines[1:]:+ merged_content, separator = resolve_text_line_boundary(+ merged_content,+ block_language=block_language,+ next_content=current_line,+ )+ merged_content = f"{merged_content}{separator}{current_line}"+ return merged_content.strip()++def full_to_half_exclude_marks(text: str) -> str:"""将全角英文字母和数字转换为半角形式,同时保留全角标点。"""result = []diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.pyindex daafa77d..2f4d711b 100644--- a/tests/unittest/test_flash_pdf_samples.py+++ b/tests/unittest/test_flash_pdf_samples.py@@ -757,6 +757,14 @@ def test_demo3_pages1_and2_fix_title_front_matter_and_embedding_formula() -> Nonblock for block in page1 if _visible_content(block) == "Abstract")["type"] == "paragraph_title"assert released_code["type"] == "page_footnote"+ github_target = (+ "https://github.com/google-research/tapas/blob/master/TABLEFORMER.md"+ )+ assert released_code["content"].count("<hyperlink>") == 1+ assert released_code["content"] == (+ "1Code has been released at "+ f"<hyperlink>{github_target}<url>{github_target}</url></hyperlink>"+ )assert aside["angle"] == 270assert aside["bbox"][2] <= 0.12assert _visible_content(introduction).endswith(@@ -806,6 +814,7 @@ def test_demo3_pages6_7_and10_fix_caption_inline_titles_and_reference_tail() ->model_list = _native_model_list("demo3.pdf")page6 = model_list[5]page7 = model_list[6]+ page9 = model_list[8]page10 = model_list[9]table2_caption = next(@@ -867,6 +876,52 @@ def test_demo3_pages6_7_and10_fix_caption_inline_titles_and_reference_tail() ->)assert "**Attention Bias Scaling.** Unlike" in page7_markdown+ etc_reference = next(+ block+ for block in page9+ if "2020.emnlp-main.19" in str(block.get("content", ""))+ )+ assert etc_reference["content"].count("<hyperlink>") == 1+ assert (+ "<hyperlink>ETC: Encoding long and structured inputs in transformers"+ "<url>https://doi.org/10.18653/v1/2020.emnlp-main.19</url>"+ "</hyperlink>"+ ) in etc_reference["content"]++ dehyphenated_references = (+ (+ "https://doi.org/10.18653/v1/N19-1423",+ "BERT: Pre-training of deep bidirectional transformers for language understanding",+ ),+ (+ "https://doi.org/10.18653/v1/2020.findings-emnlp.27",+ "Understanding tables with intermediate pre-training",+ ),+ (+ "https://doi.org/10.18653/v1/P17-1167",+ "Search-based neural structured learning for sequential question answering",+ ),+ (+ "https://doi.org/10.18653/v1/D19-1603",+ "Answering conversational questions on structured data without logical forms",+ ),+ (+ "https://doi.org/10.3115/v1/P15-1142",+ "Compositional semantic parsing on semi-structured tables",+ ),+ )+ for target, label in dehyphenated_references:+ reference = next(+ block+ for block in page10+ if target in str(block.get("content", ""))+ )+ assert reference["content"].count("<hyperlink>") == 1+ assert (+ f"<hyperlink>{label}<url>{target}</url></hyperlink>"+ in reference["content"]+ )+ying_reference = next(blockfor block in page10@@ -1703,8 +1758,15 @@ def test_npu_numbered_figure_captions_are_independent_annotations() -> None:for block in model_list[21]if reference_urls[0] in str(block.get("content", "")))- assert " ".join(reference_urls) in reference_block- assert not any(first + second in reference_block for first, second in zip(reference_urls, reference_urls[1:]))+ reference_visible_text = inline_plain_text(+ parse_inline_content(reference_block)+ )+ assert " ".join(reference_urls) in reference_visible_text+ assert not any(+ first + second in reference_visible_text+ for first, second in zip(reference_urls, reference_urls[1:])+ )+ assert all(f"<url>{url}</url>" in reference_block for url in reference_urls)def test_frozen_soil_page3_formula3_remains_one_equation() -> None:diff --git a/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.pyindex 02f6bacb..d7f7f5e5 100644--- a/tests/unittest/test_pdf_analyze_block_content.py+++ b/tests/unittest/test_pdf_analyze_block_content.py@@ -427,7 +427,7 @@ def test_fill_window_batches_txt_post_ocr_before_page_content(monkeypatch: pytesmonkeypatch.setattr(text_content,"build_pdf_native_visual_lines_and_styles",- lambda *_args, **_kwargs: ([], [], []),+ lambda *_args, **_kwargs: ([], [], [], []),)monkeypatch.setattr(text_content,@@ -529,6 +529,24 @@ def test_text_content_joins_cross_line_url_candidate_without_space() -> None:assert content == "Available at https://doi.org/10.1016/example for details."+def test_text_content_joins_three_line_url_with_accumulated_context() -> None:+ """验证 Hybrid TXT 回填可跨三行保留 URL 协议上下文并连续拼接。"""++ content = text_content._lines_to_block_content(+ _build_text_lines(+ "Code at https://github.",+ "com/google-research/tapas/blob/master/",+ "TABLEFORMER.md",+ ),+ BlockType.TEXT,+ )++ assert content == (+ "Code at "+ "https://github.com/google-research/tapas/blob/master/TABLEFORMER.md"+ )++@pytest.mark.parametrize("block_type", [BlockType.CODE, RAW_ALGORITHM])def test_code_content_keeps_existing_line_breaks(block_type: str) -> None:"""验证 code/algorithm 原有的逐行拼接语义保持不变。"""@@ -707,7 +725,7 @@ def test_process_low_txt_fills_native_formulas_after_table_cleanup(monkeypatch.setattr(window,"_build_pdf_text_visual_run_data",- lambda _page: ([], []),+ lambda _page: ([], [], []),)def fake_fill_low_table_contents(*_args: object) -> None:diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.pyindex 5256bbde..387276b1 100644--- a/tests/unittest/test_pdf_analyze_visual_blocks.py+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py@@ -650,6 +650,32 @@ def test_normalize_pdf_model_list_preserves_inline_formulas_during_full_width_classert model_list[0][0]["content"] == "前A1 <eq>F2+x</eq> 中B3 <eq>C4+y</eq> 后D5"+def test_normalize_pdf_model_list_preserves_hyperlink_url_payload() -> None:+ """验证可见链接文本正常清洗,而 URL 全角字符和公式样式字面量保持原样。"""++ model_list = [+ [+ {+ "type": BlockType.TEXT,+ "content": (+ "前A <hyperlink>标B"+ "<url>https://example.test/A\\(x\\)?q=1&y=2</url>"+ "</hyperlink> 后C \\(D\\)"+ ),+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],+ }+ ]+ ]++ normalization._normalize_pdf_model_list(model_list)++ assert model_list[0][0]["content"] == (+ "前A <hyperlink>标B"+ "<url>https://example.test/A\\(x\\)?q=1&y=2</url>"+ "</hyperlink> 后C <eq>D</eq>"+ )++@pytest.mark.parametrize(("content", "expected"),[diff --git a/tests/unittest/test_pdf_document.py b/tests/unittest/test_pdf_document.pyindex 9a2c7160..4d6a220f 100644--- a/tests/unittest/test_pdf_document.py+++ b/tests/unittest/test_pdf_document.py@@ -232,6 +232,119 @@ def _build_rotated_cropped_signature_pdf() -> bytes:return output.getvalue()+def _build_rotated_cropped_link_pdf() -> bytes:+ """构造带 QuadPoints、Rect 回退和无效动作的旋转 Link 注解测试 PDF。"""++ writer = PdfWriter()+ page = writer.add_blank_page(width=100, height=200)+ page.rotate(90)+ page.cropbox.lower_left = (5, 10)+ page.cropbox.upper_right = (95, 190)+ annotations = ArrayObject()++ def add_uri_link(+ target: str,+ rect: tuple[float, float, float, float],+ *,+ quad_points: tuple[float, ...] | None = None,+ flags: int = 0,+ ) -> None:+ """追加一个可配置 URI Link,用于覆盖目标校验和区域读取分支。"""++ annotation = DictionaryObject(+ {+ NameObject("/Type"): NameObject("/Annot"),+ NameObject("/Subtype"): NameObject("/Link"),+ NameObject("/Rect"): ArrayObject(+ [FloatObject(value) for value in rect]+ ),+ NameObject("/A"): DictionaryObject(+ {+ NameObject("/S"): NameObject("/URI"),+ NameObject("/URI"): TextStringObject(target),+ }+ ),+ }+ )+ if quad_points is not None:+ annotation[NameObject("/QuadPoints")] = ArrayObject(+ [FloatObject(value) for value in quad_points]+ )+ if flags:+ annotation[NameObject("/F")] = NumberObject(flags)+ annotations.append(writer._add_object(annotation))++ add_uri_link(+ "https://example.com/a?x=1&y=2",+ (10, 20, 60, 40),+ quad_points=(20, 35, 40, 35, 20, 25, 40, 25),+ )+ add_uri_link("mailto:[email protected]", (10, 50, 40, 60))+ add_uri_link("tel:+123456", (10, 70, 40, 80))+ add_uri_link("javascript:alert(1)", (10, 90, 40, 100))+ add_uri_link("relative/path", (10, 110, 40, 120))+ add_uri_link(+ "https://hidden.example.com",+ (10, 130, 40, 140),+ flags=pdf_document.pdfium_c.FPDF_ANNOT_FLAG_HIDDEN,+ )+ add_uri_link(+ "https://invisible.example.com",+ (45, 130, 75, 140),+ flags=pdf_document.pdfium_c.FPDF_ANNOT_FLAG_INVISIBLE,+ )+ add_uri_link(+ "https://noview.example.com",+ (10, 145, 40, 155),+ flags=pdf_document.pdfium_c.FPDF_ANNOT_FLAG_NOVIEW,+ )+ annotations.append(+ writer._add_object(+ DictionaryObject(+ {+ NameObject("/Type"): NameObject("/Annot"),+ NameObject("/Subtype"): NameObject("/Link"),+ NameObject("/Rect"): ArrayObject(+ [FloatObject(10), FloatObject(20)]+ ),+ NameObject("/A"): DictionaryObject(+ {+ NameObject("/S"): NameObject("/URI"),+ NameObject("/URI"): TextStringObject(+ "https://broken.example.com"+ ),+ }+ ),+ }+ )+ )+ )+ annotations.append(+ writer._add_object(+ DictionaryObject(+ {+ NameObject("/Type"): NameObject("/Annot"),+ NameObject("/Subtype"): NameObject("/Link"),+ NameObject("/Rect"): ArrayObject(+ [+ FloatObject(10),+ FloatObject(165),+ FloatObject(40),+ FloatObject(175),+ ]+ ),+ NameObject("/Dest"): TextStringObject("missing-destination"),+ }+ )+ )+ )+ page[NameObject("/Annots")] = annotations++ output = BytesIO()+ writer.write(output)+ return output.getvalue()++class _TrackingLock:def __init__(self) -> None:self.depth = 0@@ -286,6 +399,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: pdef __init__(self, pdf_bytes: bytes) -> None:events.append(f"doc.open:{lock.depth}:{pdf_bytes!r}")self.page = _FakePage()+ self.raw = object()def __len__(self) -> int:events.append(f"doc.__len__:{lock.depth}")@@ -370,6 +484,18 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: pevents.append(f"signature_bboxes:{lock.depth}:{page_bbox}:{page_rotation}")return []+ def fake_extract_page_link_annotations(+ page: _FakePage,+ raw_doc: object,+ page_bbox: tuple[float, float, float, float],+ page_rotation: int,+ ) -> list[pdf_document.PDFLinkAnnotation]:+ """记录 Link 注解遍历时页面和文档句柄仍处于 PDFium 锁内。"""++ assert raw_doc is doc._pdf_doc.raw+ events.append(f"link_annotations:{lock.depth}:{page_bbox}:{page_rotation}")+ return []+monkeypatch.setattr(pdf_document.pdfium, "PdfDocument", _FakeDoc)monkeypatch.setattr(pdf_document, "get_chars", fake_get_chars, raising=False)monkeypatch.setattr(pdf_document, "pdftext_get_chars", fake_get_chars, raising=False)@@ -379,6 +505,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: pmonkeypatch.setattr(pdf_document, "_extract_page_image_infos", fake_extract_page_image_infos)monkeypatch.setattr(pdf_document, "_extract_page_form_bboxes", fake_extract_page_form_bboxes)monkeypatch.setattr(pdf_document, "_extract_page_signature_bboxes", fake_extract_page_signature_bboxes)+ monkeypatch.setattr(pdf_document, "_extract_page_link_annotations", fake_extract_page_link_annotations)doc = pdf_document.PDFDocument(b"%PDF")@@ -393,6 +520,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: passert doc.get_page_image_infos(0) == []assert doc.get_page_form_bboxes(0) == []assert doc.get_page_signature_bboxes(0) == []+ assert doc.get_page_link_annotations(0) == []assert any(event.startswith("doc.open:") and not event.startswith("doc.open:0:") for event in events)assert any(event.startswith("doc.__getitem__:") and not event.startswith("doc.__getitem__:0:") for event in events)@@ -410,6 +538,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: passert "image_infos:1:(0.0, 0.0, 20.0, 10.0):0" in eventsassert "form_bboxes:1:(0.0, 0.0, 20.0, 10.0):0" in eventsassert "signature_bboxes:1:(0.0, 0.0, 20.0, 10.0):0" in events+ assert "link_annotations:1:(0.0, 0.0, 20.0, 10.0):0" in eventsdef test_pdf_document_does_not_expose_legacy_compat_hooks() -> None:@@ -655,6 +784,71 @@ def test_get_page_signature_bboxes_filters_visibility_and_applies_page_geometry()+def test_pdf_document_extracts_safe_external_link_annotations() -> None:+ """验证外部 URI 白名单、QuadPoints 优先级和旋转 CropBox 坐标转换。"""++ with pdf_document.PDFDocument(_build_rotated_cropped_link_pdf()) as document:+ page_size = document.page_size(0)+ links = document[0].get_link_annotations()++ assert page_size == pytest.approx((180.0, 90.0))+ assert [link.target for link in links] == [+ "https://example.com/a?x=1&y=2",+ "mailto:[email protected]",+ "tel:+123456",+ ]+ assert links[0].bboxes[0] == pytest.approx((15.0, 15.0, 25.0, 35.0))+ assert links[1].bboxes[0] == pytest.approx((40.0, 5.0, 50.0, 35.0))+ assert links[2].bboxes[0] == pytest.approx((60.0, 5.0, 70.0, 35.0))+ assert [link.source_index for link in links] == [0, 1, 2]+++ ("target", "expected"),+ [+ ("HTTP://Example.com/path", "HTTP://Example.com/path"),+ ("mailto:[email protected]", "mailto:[email protected]"),+ ("tel:+123456", "tel:+123456"),+ ("https:///missing-host", None),+ ("mailto:", None),+ ("javascript:alert(1)", None),+ ("relative/path", None),+ ("https://example.com/a\x01b", None),+ ],+)+def test_pdf_external_link_target_validation(+ target: str,+ expected: str | None,+) -> None:+ """验证 PDF producer 只接受显式安全协议及完整目标。"""++ assert pdf_document._validate_pdf_external_link_target(target) == expected+++ ("rotation", "expected"),+ [+ (0, (15.0, 155.0, 35.0, 165.0)),+ (90, (15.0, 15.0, 25.0, 35.0)),+ (180, (55.0, 15.0, 75.0, 25.0)),+ (270, (155.0, 55.0, 165.0, 75.0)),+ ],+)+def test_pdf_link_region_geometry_supports_standard_page_rotations(+ rotation: int,+ expected: tuple[float, float, float, float],+) -> None:+ """验证 Link 点集在四个标准页面方向下转换到统一视觉坐标。"""++ bbox = pdf_document._visual_bbox_from_pdf_points(+ [(20.0, 25.0), (40.0, 25.0), (20.0, 35.0), (40.0, 35.0)],+ (5.0, 10.0, 95.0, 190.0),+ rotation,+ )++ assert bbox == pytest.approx(expected)++def test_extract_page_signature_bboxes_closes_handles_and_skips_bad_annotation(monkeypatch: pytest.MonkeyPatch,) -> None:diff --git a/tests/unittest/test_pdf_text_styles.py b/tests/unittest/test_pdf_text_styles.pyindex c0eda51a..c4a0f6d6 100644--- a/tests/unittest/test_pdf_text_styles.py+++ b/tests/unittest/test_pdf_text_styles.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport mathfrom io import BytesIO+from pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import MagicMockfrom zipfile import ZipFile@@ -14,15 +15,26 @@ from mineru.backend.analysis.pdf.text.models import _AnalyzeLine, _AnalyzeSpanfrom mineru.backend.analysis.pdf.text.native import txt_spans_extractfrom mineru.backend.postprocess.pages import model_list_to_pagesfrom mineru.model.flash import PdfModel-from mineru.render import render_docx, render_html, render_markdown-from mineru.types import RAW_CAPTION, RAW_FOOTNOTE, BlockType, ContentType, MiddleJson-from mineru.utils.pdf_document import PDFDocument+from mineru.render import render_content_list, render_docx, render_html, render_markdown+from mineru.types import (+ RAW_CAPTION,+ RAW_FOOTNOTE,+ BlockType,+ ContentType,+ MiddleJson,+ PageInfo,+)+from mineru.utils.pdf_document import PDFDocument, PDFLinkAnnotationfrom mineru.utils.pdf_text_styles import (PDF_FONT_FORCE_BOLD_FLAG,PDF_FONT_ITALIC_FLAG,+ PDFTextLinkLine,+ PDFTextLinkRange,PDFTextStyleLine,PDFTextStyleRange,+ apply_pdf_text_links,apply_pdf_text_styles,+ detect_pdf_text_link_lines,detect_pdf_text_style_lines,)@@ -143,6 +155,613 @@ def _char_span(line: SimpleNamespace, start: int, end: int) -> tuple[float, floareturn line.chars[start]["bbox"][0], line.chars[end - 1]["bbox"][2]+def _link_evidence_line(+ text: str,+ target: str,+ source_index: int,+ *,+ start: int = 0,+ end: int | None = None,+) -> PDFTextLinkLine:+ """构造跨行合并测试使用的轻量链接证据。"""++ resolved_end = len(text) if end is None else end+ top = 10.0 + (source_index % 10) * 10.0+ return PDFTextLinkLine(+ bbox=(10.0, top, 90.0, top + 8.0),+ text=text,+ link_ranges=(PDFTextLinkRange(start, resolved_end, target),),+ source_index=source_index,+ )++[email protected]("angle", [0, 90, 180, 270])+def test_detect_and_apply_pdf_text_link_ranges_with_styles(angle: int) -> None:+ """验证标准方向链接映射、内部空格、URL 转义、样式顺序和幂等性。"""++ line = _text_line("alpha beta", angle=angle)+ annotation = PDFLinkAnnotation(+ target="https://example.test/a?x=1&y=2",+ bboxes=((line.bbox[0], line.bbox[1], line.bbox[2], line.bbox[3]),),+ source_index=0,+ )+ link_lines = detect_pdf_text_link_lines([line], [annotation])++ assert link_lines == [+ PDFTextLinkLine(+ bbox=line.bbox,+ text="alphabeta",+ link_ranges=(+ PDFTextLinkRange(+ 0,+ 9,+ "https://example.test/a?x=1&y=2",+ ),+ ),+ source_index=0,+ )+ ]++ blocks = [+ {+ "type": BlockType.TEXT,+ "bbox": (0.0, 0.0, 1.0, 1.0),+ "content": "alpha beta",+ }+ ]+ apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))+ apply_pdf_text_styles(+ blocks,+ [+ PDFTextStyleLine(+ bbox=line.bbox,+ text="alphabeta",+ style_ranges=(PDFTextStyleRange(5, 9, ("underline",)),),+ source_index=0,+ )+ ],+ (100.0, 100.0),+ )+ expected = (+ '<hyperlink>alpha <text style="underline">beta</text>'+ "<url>https://example.test/a?x=1&y=2</url></hyperlink>"+ )+ assert blocks[0]["content"] == expected++ apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))+ assert blocks[0]["content"] == expected+++def test_detect_pdf_text_links_keeps_partial_ranges_and_drops_conflicts() -> None:+ """验证局部字符链接可保留,而不同目标重叠字符按歧义丢弃。"""++ line = _text_line("alpha")+ partial_bbox = (+ line.chars[2]["bbox"][0],+ line.bbox[1],+ line.chars[3]["bbox"][2],+ line.bbox[3],+ )+ partial = PDFLinkAnnotation(+ target="https://partial.example.test",+ bboxes=(partial_bbox,),+ source_index=0,+ )+ partial_lines = detect_pdf_text_link_lines([line], [partial])+ blocks = [+ {+ "type": BlockType.TEXT,+ "bbox": (0.0, 0.0, 1.0, 1.0),+ "content": "alpha",+ }+ ]+ apply_pdf_text_links(blocks, partial_lines, (100.0, 100.0))+ assert blocks[0]["content"] == (+ "al<hyperlink>ph<url>https://partial.example.test</url></hyperlink>a"+ )++ conflict = PDFLinkAnnotation(+ target="https://conflict.example.test",+ bboxes=(partial_bbox,),+ source_index=1,+ )+ assert detect_pdf_text_link_lines([line], [partial, conflict]) == []+++def test_apply_pdf_text_links_splits_formula_gaps_and_maps_repeated_labels() -> None:+ """验证链接不跨公式包装,并按物理行顺序定位重复标签。"""++ formula_blocks = [+ {+ "type": BlockType.TEXT,+ "bbox": (0.0, 0.0, 1.0, 1.0),+ "content": "pre<eq>x</eq>post",+ }+ ]+ apply_pdf_text_links(+ formula_blocks,+ [+ PDFTextLinkLine(+ bbox=(10.0, 10.0, 60.0, 20.0),+ text="prexpost",+ link_ranges=(+ PDFTextLinkRange(0, 8, "https://formula.example.test"),+ ),+ source_index=0,+ )+ ],+ (100.0, 100.0),+ )+ assert formula_blocks[0]["content"] == (+ "<hyperlink>pre<url>https://formula.example.test</url></hyperlink>"+ "<eq>x</eq>"+ "<hyperlink>post<url>https://formula.example.test</url></hyperlink>"+ )++ repeated_blocks = [+ {+ "type": BlockType.TEXT,+ "bbox": (0.0, 0.0, 1.0, 1.0),+ "content": "link and link",+ }+ ]+ apply_pdf_text_links(+ repeated_blocks,+ [+ PDFTextLinkLine(+ bbox=(10.0, 10.0, 35.0, 20.0),+ text="link",+ link_ranges=(PDFTextLinkRange(0, 4, "https://first.test"),),+ source_index=0,+ ),+ PDFTextLinkLine(+ bbox=(10.0, 30.0, 35.0, 40.0),+ text="link",+ link_ranges=(PDFTextLinkRange(0, 4, "https://second.test"),),+ source_index=1,+ ),+ ],+ (100.0, 100.0),+ )+ assert repeated_blocks[0]["content"] == (+ "<hyperlink>link<url>https://first.test</url></hyperlink> and "+ "<hyperlink>link<url>https://second.test</url></hyperlink>"+ )+++def test_apply_pdf_text_links_merges_three_line_visible_url() -> None:+ """验证三行同 href URL 合成一个标签,并吸收边界点号且不插入空格。"""++ target = "https://github.com/google-research/tapas/blob/master/TABLEFORMER.md"+ blocks = [+ {+ "type": BlockType.PAGE_FOOTNOTE,+ "bbox": (0.0, 0.0, 1.0, 1.0),+ "content": f"1Code has been released at {target}",+ }+ ]+ link_lines = [+ _link_evidence_line(+ "1Codehasbeenreleasedathttps://github.",+ target,+ 51,+ start=22,+ end=36,+ ),+ _link_evidence_line(+ "com/google-research/tapas/blob/master/",+ target,+ 52,+ ),+ _link_evidence_line("TABLEFORMER.md", target, 53),+ ]++ apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))++ expected = (+ "1Code has been released at "+ f"<hyperlink>{target}<url>{target}</url></hyperlink>"+ )+ assert blocks[0]["content"] == expected+ apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))+ assert blocks[0]["content"] == expected+++ (+ "content",+ "first_text",+ "first_start",+ "second_text",+ "second_end",+ "label",+ ),+ [+ (+ "Müller. 2020. Understanding tables with intermediate pre-training. In Findings",+ "Müller.2020.Understandingtableswithinterme-",+ len("Müller.2020."),+ "diatepre-training.InFindings",+ len("diatepre-training"),+ "Understanding tables with intermediate pre-training",+ ),+ (+ "Search-based neural structured learning for sequential question answering. In Proceedings",+ "Search-basedneuralstructuredlearningforsequen-",+ 0,+ "tialquestionanswering.InProceedings",+ len("tialquestionanswering"),+ "Search-based neural structured learning for sequential question answering",+ ),+ (+ "Yasemin Altun. 2019. Answering conversational questions",+ "YaseminAltun.2019.An-",+ len("YaseminAltun.2019."),+ "sweringconversationalquestions",+ len("sweringconversationalquestions"),+ "Answering conversational questions",+ ),+ (+ "Percy Liang. 2015. Compositional semantic parsing",+ "PercyLiang.2015.Compo-",+ len("PercyLiang.2015."),+ "sitionalsemanticparsing",+ len("sitionalsemanticparsing"),+ "Compositional semantic parsing",+ ),+ ],+)+def test_apply_pdf_text_links_maps_dehyphenated_first_fragment(+ content: str,+ first_text: str,+ first_start: int,+ second_text: str,+ second_end: int,+ label: str,+) -> None:+ """验证同 href 相邻行的首段断词符被回填删除后仍能完整映射。"""++ target = "https://doi.org/10.18653/v1/example"+ blocks = [+ {+ "type": BlockType.REF_TEXT,+ "bbox": (0.0, 0.0, 1.0, 1.0),+ "content": content,+ }+ ]+ apply_pdf_text_links(+ blocks,+ [+ _link_evidence_line(+ first_text,+ target,+ 80,+ start=first_start,+ ),+ _link_evidence_line(+ second_text,+ target,+ 81,+ end=second_end,+ ),+ ],+ (100.0, 100.0),+ )++ expected_link = f"<hyperlink>{label}<url>{target}</url></hyperlink>"+ assert blocks[0]["content"] == content.replace(label, expected_link)+++def test_apply_pdf_text_links_maps_dehyphenated_middle_fragment() -> None:+ """验证三行链接中间行的行末断词符不再阻断同 href 合并。"""++ target = "https://doi.org/10.18653/v1/N19-1423"+ label = (+ "BERT: Pre-training of deep bidirectional transformers for language "+ "understanding"+ )+ content = f"Kristina Toutanova. 2019. {label}. In Proceedings"+ first_text = "KristinaToutanova.2019.BERT:Pre-trainingof"+ blocks = [+ {+ "type": BlockType.REF_TEXT,+ "bbox": (0.0, 0.0, 1.0, 1.0),+ "content": content,+ }+ ]+ link_lines = [+ _link_evidence_line(+ first_text,+ target,+ 90,+ start=len("KristinaToutanova.2019."),+ ),+ _link_evidence_line(+ "deepbidirectionaltransformersforlanguageunder-",+ target,+ 91,+ ),+ _link_evidence_line(+ "standing.InProceedings",+ target,+ 92,+ end=len("standing"),+ ),+ ]++ apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))++ expected = content.replace(+ label,+ f"<hyperlink>{label}<url>{target}</url></hyperlink>",+ )+ assert blocks[0]["content"] == expected+ apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))+ assert blocks[0]["content"] == expected+++ ("content", "first_line", "second_line"),+ [+ (+ "international",+ _link_evidence_line("inter-", "https://same.test", 100),+ _link_evidence_line("national", "https://same.test", 102),+ ),+ (+ "international",+ _link_evidence_line("inter-", "https://same.test", 100),+ _link_evidence_line("national", "https://different.test", 101),+ ),+ (+ "interxnational",+ _link_evidence_line("inter-", "https://same.test", 100),+ _link_evidence_line(+ "xnational",+ "https://same.test",+ 101,+ start=1,+ ),+ ),+ (+ "interxnational",+ _link_evidence_line(+ "interx-",+ "https://same.test",+ 100,+ end=len("inter"),+ ),+ _link_evidence_line("national", "https://same.test", 101),+ ),+ ],+)+def test_apply_pdf_text_links_rejects_unsafe_dehyphenated_boundaries(+ content: str,+ first_line: PDFTextLinkLine,+ second_line: PDFTextLinkLine,+) -> None:+ """验证不同 href、非相邻行或非行首行尾链接不会启用断词投影。"""++ blocks = [+ {+ "type": BlockType.TEXT,+ "bbox": (0.0, 0.0, 1.0, 1.0),+ "content": content,+ }+ ]++ apply_pdf_text_links(+ blocks,+ [first_line, second_line],+ (100.0, 100.0),+ )++ assert f"<hyperlink>{content}<url>" not in blocks[0]["content"]+++def test_apply_pdf_text_links_preserves_hyphen_before_uppercase_continuation() -> None:+ """验证下一行以大写字母开头时保留可见连字符并正常合并链接。"""++ target = "https://same.test"+ blocks = [+ {+ "type": BlockType.TEXT,+ "bbox": (0.0, 0.0, 1.0, 1.0),+ "content": "inter-National",+ }+ ]++ apply_pdf_text_links(+ blocks,+ [+ _link_evidence_line("inter-", target, 110),+ _link_evidence_line("National", target, 111),+ ],+ (100.0, 100.0),+ )++ assert blocks[0]["content"] == (+ f"<hyperlink>inter-National<url>{target}</url></hyperlink>"+ )+++def test_apply_pdf_text_links_skips_ambiguous_dehyphenated_occurrence() -> None:+ """验证断词候选在 block 中重复时不会把前后片段错误桥接。"""++ blocks = [+ {+ "type": BlockType.TEXT,+ "bbox": (0.0, 0.0, 1.0, 1.0),+ "content": "international international",+ }+ ]++ apply_pdf_text_links(+ blocks,+ [+ _link_evidence_line("inter-", "https://same.test", 120),+ _link_evidence_line("national", "https://same.test", 121),+ ],+ (100.0, 100.0),+ )++ assert "<hyperlink>international<url>" not in blocks[0]["content"]+ assert blocks[0]["content"].startswith("inter<hyperlink>national")+ assert blocks[0]["content"].endswith(" international")+++ ("second_styles", "expected_label"),+ [+ (+ ("bold",),+ '<text style="bold">ETC: Encoding long and structured inputs in transformers</text>',+ ),+ (+ ("underline",),+ (+ '<text style="bold">ETC: Encoding long and structured inputs</text> '+ '<text style="underline">in transformers</text>'+ ),+ ),+ ],+)+def test_apply_pdf_text_links_merges_title_and_preserves_style_segments(+ second_styles: tuple[str, ...],+ expected_label: str,+) -> None:+ """验证普通英文标签保留空格,同样式合并而不同样式保留子段。"""++ target = "https://doi.org/10.18653/v1/2020.emnlp-main.19"+ first_text = "ETC:Encodinglongandstructuredinputs"+ second_text = "intransformers"+ blocks = [+ {+ "type": BlockType.TEXT,+ "bbox": (0.0, 0.0, 1.0, 1.0),+ "content": "ETC: Encoding long and structured inputs in transformers",+ }+ ]+ link_lines = [+ _link_evidence_line(first_text, target, 60),+ _link_evidence_line(second_text, target, 61),+ ]+ style_lines = [+ PDFTextStyleLine(+ link_lines[0].bbox,+ first_text,+ (PDFTextStyleRange(0, len(first_text), ("bold",)),),+ 60,+ ),+ PDFTextStyleLine(+ link_lines[1].bbox,+ second_text,+ (PDFTextStyleRange(0, len(second_text), second_styles),),+ 61,+ ),+ ]++ apply_pdf_text_links(blocks, link_lines, (100.0, 100.0))+ apply_pdf_text_styles(blocks, style_lines, (100.0, 100.0))++ assert blocks[0]["content"] == (+ f"<hyperlink>{expected_label}<url>{target}</url></hyperlink>"+ )+++ ("content", "first_source", "second_source", "second_target"),+ [+ ("first unlinked second", 70, 71, "https://same.test"),+ ("first<eq>x</eq>second", 70, 71, "https://same.test"),+ ("first second", 70, 72, "https://same.test"),+ ("first second", 70, 71, "https://different.test"),+ ],+)+def test_apply_pdf_text_links_does_not_cross_invalid_merge_boundaries(+ content: str,+ first_source: int,+ second_source: int,+ second_target: str,+) -> None:+ """验证无 href 正文、公式、非相邻行或不同目标都会阻断链接合并。"""++ first_target = "https://same.test"+ blocks = [+ {+ "type": BlockType.TEXT,+ "bbox": (0.0, 0.0, 1.0, 1.0),+ "content": content,+ }+ ]+ apply_pdf_text_links(+ blocks,+ [+ _link_evidence_line("first", first_target, first_source),+ _link_evidence_line("second", second_target, second_source),+ ],+ (100.0, 100.0),+ )++ assert blocks[0]["content"].count("<hyperlink>") == 2+++ ("block_type", "should_link"),+ [+ (BlockType.TEXT, True),+ (BlockType.REF_TEXT, True),+ (BlockType.DOC_TITLE, True),+ (BlockType.PARAGRAPH_TITLE, True),+ (BlockType.LIST, True),+ (BlockType.INDEX, True),+ (BlockType.HEADER, True),+ (BlockType.FOOTER, True),+ (BlockType.PAGE_NUMBER, True),+ (BlockType.ASIDE_TEXT, True),+ (BlockType.PAGE_FOOTNOTE, True),+ (RAW_CAPTION, True),+ (RAW_FOOTNOTE, True),+ (BlockType.TABLE, False),+ (BlockType.CODE, False),+ (BlockType.EQUATION, False),+ (BlockType.IMAGE, False),+ ],+)+def test_apply_pdf_text_links_only_enriches_natural_language_blocks(+ block_type: str,+ should_link: bool,+) -> None:+ """验证 PDF Link 只进入已批准的自然语言 block 类型。"""++ blocks = [+ {+ "type": block_type,+ "bbox": (0.0, 0.0, 1.0, 1.0),+ "content": "label",+ }+ ]+ apply_pdf_text_links(+ blocks,+ [+ PDFTextLinkLine(+ bbox=(10.0, 10.0, 40.0, 20.0),+ text="label",+ link_ranges=(PDFTextLinkRange(0, 5, "https://target.test"),),+ source_index=0,+ )+ ],+ (100.0, 100.0),+ )++ expected = (+ "<hyperlink>label<url>https://target.test</url></hyperlink>"+ if should_link+ else "label"+ )+ assert blocks[0]["content"] == expected++@pytest.mark.parametrize(("line_options", "expected_styles"),[@@ -1090,6 +1709,49 @@ def test_flash_native_pdf_styles_reach_model_middle_and_renderers() -> None:assert '<w:i w:val="1"' not in document_xml+def test_demo1_pdf_link_reaches_model_middle_and_all_renderers() -> None:+ """验证真实 demo1 URI Link 贯穿 model、MiddleJson 和四类 renderer。"""++ pdf_path = Path(__file__).parents[2] / "demo/pdfs/demo1.pdf"+ with PDFDocument(str(pdf_path)) as document:+ model_list = PdfModel().predict(document)++ target = "http://www.elsevier.com/locate/jhydrol"+ label = "www.elsevier.com/locate/jhydrol"+ inline_markup = f"<hyperlink>{label}<url>{target}</url></hyperlink>"+ assert any(+ block.get("content") == inline_markup+ for block in model_list[0]+ )++ middle = MiddleJson(+ pages=model_list_to_pages(model_list),+ file_suffix="pdf",+ effort="flash",+ parse_mode="txt",+ mineru_version="test",+ )+ link_block = next(+ block+ for block in middle.pages[0].blocks+ if getattr(block, "content", None) == inline_markup+ )+ link_middle = MiddleJson(+ pages=[PageInfo(page_idx=0, blocks=[link_block])],+ file_suffix="pdf",+ effort="flash",+ parse_mode="txt",+ mineru_version="test",+ )+ assert f"[{label}]({target})" in render_markdown(link_middle)+ assert f'href="{target}"' in render_html(link_middle, standalone=False)+ relationships = ZipFile(BytesIO(render_docx(link_middle))).read(+ "word/_rels/document.xml.rels"+ ).decode("utf-8")+ assert target in relationships+ assert f"[{label}]({target})" in str(render_content_list(link_middle))++def test_hybrid_txt_reuses_loaded_chars_and_applies_styles(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -1110,7 +1772,17 @@ def test_hybrid_txt_reuses_loaded_chars_and_applies_styles(0,)]- build_styles = MagicMock(return_value=(page_chars, [], style_lines))+ link_lines = [+ PDFTextLinkLine(+ (10.0, 10.0, 52.0, 20.0),+ "deleted",+ (PDFTextLinkRange(0, 7, "https://hybrid.example.test"),),+ 0,+ )+ ]+ build_styles = MagicMock(+ return_value=(page_chars, [], style_lines, link_lines)+ )observed_chars: list[object] = []def fake_fill_native(@@ -1181,7 +1853,104 @@ def test_hybrid_txt_reuses_loaded_chars_and_applies_styles(assert observed_chars == [page_chars]assert model_list[0][0]["content"] == (- '<text style="bold,underline,strikethrough">deleted</text>'+ '<hyperlink><text style="bold,underline,strikethrough">deleted</text>'+ "<url>https://hybrid.example.test</url></hyperlink>"+ )++[email protected]("effort", ["medium", "high", "xhigh"])+def test_hybrid_txt_efforts_apply_dehyphenated_links(+ monkeypatch: pytest.MonkeyPatch,+ effort: str,+) -> None:+ """验证 Medium、High 与 XHigh 共享的 TXT 回填路径应用断词链接投影。"""++ target = f"https://{effort}.example.test"+ link_lines = [+ PDFTextLinkLine(+ (10.0, 10.0, 52.0, 20.0),+ "inter-",+ (PDFTextLinkRange(0, 6, target),),+ 0,+ ),+ PDFTextLinkLine(+ (10.0, 30.0, 52.0, 40.0),+ "national",+ (PDFTextLinkRange(0, 8, target),),+ 1,+ ),+ ]+ monkeypatch.setattr(+ text_content,+ "build_pdf_native_visual_lines_and_styles",+ lambda *_args, **_kwargs: ([], [], [], link_lines),+ )+ monkeypatch.setattr(+ text_content,+ "_build_page_text_formula_spans",+ lambda *_args: [],+ )+ monkeypatch.setattr(+ text_content,+ "_fill_native_pdf_text_spans",+ lambda _page, spans, *_args, **_kwargs: spans,+ )+ monkeypatch.setattr(+ text_content,+ "_group_page_spans_by_block",+ lambda *_args: {+ 0: [+ _AnalyzeLine(+ bbox=(10.0, 10.0, 52.0, 20.0),+ spans=[+ _AnalyzeSpan(+ type=ContentType.TEXT,+ bbox=(10.0, 10.0, 52.0, 20.0),+ content="inter-",+ score=1.0,+ )+ ],+ ),+ _AnalyzeLine(+ bbox=(10.0, 30.0, 52.0, 40.0),+ spans=[+ _AnalyzeSpan(+ type=ContentType.TEXT,+ bbox=(10.0, 30.0, 52.0, 40.0),+ content="national",+ 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 = 1+ model_list = [+ [+ {+ "type": BlockType.TEXT,+ "bbox": [0.1, 0.1, 0.52, 0.4],+ "content": "",+ }+ ]+ ]++ text_content._fill_window_block_content_and_lines(+ [{"img_pil": object(), "scale": 1.0}],+ [pdf_page],+ model_list,+ [[]],+ [[]],+ "txt",+ {BlockType.TEXT},+ MagicMock(),+ )++ assert model_list[0][0]["content"] == (+ f"<hyperlink>international<url>{target}</url></hyperlink>")@@ -1208,10 +1977,16 @@ def test_low_txt_applies_styles_after_native_content_fill(),0,)+ link_line = PDFTextLinkLine(+ (10.0, 10.0, 52.0, 20.0),+ "deleted",+ (PDFTextLinkRange(0, 7, "https://low.example.test"),),+ 0,+ )monkeypatch.setattr(window,"_build_pdf_text_visual_run_data",- lambda _page: ([span], [style_line]),+ lambda _page: ([span], [style_line], [link_line]),)monkeypatch.setattr(window, "_fill_low_table_contents", lambda *_args: None)monkeypatch.setattr(@@ -1231,14 +2006,84 @@ def test_low_txt_applies_styles_after_native_content_fill()assert model_list[0][0]["content"] == (- '<text style="bold,underline,strikethrough">deleted</text>'+ '<hyperlink><text style="bold,underline,strikethrough">deleted</text>'+ "<url>https://low.example.test</url></hyperlink>"+ )+++def test_low_txt_applies_dehyphenated_links_after_native_content_fill(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证 Low/TXT 在删除物理行断词符后恢复完整链接。"""++ target = "https://low.example.test/dehyphenated"+ spans = [+ _AnalyzeSpan(+ type=ContentType.TEXT,+ bbox=(10.0, 10.0, 52.0, 20.0),+ content="inter-",+ score=1.0,+ ),+ _AnalyzeSpan(+ type=ContentType.TEXT,+ bbox=(10.0, 30.0, 52.0, 40.0),+ content="national",+ score=1.0,+ ),+ ]+ link_lines = [+ PDFTextLinkLine(+ spans[0].bbox,+ "inter-",+ (PDFTextLinkRange(0, 6, target),),+ 0,+ ),+ PDFTextLinkLine(+ spans[1].bbox,+ "national",+ (PDFTextLinkRange(0, 8, target),),+ 1,+ ),+ ]+ monkeypatch.setattr(+ window,+ "_build_pdf_text_visual_run_data",+ lambda _page: (spans, [], link_lines),+ )+ monkeypatch.setattr(window, "_fill_low_table_contents", lambda *_args: None)+ monkeypatch.setattr(+ window,+ "_fill_low_txt_native_formula_contents",+ lambda *_args: None,+ )+ model_list = [+ [+ {+ "type": BlockType.TEXT,+ "bbox": [0.1, 0.1, 0.52, 0.4],+ "content": "",+ }+ ]+ ]++ window._process_low_text(+ [{"img_pil": object(), "scale": 1.0}],+ [MagicMock(size=(100.0, 100.0))],+ model_list,+ "txt",+ MagicMock(),+ [[]],+ )++ assert model_list[0][0]["content"] == (+ f"<hyperlink>international<url>{target}</url></hyperlink>")def test_ocr_path_does_not_collect_or_apply_pdf_styles(monkeypatch: pytest.MonkeyPatch,) -> None:- """验证 OCR 路径不会读取 drawing 或应用 PDF 原生文本样式。"""+ """验证 OCR 路径不会读取或应用 PDF 原生文本样式与超链接。"""build_styles = MagicMock()monkeypatch.setattr(@@ -1294,6 +2139,74 @@ def test_ocr_path_does_not_collect_or_apply_pdf_styles(assert model_list[0][0]["content"] == "deleted"+def test_high_char_count_txt_path_skips_pdf_text_enrichment(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证超高字符页走 post-OCR 兜底时不读取样式或 Link 注解。"""++ build_enrichment = MagicMock()+ monkeypatch.setattr(+ text_content,+ "build_pdf_native_visual_lines_and_styles",+ build_enrichment,+ )+ plain_span = _AnalyzeSpan(+ type=ContentType.TEXT,+ bbox=(10.0, 10.0, 52.0, 20.0),+ content="plain",+ score=1.0,+ )+ monkeypatch.setattr(+ text_content,+ "_build_page_text_formula_spans",+ lambda *_args: [],+ )+ monkeypatch.setattr(+ text_content,+ "_fill_native_pdf_text_spans",+ lambda *_args, **_kwargs: [plain_span],+ )+ monkeypatch.setattr(+ text_content,+ "_group_page_spans_by_block",+ lambda *_args: {+ 0: [+ _AnalyzeLine(+ bbox=plain_span.bbox,+ spans=[plain_span],+ )+ ]+ },+ )+ pdf_page = MagicMock(size=(100.0, 100.0))+ pdf_page.get_char_count.return_value = (+ text_content.MAX_NATIVE_TEXT_CHARS_PER_PAGE + 1+ )+ model_list = [+ [+ {+ "type": BlockType.TEXT,+ "bbox": [0.1, 0.1, 0.52, 0.2],+ "content": "",+ }+ ]+ ]++ text_content._fill_window_block_content_and_lines(+ [{"img_pil": object(), "scale": 1.0}],+ [pdf_page],+ model_list,+ [[]],+ [[]],+ "txt",+ {BlockType.TEXT},+ MagicMock(),+ )++ build_enrichment.assert_not_called()+ assert model_list[0][0]["content"] == "plain"++def test_native_span_fill_does_not_read_preloaded_page_chars_twice() -> None:"""验证样式检测已加载 chars 后,原生 span 回填不会再次读取当前页字符。"""diff --git a/tests/unittest/test_postprocess_paragraphs.py b/tests/unittest/test_postprocess_paragraphs.pyindex fe2354a0..578469af 100644--- a/tests/unittest/test_postprocess_paragraphs.py+++ b/tests/unittest/test_postprocess_paragraphs.py@@ -660,11 +660,23 @@ def test_can_auto_merge_horizontal_text_blocks_rejects_paragraph_boundaries() ->previous_block["content"] = "finished."assert not can_auto_merge_text_blocks(current_block, previous_block)+ previous_block, current_block = _horizontal_pair()+ previous_block["content"] = (+ "<hyperlink>finished.<url>https://example.test/no-period</url></hyperlink>"+ )+ assert not can_auto_merge_text_blocks(current_block, previous_block)+for current_content in ("1 numbered", "Uppercase"):previous_block, current_block = _horizontal_pair()current_block["content"] = current_contentassert not can_auto_merge_text_blocks(current_block, previous_block)+ previous_block, current_block = _horizontal_pair()+ current_block["content"] = (+ "<hyperlink>Uppercase<url>https://example.test/lowercase</url></hyperlink>"+ )+ assert not can_auto_merge_text_blocks(current_block, previous_block)+previous_block, current_block = _horizontal_pair()current_block["lines"][0]["bbox"][0] = 0.2assert not can_auto_merge_text_blocks(current_block, previous_block)diff --git a/tests/unittest/test_text_utils.py b/tests/unittest/test_text_utils.pyindex f12f8d7b..f4b94795 100644--- a/tests/unittest/test_text_utils.py+++ b/tests/unittest/test_text_utils.py@@ -1,6 +1,9 @@import pytest-from mineru.utils.text_utils import resolve_text_line_boundary+from mineru.utils.text_utils import (+ merge_text_line_contents,+ resolve_text_line_boundary,+)@pytest.mark.parametrize(@@ -103,3 +106,33 @@ def test_resolve_text_line_boundary_keeps_conservative_joining_rules()assert f"{processed_previous}{separator}{next_content}" == expected+++def test_merge_text_line_contents_keeps_accumulated_url_context() -> None:+ """验证三行 URL 使用完整累计前缀,而普通标题和独立 URL 保留自然空格。"""++ assert merge_text_line_contents(+ [+ "Code at https://github.",+ "com/google-research/tapas/blob/master/",+ "TABLEFORMER.md",+ ],+ block_language="en",+ ) == (+ "Code at "+ "https://github.com/google-research/tapas/blob/master/TABLEFORMER.md"+ )+ assert merge_text_line_contents(+ [+ "ETC: Encoding long and structured inputs",+ "in transformers",+ ],+ block_language="en",+ ) == "ETC: Encoding long and structured inputs in transformers"+ assert merge_text_line_contents(+ [+ "https://example.test/first",+ "https://example.test/second",+ ],+ block_language="en",+ ) == "https://example.test/first https://example.test/second"