Skip to content

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

feat: implement PDF strikethrough style detection and application for visual text

myhlolia0e5cb013368
diff --git a/mineru/backend/analysis/pdf/tables.py b/mineru/backend/analysis/pdf/tables.py
index a41ea8e4..63527a7b 100644
--- a/mineru/backend/analysis/pdf/tables.py
+++ b/mineru/backend/analysis/pdf/tables.py
@@ -21,6 +21,7 @@ from mineru.utils.bbox_utils import (
)
from mineru.utils.ocr_utils import mask_formula_regions_for_ocr_det
from mineru.utils.pdf_document import PDFPage, get_lines_from_chars
+from mineru.utils.pdf_text_styles import PDFTextStyleLine
from mineru.utils.spatial_text import project_ocr_table_text, project_pdf_table_text
from .constants import (
@@ -47,6 +48,7 @@ from .geometry import (
)
from .text.models import _AnalyzeSpan
from .text.native import __replace_ligatures, __replace_unicode, _is_supported_rotation
+from .text.styles import build_pdf_native_visual_lines_and_styles
def _apply_table_rotate_labels(
@@ -60,18 +62,9 @@ def _apply_table_rotate_labels(
table_item["layout_item"]["angle"] = int(rotate_label or "0")
-def _build_pdf_text_visual_run_spans(pdf_page: PDFPage) -> list[_AnalyzeSpan]:
- """将 Low/TXT 原生粗行按 Flash 字符间隙拆成可独立分配的视觉 run。"""
+def _visual_line_items_to_spans(line_items: list[Any]) -> list[_AnalyzeSpan]:
+ """把 Flash 视觉 run 转为 Hybrid 文本分配使用的私有 span。"""
- # 延迟导入避免 Hybrid 模块初始化时提前加载完整 Flash PDF 流水线。
- from mineru.model.flash.native_pdf.native_text import _build_native_line_items
-
- line_items = _build_native_line_items(
- get_lines_from_chars(pdf_page.get_chars()),
- tuple(float(value) for value in pdf_page.size),
- page_rotation=pdf_page.rotation,
- supported_angles=_LOW_TXT_VISUAL_RUN_ANGLES,
- )
page_spans: list[_AnalyzeSpan] = []
for line_item in line_items:
content = __replace_ligatures(__replace_unicode(line_item.text)).strip()
@@ -88,6 +81,25 @@ def _build_pdf_text_visual_run_spans(pdf_page: PDFPage) -> list[_AnalyzeSpan]:
return page_spans
+def _build_pdf_text_visual_run_data(
+ pdf_page: PDFPage,
+) -> tuple[list[_AnalyzeSpan], list[PDFTextStyleLine]]:
+ """一次构造 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,
+ )
+ return _visual_line_items_to_spans(line_items), style_lines
+
+
+def _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)
+ return page_spans
+
+
def _detect_table_angle_from_pdf_lines(
pdf_lines: list[dict[str, Any]],
table_bbox: BBox,
diff --git a/mineru/backend/analysis/pdf/text/content.py b/mineru/backend/analysis/pdf/text/content.py
index 2973bc3d..9e12ae69 100644
--- a/mineru/backend/analysis/pdf/text/content.py
+++ b/mineru/backend/analysis/pdf/text/content.py
@@ -7,12 +7,17 @@ from typing import Any, Literal
import numpy as np
from PIL import Image
+from pdftext.schema import Char
from mineru.backend.local_model_runtime import HybridLocalModelContext, run_ocr_inference
from mineru.types import BBox, BlockType, ContentType
from mineru.utils.language import detect_lang
from mineru.utils.ocr_utils import OcrConfidence, rotate_vertical_crop_if_needed
from mineru.utils.pdf_document import PDFPage, get_lines_from_chars
+from mineru.utils.pdf_text_styles import (
+ PDFTextStyleLine,
+ apply_pdf_strikethrough_styles,
+)
from mineru.utils.text_utils import resolve_text_line_boundary
from ..constants import (
@@ -24,6 +29,7 @@ from ..geometry import _bbox_to_pixel_bbox, _sidecar_bbox_to_page_bbox
from .lines import group_spans_to_lines
from .models import _AnalyzeLine, _AnalyzeSpan
from .native import (
+ MAX_NATIVE_TEXT_CHARS_PER_PAGE,
SpanBlockMatcher,
__replace_ligatures,
__replace_unicode,
@@ -32,6 +38,7 @@ from .native import (
_restore_post_ocr_fallback,
txt_spans_extract,
)
+from .styles import build_pdf_native_visual_lines_and_styles
def _validate_text_formula_window_inputs(
@@ -139,8 +146,10 @@ def _fill_native_pdf_text_spans(
page_pil_image: Image.Image,
render_scale: float,
page_size: tuple[float, float],
+ *,
+ page_chars: list[Char] | None = None,
) -> list[_AnalyzeSpan]:
- """复用原生 PDF 字符回填逻辑,并为内容不足的 span 准备后置 OCR 裁图。"""
+ """复用原生 PDF 字符回填逻辑,并允许共享同页删除线检测读取的字符。"""
page_width, page_height = page_size
virtual_block = (0, 0, page_width, page_height, None, None, None, BlockType.TEXT)
return txt_spans_extract(
@@ -150,6 +159,7 @@ def _fill_native_pdf_text_spans(
render_scale,
[virtual_block],
[],
+ page_chars=page_chars,
)
@@ -316,7 +326,14 @@ def _fill_window_block_content_and_lines(
raise ValueError(f"Hybrid block content page count mismatch: {page_counts}")
target_block_types = set(ocr_det_type) | TITLE_BLOCK_TYPES | {BlockType.TEXT}
- page_block_line_results: list[tuple[list[dict[str, Any]], dict[int, list[_AnalyzeLine]], tuple[float, float]]] = []
+ page_block_line_results: list[
+ tuple[
+ list[dict[str, Any]],
+ dict[int, list[_AnalyzeLine]],
+ tuple[float, float],
+ list[PDFTextStyleLine],
+ ]
+ ] = []
for image_dict, pdf_page, page_model_list, page_inline_formula_list, page_ocr_res_list in zip(
images_list,
pdf_pages,
@@ -333,13 +350,28 @@ def _fill_window_block_content_and_lines(
page_size,
render_scale,
)
+ style_lines: list[PDFTextStyleLine] = []
if parse_mode == "txt":
+ page_chars = None
+ try:
+ page_char_count = pdf_page.get_char_count()
+ except Exception:
+ page_char_count = None
+ if (
+ not isinstance(page_char_count, int)
+ 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_spans = _fill_native_pdf_text_spans(
pdf_page,
page_spans,
page_pil_image,
render_scale,
page_size,
+ page_chars=page_chars,
)
block_lines = _group_page_spans_by_block(
@@ -348,20 +380,30 @@ def _fill_window_block_content_and_lines(
page_size,
target_block_types,
)
- page_block_line_results.append((page_model_list, block_lines, page_size))
+ page_block_line_results.append(
+ (page_model_list, block_lines, page_size, style_lines)
+ )
if parse_mode == "txt":
_apply_window_post_ocr(
local_model_context,
- [block_lines for _, block_lines, _ in page_block_line_results],
+ [
+ block_lines
+ for _, block_lines, _, _style_lines in page_block_line_results
+ ],
)
- for page_model_list, block_lines, page_size in page_block_line_results:
+ for page_model_list, block_lines, page_size, style_lines in page_block_line_results:
_apply_block_content_and_line_metadata(
page_model_list,
block_lines,
page_size,
)
+ apply_pdf_strikethrough_styles(
+ page_model_list,
+ style_lines,
+ page_size,
+ )
return model_list
diff --git a/mineru/backend/analysis/pdf/text/native.py b/mineru/backend/analysis/pdf/text/native.py
index 2efa8beb..7f398ddb 100644
--- a/mineru/backend/analysis/pdf/text/native.py
+++ b/mineru/backend/analysis/pdf/text/native.py
@@ -60,8 +60,10 @@ def txt_spans_extract(
scale: float,
all_bboxes: list[tuple[Any, ...]],
all_discarded_blocks: list[tuple[Any, ...]],
+ *,
+ page_chars: list[Char] | dict[str, list[Char]] | None = None,
) -> list[_AnalyzeSpan]:
- """从 PDF 原生字符中提取文本 Span,必要时准备后置 OCR 兜底。"""
+ """从 PDF 原生字符中提取文本 Span,并允许复用调用方已读取的页面字符。"""
page_char_count = None
try:
page_char_count = pdf_page.get_char_count()
@@ -73,7 +75,8 @@ def txt_spans_extract(
need_ocr_spans = [span for span in spans if span.type == ContentType.TEXT]
return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)
- page_chars = pdf_page.get_chars()
+ if page_chars is None:
+ page_chars = pdf_page.get_chars()
page_all_chars = _get_chars_for_span_fill(page_chars)
# 计算所有span的高度的中位数
diff --git a/mineru/backend/analysis/pdf/text/styles.py b/mineru/backend/analysis/pdf/text/styles.py
new file mode 100644
index 00000000..9537d44b
--- /dev/null
+++ b/mineru/backend/analysis/pdf/text/styles.py
@@ -0,0 +1,42 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""Hybrid TXT 路径复用的 PDF 原生文本样式准备入口。"""
+
+from __future__ import annotations
+
+from typing import Any, Sequence
+
+from pdftext.schema import Char
+
+from mineru.utils.pdf_document import PDFPage, get_lines_from_chars
+from mineru.utils.pdf_text_styles import (
+ PDFTextStyleLine,
+ detect_pdf_strikethrough_lines,
+)
+
+
+def build_pdf_native_visual_lines_and_styles(
+ pdf_page: PDFPage,
+ *,
+ page_chars: list[Char] | None = None,
+ supported_angles: Sequence[float] = (0.0,),
+) -> tuple[list[Char], list[Any], list[PDFTextStyleLine]]:
+ """一次读取当前页字符,构造视觉 run 及其水平删除线证据。"""
+
+ # 延迟导入避免 Hybrid 模块初始化时提前加载完整 Flash PDF 流水线。
+ from mineru.model.flash.native_pdf.native_text import _build_native_line_items
+
+ chars = page_chars if page_chars is not None else pdf_page.get_chars()
+ line_items = _build_native_line_items(
+ get_lines_from_chars(chars),
+ tuple(float(value) for value in pdf_page.size),
+ page_rotation=pdf_page.rotation,
+ supported_angles=supported_angles,
+ )
+ style_lines = detect_pdf_strikethrough_lines(
+ line_items,
+ pdf_page.get_drawing_lines(),
+ )
+ return chars, line_items, style_lines
+
+
+__all__ = ["build_pdf_native_visual_lines_and_styles"]
diff --git a/mineru/backend/analysis/pdf/window.py b/mineru/backend/analysis/pdf/window.py
index ae68b56f..74edaf27 100644
--- a/mineru/backend/analysis/pdf/window.py
+++ b/mineru/backend/analysis/pdf/window.py
@@ -14,6 +14,7 @@ from mineru.types import RAW_FORMULA_NUMBER, BlockType
from mineru.utils.config_reader import get_processing_window_size
from mineru.utils.pdf_document import PDFDocument, PDFPage
from mineru.utils.pdf_image_tools import load_images_from_pdf_bytes_range
+from mineru.utils.pdf_text_styles import apply_pdf_strikethrough_styles
from mineru.utils.spatial_text import project_pdf_spatial_text
from .constants import (
@@ -47,7 +48,7 @@ from .ocr import (
)
from .tables import (
_apply_medium_table_recognition,
- _build_pdf_text_visual_run_spans,
+ _build_pdf_text_visual_run_data,
_fill_low_table_contents,
_apply_table_orientations,
)
@@ -189,9 +190,10 @@ 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)
block_lines = _group_page_spans_by_block(
page_model_list,
- _build_pdf_text_visual_run_spans(pdf_page),
+ page_spans,
page_size,
target_block_types,
)
@@ -200,6 +202,11 @@ def _process_low_text(
block_lines,
page_size,
)
+ apply_pdf_strikethrough_styles(
+ page_model_list,
+ style_lines,
+ page_size,
+ )
elif parse_mode == "ocr":
images_pil_list = [image_dict["img_pil"] for image_dict in images_list]
np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]
diff --git a/mineru/model/flash/native_pdf/pipeline.py b/mineru/model/flash/native_pdf/pipeline.py
index 70531b7a..b1247791 100644
--- a/mineru/model/flash/native_pdf/pipeline.py
+++ b/mineru/model/flash/native_pdf/pipeline.py
@@ -10,6 +10,11 @@ from typing import Any
from mineru.model.flash.xycut import sort_entries
from mineru.utils.pdf_document import PDFDocument, PDFImageInfo, get_lines_from_chars
+from mineru.utils.pdf_text_styles import (
+ PDFTextStyleLine,
+ apply_pdf_strikethrough_styles,
+ detect_pdf_strikethrough_lines,
+)
from .models import (
_DocumentBodyProfile,
@@ -201,6 +206,7 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
)
page_sources: list[_PageSource] = []
+ page_style_lines: list[list[PDFTextStyleLine]] = []
for page_idx in range(pdf_doc.page_count):
page_size = page_sizes[page_idx]
chars = pdf_doc.get_page_chars(page_idx)
@@ -210,6 +216,9 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
page_rotation=pdf_doc.page_rotation(page_idx),
)
drawing_lines = _get_pdf_drawing_lines(pdf_doc, page_idx)
+ page_style_lines.append(
+ detect_pdf_strikethrough_lines(lines, drawing_lines)
+ )
source = _PageSource(
page_size=page_size,
lines=lines,
@@ -251,7 +260,7 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
prepared_pages,
document_body_profile,
)
- return [
+ finalized_pages = [
_finalize_prepared_page(
prepared,
page_index,
@@ -260,6 +269,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(
+ finalized_pages,
+ page_style_lines,
+ page_sizes,
+ strict=True,
+ ):
+ apply_pdf_strikethrough_styles(page_blocks, style_lines, page_size)
+ return finalized_pages
def _prepare_page_source(source: _PageSource) -> _PreparedPage:
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
index 73b1c612..6f7fea98 100644
--- a/mineru/utils/pdf_document.py
+++ b/mineru/utils/pdf_document.py
@@ -128,6 +128,11 @@ class PDFPage:
def get_chars(self) -> list[Char]:
return self.pdf_doc.get_page_chars(self._idx)
+ def get_drawing_lines(self) -> list[PDFDrawingLine]:
+ """读取当前页已规范到视觉页面坐标的横竖 drawing。"""
+
+ return self.pdf_doc.get_page_drawing_lines(self._idx)
+
class PDFDocument:
"""A PDF file loaded in memory, with lazy pypdfium2 access.
diff --git a/mineru/utils/pdf_text_styles.py b/mineru/utils/pdf_text_styles.py
new file mode 100644
index 00000000..7fbde40c
--- /dev/null
+++ b/mineru/utils/pdf_text_styles.py
@@ -0,0 +1,717 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""从 PDF 原生字符与绘图线中恢复文本删除线样式。"""
+
+from __future__ import annotations
+
+import math
+import re
+import statistics
+from dataclasses import dataclass
+from typing import Any, Sequence
+
+from loguru import logger
+
+from mineru.types import BBox, BlockType, RAW_CAPTION, RAW_FOOTNOTE
+
+
+STRIKETHROUGH_MIN_LENGTH_HEIGHT_RATIO = 2.0
+STRIKETHROUGH_CENTER_TOLERANCE_HEIGHT_RATIO = 0.2
+STRIKETHROUGH_MAX_WIDTH_HEIGHT_RATIO = 0.2
+STRIKETHROUGH_MIN_TEXT_COVERAGE_RATIO = 0.55
+STRIKETHROUGH_ENDPOINT_TOLERANCE_HEIGHT_RATIO = 0.5
+
+PDF_NATURAL_TEXT_STYLE_BLOCK_TYPES = frozenset(
+ {
+ BlockType.TEXT,
+ BlockType.REF_TEXT,
+ BlockType.DOC_TITLE,
+ BlockType.PARAGRAPH_TITLE,
+ BlockType.LIST,
+ BlockType.INDEX,
+ BlockType.HEADER,
+ BlockType.FOOTER,
+ BlockType.PAGE_NUMBER,
+ BlockType.ASIDE_TEXT,
+ BlockType.PAGE_FOOTNOTE,
+ RAW_CAPTION,
+ RAW_FOOTNOTE,
+ }
+)
+
+_KNOWN_INLINE_TAG_RE = re.compile(
+ r"<(?P<close>/)?(?P<tag>eq|text|hyperlink|url|sup|sub|strong|b|em|i|s|u)(?P<attrs>\s[^<>]*?)?>",
+ re.IGNORECASE,
+)
+_STYLE_ATTR_RE = re.compile(r"\bstyle\s*=\s*([\"'])(?P<style>.*?)\1", re.IGNORECASE | re.DOTALL)
+_PDF_CONTROL_CHAR_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]")
+_PDF_SEPARATOR_SPACE_CHARS = frozenset(
+ "\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006"
+ "\u2007\u2008\u2009\u200a\u202f\u205f\u3000"
+)
+_PDF_ZERO_WIDTH_CHARS = frozenset({"\u200b", "\u2060", "\ufeff"})
+_LIGATURE_REPLACEMENTS = {
+ "ff": "ff",
+ "fi": "fi",
+ "fl": "fl",
+ "ffi": "ffi",
+ "ffl": "ffl",
+ "ſt": "ft",
+ "st": "st",
+}
+
+
+@dataclass(frozen=True, slots=True)
+class PDFTextStyleRange:
+ """保存可比较文本中的一个半开删除线区间。"""
+
+ start: int
+ end: int
+
+
+@dataclass(frozen=True, slots=True)
+class PDFTextStyleLine:
+ """保存一个视觉文本 run 的几何、可比较文本和删除线区间。"""
+
+ bbox: BBox
+ text: str
+ strikethrough_ranges: tuple[PDFTextStyleRange, ...]
+ source_index: int
+
+
+@dataclass(frozen=True, slots=True)
+class _VisibleChar:
+ """保存参与删除线几何判断的可见字符。"""
+
+ source_index: int
+ bbox: BBox
+
+
+@dataclass(slots=True)
+class _LineCandidate:
+ """保存删除线匹配阶段使用的视觉文本行指标。"""
+
+ bbox: BBox
+ chars: list[dict[str, Any]]
+ visible_chars: list[_VisibleChar]
+ median_height: float
+ center_y: float
+ source_index: int
+ ranges: list[tuple[int, int]]
+
+
+@dataclass(frozen=True, slots=True)
+class _DrawingMatch:
+ """保存单条 drawing 对单个文本行的匹配结果和排序指标。"""
+
+ start_index: int
+ end_index: int
+ center_distance_ratio: float
+ horizontal_overlap_ratio: float
+
+
+@dataclass(frozen=True, slots=True)
+class _ProjectedChar:
+ """保存 model content 可比较字符到原字符串位置的映射。"""
+
+ value: str
+ raw_start: int
+ raw_end: int
+ styleable: bool
+
+
+def _coerce_bbox(value: Any) -> BBox | None:
+ """把 list、tuple 或 pdftext bbox 对象收敛为合法有限 bbox。"""
+
+ raw_bbox = getattr(value, "bbox", value)
+ try:
+ if raw_bbox is None or len(raw_bbox) != 4:
+ return None
+ bbox = tuple(float(item) for item in raw_bbox)
+ except (TypeError, ValueError):
+ return None
+ if not all(math.isfinite(item) for item in bbox):
+ return None
+ if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
+ return None
+ return bbox # type: ignore[return-value]
+
+
+def _ordered_line_chars(line: Any) -> list[dict[str, Any]]:
+ """按 char_idx 修复异常乱序字符,同时保留缺少索引时的来源顺序。"""
+
+ chars = [char for char in getattr(line, "chars", []) if isinstance(char, dict)]
+ indexed_chars = [char.get("char_idx") for char in chars]
+ if (
+ chars
+ and all(isinstance(index, int) for index in indexed_chars)
+ and any(first > second for first, second in zip(indexed_chars, indexed_chars[1:]))
+ ):
+ return sorted(chars, key=lambda char: int(char["char_idx"]))
+ return chars
+
+
+def _normalize_match_fragment(value: Any) -> str:
+ """把单个字符片段规范为忽略排版空白的确定性匹配文本。"""
+
+ output: list[str] = []
+ for char in str(value or ""):
+ if char in _PDF_ZERO_WIDTH_CHARS or char == "\u00ad":
+ continue
+ if char == "\x02":
+ output.append("-")
+ continue
+ if char.isspace() or char in _PDF_SEPARATOR_SPACE_CHARS:
+ continue
+ if _PDF_CONTROL_CHAR_RE.fullmatch(char):
+ continue
+ output.append(_LIGATURE_REPLACEMENTS.get(char, char))
+ return "".join(output)
+
+
+def _build_line_candidate(line: Any) -> _LineCandidate | None:
+ """从视觉水平 line 构造字符几何候选,旋转文字和退化行返回空。"""
+
+ if int(getattr(line, "angle", 0) or 0) % 360 != 0:
+ return None
+ line_bbox = _coerce_bbox(getattr(line, "bbox", None))
+ if line_bbox is None:
+ return None
+ chars = _ordered_line_chars(line)
+ visible_chars: list[_VisibleChar] = []
+ for char_index, char in enumerate(chars):
+ text = str(char.get("char") or "")
+ bbox = _coerce_bbox(char.get("bbox"))
+ if bbox is None or not text.isprintable() or text.isspace():
+ continue
+ visible_chars.append(_VisibleChar(source_index=char_index, bbox=bbox))
+ if not visible_chars:
+ return None
+
+ heights = [char.bbox[3] - char.bbox[1] for char in visible_chars]
+ median_height = statistics.median(heights)
+ if median_height <= 0:
+ return None
+ body_centers = [
+ (char.bbox[1] + char.bbox[3]) / 2
+ for char, height in zip(visible_chars, heights)
+ if height >= 0.8 * median_height
+ ]
+ if not body_centers:
+ return None
+ return _LineCandidate(
+ bbox=line_bbox,
+ chars=chars,
+ visible_chars=visible_chars,
+ median_height=median_height,
+ center_y=statistics.median(body_centers),
+ source_index=int(getattr(line, "source_index", 0) or 0),
+ ranges=[],
+ )
+
+
+def _drawing_match_for_line(line: _LineCandidate, drawing: Any) -> _DrawingMatch | None:
+ """按长度、中带、线宽、字符覆盖和端点贴合校验单条删除线候选。"""
+
+ if getattr(drawing, "orientation", None) != "horizontal":
+ return None
+ drawing_bbox = _coerce_bbox(getattr(drawing, "bbox", None))
+ if drawing_bbox is None:
+ return None
+ drawing_length = drawing_bbox[2] - drawing_bbox[0]
+ if drawing_length < STRIKETHROUGH_MIN_LENGTH_HEIGHT_RATIO * line.median_height:
+ return None
+ drawing_center_y = (drawing_bbox[1] + drawing_bbox[3]) / 2
+ center_distance_ratio = abs(drawing_center_y - line.center_y) / line.median_height
+ if center_distance_ratio > STRIKETHROUGH_CENTER_TOLERANCE_HEIGHT_RATIO:
+ return None
+ try:
+ drawing_width = max(0.0, float(getattr(drawing, "width", 0.0) or 0.0))
+ except (TypeError, ValueError):
+ return None
+ if drawing_width > STRIKETHROUGH_MAX_WIDTH_HEIGHT_RATIO * line.median_height:
+ return None
+
+ hit_chars = [
+ char
+ for char in line.visible_chars
+ if drawing_bbox[0] <= (char.bbox[0] + char.bbox[2]) / 2 <= drawing_bbox[2]
+ ]
+ if not hit_chars:
+ return None
+ hit_left = min(char.bbox[0] for char in hit_chars)
+ hit_right = max(char.bbox[2] for char in hit_chars)
+ if (hit_right - hit_left) / drawing_length < STRIKETHROUGH_MIN_TEXT_COVERAGE_RATIO:
+ return None
+ endpoint_distance = min(
+ abs(drawing_bbox[0] - hit_left),
+ abs(drawing_bbox[2] - hit_right),
+ )
+ if endpoint_distance > STRIKETHROUGH_ENDPOINT_TOLERANCE_HEIGHT_RATIO * line.median_height:
+ return None
+
+ overlap = max(
+ 0.0,
+ min(line.bbox[2], drawing_bbox[2]) - max(line.bbox[0], drawing_bbox[0]),
+ )
+ horizontal_overlap_ratio = overlap / max(
+ 0.01,
+ min(line.bbox[2] - line.bbox[0], drawing_length),
+ )
+ return _DrawingMatch(
+ start_index=min(char.source_index for char in hit_chars),
+ end_index=max(char.source_index for char in hit_chars) + 1,
+ center_distance_ratio=center_distance_ratio,
+ horizontal_overlap_ratio=horizontal_overlap_ratio,
+ )
+
+
+def _merge_source_ranges(ranges: list[tuple[int, int]]) -> list[tuple[int, int]]:
+ """合并重叠或相邻的来源字符区间。"""
+
+ merged: list[tuple[int, int]] = []
+ for start, end in sorted(ranges):
+ if start >= end:
+ continue
+ if merged and start <= merged[-1][1]:
+ merged[-1] = (merged[-1][0], max(merged[-1][1], end))
+ else:
+ merged.append((start, end))
+ return merged
+
+
+def _line_style_payload(line: _LineCandidate) -> PDFTextStyleLine | None:
+ """把来源字符和删除线索引转换为紧凑文本及其半开样式区间。"""
+
+ source_ranges = _merge_source_ranges(line.ranges)
+ compact_parts: list[str] = []
+ compact_ranges: list[PDFTextStyleRange] = []
+ compact_length = 0
+ active_start: int | None = None
+ active_end = 0
+ for char_index, char in enumerate(line.chars):
+ fragment = _normalize_match_fragment(char.get("char"))
+ if not fragment:
+ continue
+ fragment_start = compact_length
+ compact_parts.append(fragment)
+ fragment_end = fragment_start + len(fragment)
+ compact_length = fragment_end
+ is_struck = any(start <= char_index < end for start, end in source_ranges)
+ if is_struck:
+ if active_start is None:
+ active_start = fragment_start
+ active_end = fragment_end
+ elif active_start is not None:
+ compact_ranges.append(PDFTextStyleRange(active_start, active_end))
+ active_start = None
+ if active_start is not None:
+ compact_ranges.append(PDFTextStyleRange(active_start, active_end))
+
+ text = "".join(compact_parts)
+ if not text:
+ return None
+ return PDFTextStyleLine(
+ bbox=line.bbox,
+ text=text,
+ strikethrough_ranges=tuple(compact_ranges),
+ source_index=line.source_index,
+ )
+
+
+def _build_line_center_grid(
+ candidates: Sequence[_LineCandidate],
+) -> tuple[float, dict[int, list[int]]]:
+ """按删除线允许的纵向中带建立行索引,避免逐 drawing 扫描整页文本行。"""
+
+ grid_size = max(
+ 1.0,
+ statistics.median(line.median_height for line in candidates),
+ )
+ grid: dict[int, list[int]] = {}
+ for line_index, line in enumerate(candidates):
+ tolerance = STRIKETHROUGH_CENTER_TOLERANCE_HEIGHT_RATIO * line.median_height
+ start_cell = math.floor((line.center_y - tolerance) / grid_size)
+ end_cell = math.floor((line.center_y + tolerance) / grid_size)
+ for cell in range(start_cell, end_cell + 1):
+ grid.setdefault(cell, []).append(line_index)
+ return grid_size, grid
+
+
+def detect_pdf_strikethrough_lines(
+ lines: Sequence[Any],
+ drawing_lines: Sequence[Any],
+) -> list[PDFTextStyleLine]:
+ """从视觉文本 run 与页面 drawing 中生成全部水平行及其删除线证据。"""
+
+ horizontal_drawings = [
+ drawing
+ for drawing in drawing_lines
+ if getattr(drawing, "orientation", None) == "horizontal"
+ ]
+ if not horizontal_drawings:
+ return []
+ candidates = [candidate for line in lines if (candidate := _build_line_candidate(line)) is not None]
+ if not candidates:
+ return []
+ grid_size, line_grid = _build_line_center_grid(candidates)
+ for drawing in horizontal_drawings:
+ drawing_bbox = _coerce_bbox(getattr(drawing, "bbox", None))
+ if drawing_bbox is None:
+ continue
+ drawing_center_y = (drawing_bbox[1] + drawing_bbox[3]) / 2
+ candidate_indices = line_grid.get(math.floor(drawing_center_y / grid_size), [])
+ matches = [
+ (line_index, match)
+ for line_index in candidate_indices
+ if (match := _drawing_match_for_line(candidates[line_index], drawing)) is not None
+ ]
+ if not matches:
+ continue
+ line_index, best_match = min(
+ matches,
+ key=lambda item: (
+ item[1].center_distance_ratio,
+ -item[1].horizontal_overlap_ratio,
+ candidates[item[0]].source_index,
+ ),
+ )
+ candidates[line_index].ranges.append(
+ (best_match.start_index, best_match.end_index)
+ )
+
+ if not any(line.ranges for line in candidates):
+ return []
+ payloads = [payload for line in candidates if (payload := _line_style_payload(line)) is not None]
+ return sorted(payloads, key=lambda line: (line.bbox[1], line.bbox[0], line.source_index))
+
+
+def _block_bbox_to_page_bbox(value: Any, page_size: tuple[float, float]) -> BBox | None:
+ """把 model-list 的归一化 bbox 转回页面 point,同时兼容已是绝对坐标的内部输入。"""
+
+ bbox = _coerce_bbox(value)
+ if bbox is None:
+ return None
+ if all(0.0 <= coordinate <= 1.0 for coordinate in bbox):
+ return (
+ bbox[0] * page_size[0],
+ bbox[1] * page_size[1],
+ bbox[2] * page_size[0],
+ bbox[3] * page_size[1],
+ )
+ return bbox
+
+
+def _bbox_overlap_ratio(first: BBox, second: BBox) -> float:
+ """返回 first 面积中落入 second 的比例。"""
+
+ intersection_width = max(0.0, min(first[2], second[2]) - max(first[0], second[0]))
+ intersection_height = max(0.0, min(first[3], second[3]) - max(first[1], second[1]))
+ first_area = max(0.01, (first[2] - first[0]) * (first[3] - first[1]))
+ return intersection_width * intersection_height / first_area
+
+
+def _line_block_score(line_bbox: BBox, block_bbox: BBox) -> tuple[float, float, float]:
+ """计算文本行归属 block 的中心包含、重叠率与紧致度评分。"""
+
+ center_x = (line_bbox[0] + line_bbox[2]) / 2
+ center_y = (line_bbox[1] + line_bbox[3]) / 2
+ center_inside = float(
+ block_bbox[0] <= center_x <= block_bbox[2]
+ and block_bbox[1] <= center_y <= block_bbox[3]
+ )
+ overlap_ratio = _bbox_overlap_ratio(line_bbox, block_bbox)
+ block_area = (block_bbox[2] - block_bbox[0]) * (block_bbox[3] - block_bbox[1])
+ return center_inside, overlap_ratio, -block_area
+
+
+def _assign_lines_to_blocks(
+ blocks: list[dict[str, Any]],
+ lines: Sequence[PDFTextStyleLine],
+ page_size: tuple[float, float],
+) -> dict[int, list[PDFTextStyleLine]]:
+ """把每个视觉文本行唯一分配给最匹配的自然语言 block。"""
+
+ target_bboxes = {
+ block_index: block_bbox
+ for block_index, block in enumerate(blocks)
+ if block.get("type") in PDF_NATURAL_TEXT_STYLE_BLOCK_TYPES
+ and isinstance(block.get("content"), str)
+ and (block_bbox := _block_bbox_to_page_bbox(block.get("bbox"), page_size)) is not None
+ }
+ assignments: dict[int, list[PDFTextStyleLine]] = {}
+ for line in lines:
+ matches = [
+ (block_index, _line_block_score(line.bbox, block_bbox))
+ for block_index, block_bbox in target_bboxes.items()
+ if (
+ block_bbox[0] <= (line.bbox[0] + line.bbox[2]) / 2 <= block_bbox[2]
+ and block_bbox[1] <= (line.bbox[1] + line.bbox[3]) / 2 <= block_bbox[3]
+ )
+ or _bbox_overlap_ratio(line.bbox, block_bbox) >= 0.5
+ ]
+ if not matches:
+ continue
+ 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=lambda line: (line.bbox[1], line.bbox[0], line.source_index))
+ return assignments
+
+
+def _text_tag_has_strikethrough(attrs: str) -> bool:
+ """判断 text 标签是否已经显式携带删除线样式。"""
+
+ match = _STYLE_ATTR_RE.search(attrs)
+ if match is None:
+ return False
+ return "strikethrough" in {
+ style.strip().lower()
+ for style in match.group("style").split(",")
+ }
+
+
+def _pop_inline_tag(stack: list[tuple[str, bool, bool]], tag: str) -> None:
+ """从行内标签栈弹出最近的同名元素,容忍损坏嵌套。"""
+
+ for index in range(len(stack) - 1, -1, -1):
+ if stack[index][0] == tag:
+ del stack[index:]
+ return
+
+
+def _project_content_chars(content: str) -> list[_ProjectedChar]:
+ """把 model content 投影为忽略空白和公式的可比较字符,并保留原始 offset。"""
+
+ projected: list[_ProjectedChar] = []
+ stack: list[tuple[str, bool, bool]] = []
+ cursor = 0
+ while cursor < len(content):
+ if not any(item[1] for item in stack) and content.startswith(r"\(", cursor):
+ formula_end = content.find(r"\)", cursor + 2)
+ if formula_end >= 0:
+ cursor = formula_end + 2
+ continue
+ tag_match = _KNOWN_INLINE_TAG_RE.match(content, cursor)
+ if tag_match is not None:
+ tag = tag_match.group("tag").lower()
+ if tag_match.group("close"):
+ _pop_inline_tag(stack, tag)
+ else:
+ attrs = tag_match.group("attrs") or ""
+ stack.append(
+ (
+ tag,
+ tag in {"eq", "url"},
+ tag == "s" or (tag == "text" and _text_tag_has_strikethrough(attrs)),
+ )
+ )
+ cursor = tag_match.end()
+ continue
+
+ raw_char = content[cursor]
+ if not any(item[1] for item in stack):
+ fragment = _normalize_match_fragment(raw_char)
+ for value in fragment:
+ projected.append(
+ _ProjectedChar(
+ value=value,
+ raw_start=cursor,
+ raw_end=cursor + 1,
+ styleable=not any(item[2] for item in stack),
+ )
+ )
+ cursor += 1
+ return projected
+
+
+def _all_occurrences(content: str, target: str, start: int) -> list[int]:
+ """返回 target 在 content 指定位置后的全部精确匹配起点。"""
+
+ output: list[int] = []
+ cursor = start
+ while target and (match := content.find(target, cursor)) >= 0:
+ output.append(match)
+ cursor = match + 1
+ return output
+
+
+def _resolve_fallback_occurrence(
+ content: str,
+ line: PDFTextStyleLine,
+ style_range: PDFTextStyleRange,
+ start: int,
+) -> int | None:
+ """在整行无法对齐时,用唯一删除片段及两侧精确上下文选择位置。"""
+
+ target = line.text[style_range.start : style_range.end]
+ occurrences = _all_occurrences(content, target, start)
+ if len(occurrences) == 1:
+ return occurrences[0]
+ if not occurrences:
+ return None
+ left_context = line.text[max(0, style_range.start - 12) : style_range.start]
+ right_context = line.text[style_range.end : style_range.end + 12]
+ 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) : position + len(target) + 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 > 0 and len(best_positions) == 1 else None
+
+
+def _match_style_ranges(
+ projected_text: str,
+ lines: Sequence[PDFTextStyleLine],
+) -> list[PDFTextStyleRange]:
+ """按物理行顺序把删除线证据确定性对齐到 block 的可比较文本。"""
+
+ output: list[PDFTextStyleRange] = []
+ cursor = 0
+ for line in lines:
+ line_start = projected_text.find(line.text, cursor)
+ if line_start >= 0:
+ output.extend(
+ PDFTextStyleRange(
+ line_start + style_range.start,
+ line_start + style_range.end,
+ )
+ for style_range in line.strikethrough_ranges
+ )
+ cursor = line_start + len(line.text)
+ continue
+ for style_range in line.strikethrough_ranges:
+ position = _resolve_fallback_occurrence(
+ projected_text,
+ line,
+ style_range,
+ cursor,
+ )
+ if position is None:
+ logger.debug(
+ "Skip ambiguous PDF strikethrough mapping: "
+ f"line={line.text!r}, target={line.text[style_range.start:style_range.end]!r}"
+ )
+ continue
+ output.append(
+ PDFTextStyleRange(
+ position,
+ position + style_range.end - style_range.start,
+ )
+ )
+ cursor = position + style_range.end - style_range.start
+ return _merge_style_ranges(output)
+
+
+def _merge_style_ranges(ranges: Sequence[PDFTextStyleRange]) -> list[PDFTextStyleRange]:
+ """合并可比较文本中重叠或直接相邻的样式区间。"""
+
+ merged: list[PDFTextStyleRange] = []
+ for style_range in sorted(ranges, key=lambda item: (item.start, item.end)):
+ if style_range.start >= style_range.end:
+ continue
+ if merged and style_range.start <= merged[-1].end:
+ merged[-1] = PDFTextStyleRange(
+ merged[-1].start,
+ max(merged[-1].end, style_range.end),
+ )
+ else:
+ merged.append(style_range)
+ return merged
+
+
+def _raw_style_intervals(
+ content: str,
+ projected: Sequence[_ProjectedChar],
+ ranges: Sequence[PDFTextStyleRange],
+) -> list[tuple[int, int]]:
+ """把可比较文本区间转换为不跨公式或现有标签的原字符串区间。"""
+
+ intervals: list[tuple[int, int]] = []
+ for style_range in ranges:
+ current_start: int | None = None
+ current_end = 0
+ for token in projected[style_range.start : style_range.end]:
+ if not token.styleable:
+ if current_start is not None:
+ intervals.append((current_start, current_end))
+ current_start = None
+ 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:
+ intervals.append((current_start, current_end))
+ current_start = token.raw_start
+ current_end = token.raw_end
+ if current_start is not None:
+ intervals.append((current_start, current_end))
+
+ merged: list[tuple[int, int]] = []
+ for start, end in sorted(intervals):
+ if start >= end:
+ continue
+ if merged and (start <= merged[-1][1] or content[merged[-1][1] : start].isspace()):
+ merged[-1] = (merged[-1][0], max(merged[-1][1], end))
+ else:
+ merged.append((start, end))
+ return merged
+
+
+def _wrap_strikethrough_intervals(content: str, intervals: Sequence[tuple[int, int]]) -> str:
+ """从右向左包装删除线区间,确保原 offset 在插入标签时保持有效。"""
+
+ output = content
+ for start, end in reversed(intervals):
+ output = (
+ f'{output[:start]}<text style="strikethrough">'
+ f"{output[start:end]}</text>{output[end:]}"
+ )
+ return output
+
+
+def apply_pdf_strikethrough_styles(
+ blocks: list[dict[str, Any]],
+ lines: Sequence[PDFTextStyleLine],
+ page_size: tuple[float, float],
+) -> None:
+ """把页面删除线证据写入自然语言 block content,无法唯一对齐时保持原文。"""
+
+ assignments = _assign_lines_to_blocks(blocks, lines, page_size)
+ for block_index, block_lines in assignments.items():
+ block = blocks[block_index]
+ content = block.get("content")
+ if not isinstance(content, str) or not content or not any(
+ line.strikethrough_ranges for line in block_lines
+ ):
+ continue
+ projected = _project_content_chars(content)
+ projected_text = "".join(token.value for token in projected)
+ style_ranges = _match_style_ranges(projected_text, block_lines)
+ if not style_ranges:
+ continue
+ intervals = _raw_style_intervals(content, projected, style_ranges)
+ if intervals:
+ block["content"] = _wrap_strikethrough_intervals(content, intervals)
+
+
+__all__ = [
+ "PDFTextStyleLine",
+ "PDFTextStyleRange",
+ "apply_pdf_strikethrough_styles",
+ "detect_pdf_strikethrough_lines",
+]
diff --git a/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.py
index c96c3d1a..15910a45 100644
--- a/tests/unittest/test_pdf_analyze_block_content.py
+++ b/tests/unittest/test_pdf_analyze_block_content.py
@@ -12,6 +12,7 @@ from mineru_vl_utils.structs import ExtractResult
from mineru.backend import analyze
from mineru.backend.analysis.pdf import constants, formulas, layout, normalization, ocr, pipeline, tables, window
from mineru.backend.analysis.pdf.text import content as text_content
+from mineru.backend.analysis.pdf.text import styles as text_styles
from mineru.backend.analysis.pdf.text.models import _AnalyzeLine, _AnalyzeSpan
from mineru.types import RAW_ALGORITHM, RAW_CAPTION, RAW_FOOTNOTE, RAW_FORMULA_NUMBER
from mineru.backend.analysis.pdf.text.native import (
@@ -419,7 +420,16 @@ def test_fill_window_batches_txt_post_ocr_before_page_content(monkeypatch: pytes
page_block_lines_list, _ = _build_post_ocr_page_block_lines(11, 22)
grouped_page_lines = iter(page_block_lines_list)
monkeypatch.setattr(text_content, "_build_page_text_formula_spans", lambda *_args: [])
- monkeypatch.setattr(text_content, "_fill_native_pdf_text_spans", lambda _page, spans, *_args: spans)
+ monkeypatch.setattr(
+ text_content,
+ "build_pdf_native_visual_lines_and_styles",
+ lambda *_args, **_kwargs: ([], [], []),
+ )
+ 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: next(grouped_page_lines))
local_model_context = MagicMock()
local_model_context.ocr_model.ocr.return_value = [[("窗口第一页", 0.9), ("窗口第二页", 0.8)]]
@@ -580,7 +590,8 @@ def test_low_txt_visual_runs_split_distant_text_before_layout_matching(
pdf_page.size = (100.0, 100.0)
pdf_page.rotation = 0
pdf_page.get_chars.return_value = []
- monkeypatch.setattr(tables, "get_lines_from_chars", lambda _chars: pdf_lines)
+ pdf_page.get_drawing_lines.return_value = []
+ monkeypatch.setattr(text_styles, "get_lines_from_chars", lambda _chars: pdf_lines)
spans = tables._build_pdf_text_visual_run_spans(pdf_page)
@@ -689,7 +700,11 @@ def test_process_low_txt_fills_native_formulas_after_table_cleanup(
pdf_page = MagicMock(size=(100.0, 100.0))
model_list = [[{"type": BlockType.EQUATION, "bbox": [0.1, 0.1, 0.5, 0.2]}]]
- monkeypatch.setattr(window, "_build_pdf_text_visual_run_spans", lambda _page: [])
+ monkeypatch.setattr(
+ window,
+ "_build_pdf_text_visual_run_data",
+ lambda _page: ([], []),
+ )
def fake_fill_low_table_contents(*_args: object) -> None:
"""模拟表格阶段认领并清理当前公式。"""
diff --git a/tests/unittest/test_pdf_text_styles.py b/tests/unittest/test_pdf_text_styles.py
new file mode 100644
index 00000000..e5daa8a3
--- /dev/null
+++ b/tests/unittest/test_pdf_text_styles.py
@@ -0,0 +1,619 @@
+from __future__ import annotations
+
+from io import BytesIO
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+from zipfile import ZipFile
+
+import pytest
+
+from mineru.backend.analysis.pdf import window
+from mineru.backend.analysis.pdf.text import content as text_content
+from mineru.backend.analysis.pdf.text.models import _AnalyzeLine, _AnalyzeSpan
+from mineru.backend.analysis.pdf.text.native import txt_spans_extract
+from mineru.backend.postprocess.pages import model_list_to_pages
+from mineru.model.flash import PdfModel
+from mineru.render import render_docx, render_html, render_markdown
+from mineru.types import BlockType, ContentType, MiddleJson
+from mineru.utils.pdf_document import PDFDocument
+from mineru.utils.pdf_text_styles import (
+ PDFTextStyleLine,
+ PDFTextStyleRange,
+ apply_pdf_strikethrough_styles,
+ detect_pdf_strikethrough_lines,
+)
+
+
+def _build_native_text_style_pdf() -> bytes:
+ """构造包含删除线、下划线、整栏横线和短横线的单页原生 PDF。"""
+
+ content = b"""0.8 w
+BT /F1 12 Tf 50 250 Td (strike: alpha ) Tj (deleted) Tj ( omega) Tj ET
+150.8 254 m 201.2 254 l S
+BT /F1 12 Tf 50 210 Td (underline: alpha ) Tj (underlined) Tj ( omega) Tj ET
+172.4 208 m 244.4 208 l S
+BT /F1 12 Tf 50 170 Td (separator: alpha crossed omega) Tj ET
+20 174 m 400 174 l S
+BT /F1 12 Tf 50 130 Td (short: alpha ) Tj (x) Tj ( omega) Tj ET
+143.6 134 m 150.8 134 l S
+BT /F1 12 Tf 50 90 Td (filled: alpha ) Tj (filled strike) Tj ( omega) Tj ET
+150.8 93.4 93.6 1.2 re f
+"""
+ objects = [
+ b"<< /Type /Catalog /Pages 2 0 R >>",
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 420 300] "
+ b"/Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>",
+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Courier >>",
+ b"<< /Length " + str(len(content)).encode("ascii") + b" >>\nstream\n" + content + b"endstream",
+ ]
+ payload = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")
+ offsets = [0]
+ for object_index, body in enumerate(objects, start=1):
+ offsets.append(len(payload))
+ payload.extend(f"{object_index} 0 obj\n".encode("ascii"))
+ payload.extend(body)
+ payload.extend(b"\nendobj\n")
+ xref_offset = len(payload)
+ payload.extend(f"xref\n0 {len(objects) + 1}\n".encode("ascii"))
+ payload.extend(b"0000000000 65535 f \n")
+ for offset in offsets[1:]:
+ payload.extend(f"{offset:010d} 00000 n \n".encode("ascii"))
+ payload.extend(
+ (
+ f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\n"
+ f"startxref\n{xref_offset}\n%%EOF\n"
+ ).encode("ascii")
+ )
+ return bytes(payload)
+
+
+def _text_line(
+ text: str,
+ *,
+ x: float = 10.0,
+ y: float = 10.0,
+ height: float = 10.0,
+ angle: int = 0,
+ source_index: int = 0,
+) -> SimpleNamespace:
+ """构造带真实字符 bbox 的轻量视觉文本行。"""
+
+ chars = []
+ cursor = x
+ for char_index, char in enumerate(text):
+ width = 3.0 if char.isspace() else 6.0
+ chars.append(
+ {
+ "char": char,
+ "bbox": (cursor, y, cursor + width, y + height),
+ "char_idx": char_index,
+ }
+ )
+ cursor += width
+ return SimpleNamespace(
+ text=text,
+ bbox=(x, y, cursor, y + height),
+ angle=angle,
+ source_index=source_index,
+ chars=chars,
+ )
+
+
+def _drawing(
+ x0: float,
+ x1: float,
+ y: float,
+ *,
+ width: float = 1.0,
+ orientation: str = "horizontal",
+) -> SimpleNamespace:
+ """构造删除线检测使用的轻量 drawing。"""
+
+ return SimpleNamespace(
+ bbox=(x0, y - width / 2, x1, y + width / 2),
+ width=width,
+ orientation=orientation,
+ )
+
+
+def _char_span(line: SimpleNamespace, start: int, end: int) -> tuple[float, float]:
+ """返回指定字符区间的左右边缘。"""
+
+ return line.chars[start]["bbox"][0], line.chars[end - 1]["bbox"][2]
+
+
+def test_detects_long_strikethrough_and_preserves_internal_spaces() -> None:
+ """验证长删除线按字符范围生成单个紧凑样式区间。"""
+
+ line = _text_line("alpha deleted text omega")
+ start = line.text.index("deleted")
+ end = start + len("deleted text")
+ x0, x1 = _char_span(line, start, end)
+
+ detected = detect_pdf_strikethrough_lines(
+ [line],
+ [_drawing(x0, x1, 15.0)],
+ )
+
+ assert len(detected) == 1
+ assert detected[0].text == "alphadeletedtextomega"
+ assert detected[0].text[
+ detected[0].strikethrough_ranges[0].start : detected[0].strikethrough_ranges[0].end
+ ] == "deletedtext"
+
+
+def test_rejects_underline_thick_short_and_column_rule() -> None:
+ """验证下划线、粗线、短线和贯穿整栏的分隔线均不产生样式。"""
+
+ line = _text_line("alpha deleted omega")
+ start = line.text.index("deleted")
+ end = start + len("deleted")
+ x0, x1 = _char_span(line, start, end)
+ short_line = _text_line("alpha xy omega", y=30.0, source_index=1)
+ short_start = short_line.text.index("xy")
+ short_x0, short_x1 = _char_span(short_line, short_start, short_start + 2)
+
+ detected = detect_pdf_strikethrough_lines(
+ [line, short_line],
+ [
+ _drawing(x0, x1, 19.5),
+ _drawing(x0, x1, 15.0, width=2.1),
+ _drawing(short_x0, short_x1, 35.0),
+ _drawing(0.0, 200.0, 15.0),
+ ],
+ )
+
+ assert all(not item.strikethrough_ranges for item in detected)
+
+
+def test_accepts_one_aligned_endpoint_and_merges_adjacent_drawings() -> None:
+ """验证尾部延长 drawing 可由左端点确认,邻接命中区间会合并。"""
+
+ line = _text_line("alpha deleted text omega")
+ deleted_start = line.text.index("deleted")
+ deleted_end = deleted_start + len("deleted")
+ text_start = line.text.index("text")
+ text_end = text_start + len("text")
+ deleted_x0, deleted_x1 = _char_span(line, deleted_start, deleted_end)
+ text_x0, text_x1 = _char_span(line, text_start, text_end)
+
+ detected = detect_pdf_strikethrough_lines(
+ [line],
+ [
+ _drawing(deleted_x0, deleted_x1 + 5.0, 15.0),
+ _drawing(text_x0, text_x1, 15.0),
+ ],
+ )
+
+ assert len(detected[0].strikethrough_ranges) == 1
+ style_range = detected[0].strikethrough_ranges[0]
+ assert detected[0].text[style_range.start : style_range.end] == "deletedtext"
+
+
+def test_keeps_two_disjoint_strikethrough_ranges() -> None:
+ """验证同一文本行内被普通字符隔开的两条删除线保持两个样式区间。"""
+
+ line = _text_line("alpha deleted middle removed omega")
+ deleted_start = line.text.index("deleted")
+ removed_start = line.text.index("removed")
+ deleted_x0, deleted_x1 = _char_span(
+ line,
+ deleted_start,
+ deleted_start + len("deleted"),
+ )
+ removed_x0, removed_x1 = _char_span(
+ line,
+ removed_start,
+ removed_start + len("removed"),
+ )
+
+ detected = detect_pdf_strikethrough_lines(
+ [line],
+ [
+ _drawing(deleted_x0, deleted_x1, 15.0),
+ _drawing(removed_x0, removed_x1, 15.0),
+ ],
+ )
+
+ assert [
+ detected[0].text[style_range.start : style_range.end]
+ for style_range in detected[0].strikethrough_ranges
+ ] == ["deleted", "removed"]
+
+
+def test_drawing_is_assigned_to_the_closest_overlapping_line() -> None:
+ """验证一条 drawing 同时接近两行时只归属中线距离更小的文本行。"""
+
+ first = _text_line("deleted", y=10.0, source_index=0)
+ second = _text_line("deleted", y=11.0, source_index=1)
+ x0, x1 = _char_span(first, 0, len(first.text))
+
+ detected = detect_pdf_strikethrough_lines(
+ [first, second],
+ [_drawing(x0, x1, 15.1)],
+ )
+
+ ranges_by_source = {
+ line.source_index: line.strikethrough_ranges
+ for line in detected
+ }
+ assert ranges_by_source[0] == (PDFTextStyleRange(0, 7),)
+ assert ranges_by_source[1] == ()
+
+
+def test_rotated_text_is_not_a_style_candidate() -> None:
+ """验证首版忽略真正旋转的视觉文本。"""
+
+ line = _text_line("rotated text", angle=90)
+
+ assert detect_pdf_strikethrough_lines(
+ [line],
+ [_drawing(10.0, 80.0, 15.0)],
+ ) == []
+
+
+def test_invalid_line_and_char_bboxes_are_ignored() -> None:
+ """验证退化 line 或 char bbox 不会进入删除线检测。"""
+
+ invalid_line = SimpleNamespace(
+ bbox=(10.0, 10.0, 10.0, 20.0),
+ angle=0,
+ source_index=0,
+ chars=[{"char": "x", "bbox": (10.0, 10.0, 10.0, 20.0)}],
+ )
+
+ assert detect_pdf_strikethrough_lines(
+ [invalid_line],
+ [_drawing(10.0, 40.0, 15.0)],
+ ) == []
+
+
+def test_applies_style_to_plain_content_and_duplicate_second_line() -> None:
+ """验证物理行顺序可将重复文本的删除线写到第二次出现位置。"""
+
+ blocks = [
+ {
+ "type": "text",
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "deleted deleted",
+ }
+ ]
+ lines = [
+ PDFTextStyleLine((10.0, 10.0, 50.0, 20.0), "deleted", (), 0),
+ PDFTextStyleLine(
+ (10.0, 30.0, 50.0, 40.0),
+ "deleted",
+ (PDFTextStyleRange(0, 7),),
+ 1,
+ ),
+ ]
+
+ apply_pdf_strikethrough_styles(blocks, lines, (100.0, 100.0))
+
+ assert blocks[0]["content"] == 'deleted <text style="strikethrough">deleted</text>'
+
+
+def test_applies_style_inside_superscript_without_crossing_tags() -> None:
+ """验证删除线只包装 sup 内的文本叶子,不破坏原有上下标标签。"""
+
+ blocks = [
+ {
+ "type": "text",
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "value <sup>deleted</sup> tail",
+ }
+ ]
+ lines = [
+ PDFTextStyleLine(
+ (10.0, 10.0, 90.0, 20.0),
+ "valuedeletedtail",
+ (PDFTextStyleRange(5, 12),),
+ 0,
+ )
+ ]
+
+ apply_pdf_strikethrough_styles(blocks, lines, (100.0, 100.0))
+
+ assert blocks[0]["content"] == (
+ 'value <sup><text style="strikethrough">deleted</text></sup> tail'
+ )
+
+
+def test_never_styles_equations_or_excluded_blocks() -> None:
+ """验证公式内容与 table block 不会被 PDF 删除线富化。"""
+
+ blocks = [
+ {
+ "type": "text",
+ "bbox": [0.0, 0.0, 1.0, 0.5],
+ "content": "before <eq>deleted</eq> after",
+ },
+ {
+ "type": "table",
+ "bbox": [0.0, 0.5, 1.0, 1.0],
+ "content": "deleted",
+ },
+ ]
+ lines = [
+ PDFTextStyleLine(
+ (10.0, 10.0, 90.0, 20.0),
+ "beforedeletedafter",
+ (PDFTextStyleRange(6, 13),),
+ 0,
+ ),
+ PDFTextStyleLine(
+ (10.0, 60.0, 90.0, 70.0),
+ "deleted",
+ (PDFTextStyleRange(0, 7),),
+ 1,
+ ),
+ ]
+
+ apply_pdf_strikethrough_styles(blocks, lines, (100.0, 100.0))
+
+ assert blocks[0]["content"] == "before <eq>deleted</eq> after"
+ assert blocks[1]["content"] == "deleted"
+
+
+def test_flash_native_pdf_strikethrough_reaches_model_middle_and_renderers() -> None:
+ """验证真实 PDF drawing 删除线贯穿 model、MiddleJson 和三种渲染输出。"""
+
+ document = PDFDocument(_build_native_text_style_pdf())
+ try:
+ model_list = PdfModel().predict(document)
+ finally:
+ document.close()
+ model_contents = [
+ str(block.get("content") or "")
+ for page in model_list
+ for block in page
+ ]
+ joined_model_content = "\n".join(model_contents)
+ assert '<text style="strikethrough">deleted</text>' in joined_model_content
+ assert '<text style="strikethrough">filled strike</text>' in joined_model_content
+ assert "underlined" in joined_model_content
+ assert '<text style="strikethrough">underlined</text>' not in joined_model_content
+ assert '<text style="strikethrough">x</text>' not in joined_model_content
+ assert '<text style="strikethrough">separator' not in joined_model_content
+
+ middle = MiddleJson(
+ pages=model_list_to_pages(model_list),
+ file_suffix="pdf",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+ markdown = render_markdown(middle)
+ html = render_html(middle, standalone=False)
+ document_xml = ZipFile(BytesIO(render_docx(middle))).read(
+ "word/document.xml"
+ ).decode("utf-8")
+
+ assert "~~deleted~~" in markdown
+ assert "<s>deleted</s>" in html
+ assert "<w:strike" in document_xml
+
+
+def test_hybrid_txt_reuses_loaded_chars_and_applies_styles(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证 Medium/High/XHigh 共用 TXT 回填入口复用 chars 并写入删除线。"""
+
+ page_chars = [{"char": "d", "bbox": (10.0, 10.0, 16.0, 20.0), "char_idx": 0}]
+ style_lines = [
+ PDFTextStyleLine(
+ (10.0, 10.0, 52.0, 20.0),
+ "deleted",
+ (PDFTextStyleRange(0, 7),),
+ 0,
+ )
+ ]
+ build_styles = MagicMock(return_value=(page_chars, [], style_lines))
+ observed_chars: list[object] = []
+
+ def fake_fill_native(
+ _pdf_page: object,
+ _page_spans: object,
+ _page_image: object,
+ _scale: object,
+ _page_size: object,
+ *,
+ page_chars: object,
+ ) -> list[_AnalyzeSpan]:
+ """记录传入原生回填的 chars,并返回稳定文本 span。"""
+
+ observed_chars.append(page_chars)
+ return [
+ _AnalyzeSpan(
+ type=ContentType.TEXT,
+ bbox=(10.0, 10.0, 52.0, 20.0),
+ content="deleted",
+ score=1.0,
+ )
+ ]
+
+ monkeypatch.setattr(
+ text_content,
+ "build_pdf_native_visual_lines_and_styles",
+ build_styles,
+ )
+ monkeypatch.setattr(text_content, "_fill_native_pdf_text_spans", fake_fill_native)
+ monkeypatch.setattr(
+ text_content,
+ "_build_page_text_formula_spans",
+ lambda *_args: [],
+ )
+ 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="deleted",
+ score=1.0,
+ )
+ ],
+ )
+ ]
+ },
+ )
+ 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.2], "content": ""}]]
+
+ text_content._fill_window_block_content_and_lines(
+ [{"img_pil": object(), "scale": 1.0}],
+ [pdf_page],
+ model_list,
+ [[]],
+ [[]],
+ "txt",
+ {BlockType.TEXT},
+ MagicMock(),
+ )
+
+ assert observed_chars == [page_chars]
+ assert model_list[0][0]["content"] == '<text style="strikethrough">deleted</text>'
+
+
+def test_low_txt_applies_styles_after_native_content_fill(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证 Low/TXT 在 block content 完成后应用同一删除线协议。"""
+
+ span = _AnalyzeSpan(
+ type=ContentType.TEXT,
+ bbox=(10.0, 10.0, 52.0, 20.0),
+ content="deleted",
+ score=1.0,
+ )
+ style_line = PDFTextStyleLine(
+ (10.0, 10.0, 52.0, 20.0),
+ "deleted",
+ (PDFTextStyleRange(0, 7),),
+ 0,
+ )
+ monkeypatch.setattr(
+ window,
+ "_build_pdf_text_visual_run_data",
+ lambda _page: ([span], [style_line]),
+ )
+ 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.2], "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"] == '<text style="strikethrough">deleted</text>'
+
+
+def test_ocr_path_does_not_collect_or_apply_pdf_styles(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证 OCR 路径不会读取 drawing 或应用原生文本删除线。"""
+
+ build_styles = MagicMock()
+ monkeypatch.setattr(
+ text_content,
+ "build_pdf_native_visual_lines_and_styles",
+ build_styles,
+ )
+ monkeypatch.setattr(
+ text_content,
+ "_build_page_text_formula_spans",
+ lambda *_args: [
+ _AnalyzeSpan(
+ type=ContentType.TEXT,
+ bbox=(10.0, 10.0, 52.0, 20.0),
+ content="deleted",
+ score=1.0,
+ )
+ ],
+ )
+ 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="deleted",
+ score=1.0,
+ )
+ ],
+ )
+ ]
+ },
+ )
+ 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}],
+ [MagicMock(size=(100.0, 100.0))],
+ model_list,
+ [[]],
+ [[]],
+ "ocr",
+ {BlockType.TEXT},
+ MagicMock(),
+ )
+
+ build_styles.assert_not_called()
+ assert model_list[0][0]["content"] == "deleted"
+
+
+def test_native_span_fill_does_not_read_preloaded_page_chars_twice() -> None:
+ """验证删除线检测已加载 chars 后,原生 span 回填不会再次读取当前页字符。"""
+
+ page_chars = [
+ {
+ "char": char,
+ "bbox": (10.0 + index * 6.0, 10.0, 16.0 + index * 6.0, 20.0),
+ "char_idx": index,
+ "rotation": 0.0,
+ "font": {"name": "Helvetica", "flags": 0},
+ }
+ for index, char in enumerate("deleted")
+ ]
+ span = _AnalyzeSpan(
+ type=ContentType.TEXT,
+ bbox=(10.0, 10.0, 52.0, 20.0),
+ score=1.0,
+ )
+ pdf_page = MagicMock()
+ pdf_page.get_char_count.return_value = len(page_chars)
+
+ result = txt_spans_extract(
+ pdf_page,
+ [span],
+ object(),
+ 1.0,
+ [(0.0, 0.0, 100.0, 100.0, None, None, None, BlockType.TEXT)],
+ [],
+ page_chars=page_chars,
+ )
+
+ assert result == [span]
+ assert span.content == "deleted"
+ pdf_page.get_chars.assert_not_called()