Skip to content

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

refactor: rename strikethrough style functions and update related documentation

myhlolie84ad3443c36
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.md
index b858a6c0..dd49065e 100644
--- a/docs/next/middle-json/rendering.md
+++ b/docs/next/middle-json/rendering.md
@@ -234,8 +234,25 @@ content_list = render_content_list(
`content` 保存适合结构化消费的文本表示,而不是可直接拼接成整篇文档的完整视觉
Markdown。`list/index` 的递归子树会收敛为一个字符串;`image/table/chart/code` 的唯一
body 会提升为父块 `content`,但图片资源只放在 `image_source`,不在 `content` 重复
-输出图片语法或 details。说明文本按源 `index` 排序后分别输出为 `captions: list[str]`
-和 `footnotes: list[str]`,视觉数组始终存在,空说明保留为空字符串。
+输出图片语法或 details。说明文本按源 `index` 排序后分别输出为
+`captions/footnotes: list[{bbox?: [x0, y0, x1, y1], content: str}]`。`bbox` 直接保留
+说明子块的归一化坐标,源坐标缺失时省略该键;不输出说明的 `type/index`。视觉数组始终
+存在,空说明保留为 `{"content": ""}`。这是相对于原字符串数组结构的直接契约变更,
+消费方必须通过对象的 `content` 字段读取说明文本。
+
+```json
+{
+ "captions": [
+ {
+ "bbox": [0.073, 0.235, 0.485, 0.245],
+ "content": "图表1:汽车指数上周下跌 2.29%"
+ },
+ {
+ "content": "没有源坐标的 Office 说明"
+ }
+ ]
+}
+```
`doc_title/paragraph_title.content` 只包含行内 Markdown,不含 heading 标记或 HTML
anchor;原始 `level` 和可选 `anchor` 作为独立字段保留。`equation.content` 是不带行间
diff --git a/mineru/backend/analysis/pdf/tables.py b/mineru/backend/analysis/pdf/tables.py
index 63527a7b..8591276b 100644
--- a/mineru/backend/analysis/pdf/tables.py
+++ b/mineru/backend/analysis/pdf/tables.py
@@ -84,7 +84,7 @@ 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 和同页水平删除线证据。"""
+ """一次构造 Low/TXT 视觉 span 和同页水平文本样式证据。"""
_page_chars, line_items, style_lines = build_pdf_native_visual_lines_and_styles(
pdf_page,
diff --git a/mineru/backend/analysis/pdf/text/content.py b/mineru/backend/analysis/pdf/text/content.py
index 9e12ae69..73ad77ca 100644
--- a/mineru/backend/analysis/pdf/text/content.py
+++ b/mineru/backend/analysis/pdf/text/content.py
@@ -16,7 +16,7 @@ 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,
+ apply_pdf_text_styles,
)
from mineru.utils.text_utils import resolve_text_line_boundary
@@ -399,7 +399,7 @@ def _fill_window_block_content_and_lines(
block_lines,
page_size,
)
- apply_pdf_strikethrough_styles(
+ apply_pdf_text_styles(
page_model_list,
style_lines,
page_size,
diff --git a/mineru/backend/analysis/pdf/text/styles.py b/mineru/backend/analysis/pdf/text/styles.py
index 9537d44b..ea140194 100644
--- a/mineru/backend/analysis/pdf/text/styles.py
+++ b/mineru/backend/analysis/pdf/text/styles.py
@@ -10,7 +10,7 @@ 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,
+ detect_pdf_text_style_lines,
)
@@ -20,7 +20,7 @@ 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 及其水平删除线证据。"""
+ """一次读取当前页字符,构造视觉 run 及其水平文本样式证据。"""
# 延迟导入避免 Hybrid 模块初始化时提前加载完整 Flash PDF 流水线。
from mineru.model.flash.native_pdf.native_text import _build_native_line_items
@@ -32,7 +32,7 @@ def build_pdf_native_visual_lines_and_styles(
page_rotation=pdf_page.rotation,
supported_angles=supported_angles,
)
- style_lines = detect_pdf_strikethrough_lines(
+ style_lines = detect_pdf_text_style_lines(
line_items,
pdf_page.get_drawing_lines(),
)
diff --git a/mineru/backend/analysis/pdf/window.py b/mineru/backend/analysis/pdf/window.py
index 74edaf27..e45dec52 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, 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.pdf_text_styles import apply_pdf_text_styles
from mineru.utils.spatial_text import project_pdf_spatial_text
from .constants import (
@@ -202,7 +202,7 @@ def _process_low_text(
block_lines,
page_size,
)
- apply_pdf_strikethrough_styles(
+ apply_pdf_text_styles(
page_model_list,
style_lines,
page_size,
diff --git a/mineru/model/flash/native_pdf/pipeline.py b/mineru/model/flash/native_pdf/pipeline.py
index b1247791..9393e6e8 100644
--- a/mineru/model/flash/native_pdf/pipeline.py
+++ b/mineru/model/flash/native_pdf/pipeline.py
@@ -12,8 +12,8 @@ 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,
+ apply_pdf_text_styles,
+ detect_pdf_text_style_lines,
)
from .models import (
@@ -217,7 +217,7 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
)
drawing_lines = _get_pdf_drawing_lines(pdf_doc, page_idx)
page_style_lines.append(
- detect_pdf_strikethrough_lines(lines, drawing_lines)
+ detect_pdf_text_style_lines(lines, drawing_lines)
)
source = _PageSource(
page_size=page_size,
@@ -275,7 +275,7 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
page_sizes,
strict=True,
):
- apply_pdf_strikethrough_styles(page_blocks, style_lines, page_size)
+ apply_pdf_text_styles(page_blocks, style_lines, page_size)
return finalized_pages
diff --git a/mineru/model/flash/native_pdf/titles.py b/mineru/model/flash/native_pdf/titles.py
index de143174..63629108 100644
--- a/mineru/model/flash/native_pdf/titles.py
+++ b/mineru/model/flash/native_pdf/titles.py
@@ -10,6 +10,10 @@ from typing import Literal
from mineru.types import BBox
+from mineru.utils.pdf_text_styles import (
+ PDF_FONT_FORCE_BOLD_FLAG,
+ PDF_FONT_ITALIC_FLAG,
+)
from .models import (
_DocumentBodyProfile,
@@ -39,12 +43,6 @@ from .line_layout import (
_title_fonts_compatible,
)
-
-# PDF FontDescriptor 中 Italic 与 ForceBold 位用于排除非常规字体画像。
-_PDF_FONT_ITALIC_FLAG = 1 << 6
-_PDF_FONT_FORCE_BOLD_FLAG = 1 << 18
-
-
def _classify_page_titles(
lines: list[_LineItem],
page_size: tuple[float, float],
@@ -682,7 +680,7 @@ def _document_font_is_regular(
) -> bool:
"""用字体样式位和全文正文基准过滤斜体、粗体等强调字体。"""
- if font[1] & (_PDF_FONT_ITALIC_FLAG | _PDF_FONT_FORCE_BOLD_FLAG):
+ if font[1] & (PDF_FONT_ITALIC_FLAG | PDF_FONT_FORCE_BOLD_FLAG):
return False
if not weights or body_weight is None:
return True
@@ -1298,7 +1296,7 @@ def _classify_cross_lane_emphasized_section_titles(
for line, bbox in line_geometry:
if line.semantic_type is not None or line.font_signature is None:
continue
- if not line.font_signature[1] & _PDF_FONT_ITALIC_FLAG:
+ if not line.font_signature[1] & PDF_FONT_ITALIC_FLAG:
continue
if _line_uses_document_regular_font(line, document_body_profile):
continue
diff --git a/mineru/render/content_list.py b/mineru/render/content_list.py
index d505a52f..f785fa2d 100644
--- a/mineru/render/content_list.py
+++ b/mineru/render/content_list.py
@@ -132,8 +132,8 @@ def _render_annotation_group(
block: VisualBlock,
accepted_types: set[str],
delimiters: LatexDelimitersConfig,
-) -> list[str]:
- """按源 index 稳定排序一组视觉说明,并逐项渲染为 Markdown。"""
+) -> list[dict[str, Any]]:
+ """按源 index 稳定排序视觉说明,并保留可用 bbox 与 Markdown 内容。"""
annotations: list[tuple[int, VisualAnnotationBlock]] = []
for position, child in enumerate(block.content):
if (
@@ -145,7 +145,14 @@ def _render_annotation_group(
):
annotations.append((position, child))
annotations.sort(key=_annotation_sort_key)
- return [render_visual_annotation(child, delimiters) for _, child in annotations]
+ rendered_annotations: list[dict[str, Any]] = []
+ for _, child in annotations:
+ annotation_payload: dict[str, Any] = {}
+ if child.bbox is not None:
+ annotation_payload["bbox"] = list(child.bbox)
+ annotation_payload["content"] = render_visual_annotation(child, delimiters)
+ rendered_annotations.append(annotation_payload)
+ return rendered_annotations
def _annotation_sort_key(
diff --git a/mineru/utils/pdf_text_styles.py b/mineru/utils/pdf_text_styles.py
index 7fbde40c..914b29d8 100644
--- a/mineru/utils/pdf_text_styles.py
+++ b/mineru/utils/pdf_text_styles.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""从 PDF 原生字符与绘图线中恢复文本删除线样式。"""
+"""从 PDF 原生字符与绘图线中恢复文本字体和装饰线样式。"""
from __future__ import annotations
@@ -7,18 +7,38 @@ import math
import re
import statistics
from dataclasses import dataclass
-from typing import Any, Sequence
+from typing import Any, Iterable, Literal, Sequence, cast
from loguru import logger
from mineru.types import BBox, BlockType, RAW_CAPTION, RAW_FOOTNOTE
-STRIKETHROUGH_MIN_LENGTH_HEIGHT_RATIO = 2.0
+TEXT_DECORATION_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
+UNDERLINE_BOTTOM_TOLERANCE_HEIGHT_RATIO = 0.2
+TEXT_DECORATION_MAX_WIDTH_HEIGHT_RATIO = 0.2
+TEXT_DECORATION_MIN_TEXT_COVERAGE_RATIO = 0.55
+TEXT_DECORATION_ENDPOINT_TOLERANCE_HEIGHT_RATIO = 0.5
+UNDERLINE_FRACTION_MAX_GAP_HEIGHT_RATIO = 0.15
+UNDERLINE_FRACTION_MIN_LOWER_LINE_COVERAGE = 0.8
+PDF_FONT_ITALIC_FLAG = 1 << 6
+PDF_FONT_FORCE_BOLD_FLAG = 1 << 18
+PDF_BOLD_MIN_WEIGHT = 600.0
+PDF_BOLD_MIN_COMPARABLE_CHAR_COUNT = 2
+
+PDFTextStyle = Literal["bold", "italic", "underline", "strikethrough"]
+PDFTextDecoration = Literal["underline", "strikethrough"]
+PDF_TEXT_STYLE_ORDER: tuple[PDFTextStyle, ...] = (
+ "bold",
+ "italic",
+ "underline",
+ "strikethrough",
+)
+_PDF_TEXT_DECORATION_ORDER: tuple[PDFTextDecoration, ...] = (
+ "underline",
+ "strikethrough",
+)
PDF_NATURAL_TEXT_STYLE_BLOCK_TYPES = frozenset(
{
@@ -37,12 +57,27 @@ PDF_NATURAL_TEXT_STYLE_BLOCK_TYPES = frozenset(
RAW_FOOTNOTE,
}
)
+_PDF_TEXT_STYLE_TARGET_BLOCK_TYPES: dict[PDFTextStyle, frozenset[str]] = {
+ "bold": frozenset({BlockType.TEXT}),
+ "italic": frozenset(),
+ "underline": frozenset({BlockType.TEXT}),
+ "strikethrough": PDF_NATURAL_TEXT_STYLE_BLOCK_TYPES,
+}
_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_FONT_SUBSET_PREFIX_RE = re.compile(r"^[A-Z]{6}\+")
+_PDF_BOLD_FONT_NAME_RE = re.compile(
+ r"bold|demi|black|heavy|(?:^|[-_,])(?:bd|bi)(?:mt)?$|gbi$|(?:^|[-_,])w[6-9]$",
+ re.IGNORECASE,
+)
+_PDF_LIST_MARKER_CHARS = frozenset(
+ "•◦‣⁃▪▫●○■□∙·▶▷►▸▹\uf0b7"
+)
+_PDF_GEOMETRIC_TEXT_STYLES = frozenset({"underline", "strikethrough"})
_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"
@@ -62,25 +97,26 @@ _LIGATURE_REPLACEMENTS = {
@dataclass(frozen=True, slots=True)
class PDFTextStyleRange:
- """保存可比较文本中的一个半开删除线区间。"""
+ """保存可比较文本中的一个半开样式区间。"""
start: int
end: int
+ styles: tuple[PDFTextStyle, ...]
@dataclass(frozen=True, slots=True)
class PDFTextStyleLine:
- """保存一个视觉文本 run 的几何、可比较文本和删除线区间。"""
+ """保存一个视觉文本 run 的几何、可比较文本和样式区间。"""
bbox: BBox
text: str
- strikethrough_ranges: tuple[PDFTextStyleRange, ...]
+ style_ranges: tuple[PDFTextStyleRange, ...]
source_index: int
@dataclass(frozen=True, slots=True)
class _VisibleChar:
- """保存参与删除线几何判断的可见字符。"""
+ """保存参与文本装饰线几何判断的可见字符。"""
source_index: int
bbox: BBox
@@ -88,24 +124,27 @@ class _VisibleChar:
@dataclass(slots=True)
class _LineCandidate:
- """保存删除线匹配阶段使用的视觉文本行指标。"""
+ """保存字体与文本装饰线匹配阶段使用的视觉文本行指标。"""
bbox: BBox
chars: list[dict[str, Any]]
visible_chars: list[_VisibleChar]
median_height: float
center_y: float
+ bottom_y: float
source_index: int
- ranges: list[tuple[int, int]]
+ font_styles: list[frozenset[PDFTextStyle]]
+ decoration_ranges: dict[PDFTextDecoration, list[tuple[int, int]]]
@dataclass(frozen=True, slots=True)
class _DrawingMatch:
"""保存单条 drawing 对单个文本行的匹配结果和排序指标。"""
+ style: PDFTextDecoration
start_index: int
end_index: int
- center_distance_ratio: float
+ target_distance_ratio: float
horizontal_overlap_ratio: float
@@ -116,7 +155,43 @@ class _ProjectedChar:
value: str
raw_start: int
raw_end: int
- styleable: bool
+ existing_styles: frozenset[PDFTextStyle]
+ formula_gap_before: bool
+
+
+@dataclass(frozen=True, slots=True)
+class _InlineTagState:
+ """保存一个已打开行内标签的匹配排除状态和已有字体样式。"""
+
+ tag: str
+ excluded: bool
+ styles: frozenset[PDFTextStyle]
+
+
+@dataclass(frozen=True, slots=True)
+class _RawStyleInterval:
+ """保存 model content 原字符串中的半开样式区间。"""
+
+ start: int
+ end: int
+ styles: tuple[PDFTextStyle, ...]
+
+
+@dataclass(frozen=True, slots=True)
+class _LineProjectionMatch:
+ """保存物理行跨公式空洞对齐到 block 可比较文本的结果。"""
+
+ start: int
+ end: int
+ source_to_projected: tuple[int | None, ...]
+
+
+def _style_line_reading_order_key(
+ line: PDFTextStyleLine,
+) -> tuple[int, float, float]:
+ """优先使用原生 source_index 排序,重复索引时再以 bbox 保持稳定。"""
+
+ return line.source_index, line.bbox[1], line.bbox[0]
def _coerce_bbox(value: Any) -> BBox | None:
@@ -168,6 +243,127 @@ def _normalize_match_fragment(value: Any) -> str:
return "".join(output)
+def _canonical_styles(styles: Iterable[str]) -> tuple[PDFTextStyle, ...]:
+ """按公开富文本协议顺序过滤、去重并规范样式集合。"""
+
+ style_set = set(styles)
+ return cast(
+ tuple[PDFTextStyle, ...],
+ tuple(style for style in PDF_TEXT_STYLE_ORDER if style in style_set),
+ )
+
+
+def _pdf_font_metadata(char: dict[str, Any]) -> tuple[str, int, float | None]:
+ """读取单个字符的规范字体名、FontDescriptor flags 和有效字重。"""
+
+ font = char.get("font")
+ if not isinstance(font, dict):
+ return "", 0, None
+ font_name = _PDF_FONT_SUBSET_PREFIX_RE.sub(
+ "",
+ str(font.get("name") or ""),
+ )
+ try:
+ font_flags = int(font.get("flags") or 0)
+ except (TypeError, ValueError):
+ font_flags = 0
+ try:
+ font_weight = float(font.get("weight"))
+ except (TypeError, ValueError):
+ font_weight = math.nan
+ if not math.isfinite(font_weight) or font_weight <= 0:
+ font_weight = None
+ return font_name, font_flags, font_weight
+
+
+def _char_font_styles(char: dict[str, Any]) -> frozenset[PDFTextStyle]:
+ """只依据直接字体证据返回 PDF 字符粗体样式。"""
+
+ font_name, font_flags, font_weight = _pdf_font_metadata(char)
+ styles: set[PDFTextStyle] = set()
+ if (
+ font_flags & PDF_FONT_FORCE_BOLD_FLAG
+ or (font_weight is not None and font_weight >= PDF_BOLD_MIN_WEIGHT)
+ or bool(_PDF_BOLD_FONT_NAME_RE.search(font_name))
+ ):
+ styles.add("bold")
+ return frozenset(styles)
+
+
+def _has_list_marker_separator(
+ chars: Sequence[dict[str, Any]],
+ marker_source_index: int,
+ next_source_index: int,
+ median_height: float,
+) -> bool:
+ """判断行首项目符号与后续正文之间是否存在空白或明显视觉间隔。"""
+
+ if any(
+ str(chars[index].get("char") or "").isspace()
+ for index in range(marker_source_index + 1, next_source_index)
+ ):
+ return True
+ marker_bbox = _coerce_bbox(chars[marker_source_index].get("bbox"))
+ next_bbox = _coerce_bbox(chars[next_source_index].get("bbox"))
+ return bool(
+ marker_bbox is not None
+ and next_bbox is not None
+ and next_bbox[0] - marker_bbox[2] >= 0.5 * median_height
+ )
+
+
+def _filter_pdf_bold_runs(
+ chars: Sequence[dict[str, Any]],
+ font_styles: Sequence[frozenset[PDFTextStyle]],
+ median_height: float,
+) -> list[frozenset[PDFTextStyle]]:
+ """过滤过短粗体 run 和与正文分离的行首项目符号粗体。"""
+
+ output = list(font_styles)
+ comparable_chars = [
+ (source_index, fragment)
+ for source_index, char in enumerate(chars)
+ if (fragment := _normalize_match_fragment(char.get("char")))
+ ]
+ run_start = 0
+ while run_start < len(comparable_chars):
+ source_index, _fragment = comparable_chars[run_start]
+ if "bold" not in output[source_index]:
+ run_start += 1
+ continue
+ run_end = run_start + 1
+ while run_end < len(comparable_chars):
+ next_source_index, _next_fragment = comparable_chars[run_end]
+ if "bold" not in output[next_source_index]:
+ break
+ run_end += 1
+
+ run = comparable_chars[run_start:run_end]
+ run_text = "".join(fragment for _index, fragment in run)
+ is_short = len(run_text) < PDF_BOLD_MIN_COMPARABLE_CHAR_COUNT
+ is_isolated_leading_marker = (
+ run_start == 0
+ and run_end < len(comparable_chars)
+ and bool(run_text)
+ and all(char in _PDF_LIST_MARKER_CHARS for char in run_text)
+ and _has_list_marker_separator(
+ chars,
+ run[-1][0],
+ comparable_chars[run_end][0],
+ median_height,
+ )
+ )
+ if is_short or is_isolated_leading_marker:
+ for run_source_index, _run_fragment in run:
+ output[run_source_index] = frozenset(
+ style
+ for style in output[run_source_index]
+ if style != "bold"
+ )
+ run_start = run_end
+ return output
+
+
def _build_line_candidate(line: Any) -> _LineCandidate | None:
"""从视觉水平 line 构造字符几何候选,旋转文字和退化行返回空。"""
@@ -191,26 +387,43 @@ def _build_line_candidate(line: Any) -> _LineCandidate | None:
median_height = statistics.median(heights)
if median_height <= 0:
return None
- body_centers = [
- (char.bbox[1] + char.bbox[3]) / 2
+ body_chars = [
+ char
for char, height in zip(visible_chars, heights)
if height >= 0.8 * median_height
]
- if not body_centers:
+ if not body_chars:
return None
+ font_styles = [_char_font_styles(char) for char in chars]
return _LineCandidate(
bbox=line_bbox,
chars=chars,
visible_chars=visible_chars,
median_height=median_height,
- center_y=statistics.median(body_centers),
+ center_y=statistics.median(
+ (char.bbox[1] + char.bbox[3]) / 2
+ for char in body_chars
+ ),
+ bottom_y=statistics.median(char.bbox[3] for char in body_chars),
source_index=int(getattr(line, "source_index", 0) or 0),
- ranges=[],
+ font_styles=_filter_pdf_bold_runs(
+ chars,
+ font_styles,
+ median_height,
+ ),
+ decoration_ranges={
+ "underline": [],
+ "strikethrough": [],
+ },
)
-def _drawing_match_for_line(line: _LineCandidate, drawing: Any) -> _DrawingMatch | None:
- """按长度、中带、线宽、字符覆盖和端点贴合校验单条删除线候选。"""
+def _drawing_match_for_line(
+ line: _LineCandidate,
+ drawing: Any,
+ style: PDFTextDecoration,
+) -> _DrawingMatch | None:
+ """按目标纵向锚点和公共几何规则校验单条文本装饰线。"""
if getattr(drawing, "orientation", None) != "horizontal":
return None
@@ -218,17 +431,23 @@ def _drawing_match_for_line(line: _LineCandidate, drawing: Any) -> _DrawingMatch
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:
+ if drawing_length < TEXT_DECORATION_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:
+ target_y = line.bottom_y if style == "underline" else line.center_y
+ target_tolerance = (
+ UNDERLINE_BOTTOM_TOLERANCE_HEIGHT_RATIO
+ if style == "underline"
+ else STRIKETHROUGH_CENTER_TOLERANCE_HEIGHT_RATIO
+ )
+ target_distance_ratio = abs(drawing_center_y - target_y) / line.median_height
+ if target_distance_ratio > target_tolerance:
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:
+ if drawing_width > TEXT_DECORATION_MAX_WIDTH_HEIGHT_RATIO * line.median_height:
return None
hit_chars = [
@@ -240,13 +459,13 @@ def _drawing_match_for_line(line: _LineCandidate, drawing: Any) -> _DrawingMatch
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:
+ if (hit_right - hit_left) / drawing_length < TEXT_DECORATION_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:
+ if endpoint_distance > TEXT_DECORATION_ENDPOINT_TOLERANCE_HEIGHT_RATIO * line.median_height:
return None
overlap = max(
@@ -258,9 +477,10 @@ def _drawing_match_for_line(line: _LineCandidate, drawing: Any) -> _DrawingMatch
min(line.bbox[2] - line.bbox[0], drawing_length),
)
return _DrawingMatch(
+ style=style,
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,
+ target_distance_ratio=target_distance_ratio,
horizontal_overlap_ratio=horizontal_overlap_ratio,
)
@@ -280,109 +500,204 @@ def _merge_source_ranges(ranges: list[tuple[int, int]]) -> list[tuple[int, int]]
def _line_style_payload(line: _LineCandidate) -> PDFTextStyleLine | None:
- """把来源字符和删除线索引转换为紧凑文本及其半开样式区间。"""
+ """把来源字符的字体与装饰线证据转换为紧凑文本样式区间。"""
- source_ranges = _merge_source_ranges(line.ranges)
+ decoration_styles: list[set[PDFTextStyle]] = [
+ set()
+ for _char in line.chars
+ ]
+ for style in _PDF_TEXT_DECORATION_ORDER:
+ for start, end in _merge_source_ranges(line.decoration_ranges[style]):
+ for char_index in range(max(0, start), min(end, len(line.chars))):
+ decoration_styles[char_index].add(style)
compact_parts: list[str] = []
- compact_ranges: list[PDFTextStyleRange] = []
- compact_length = 0
- active_start: int | None = None
- active_end = 0
+ compact_styles: list[tuple[PDFTextStyle, ...]] = []
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))
+ styles = set(line.font_styles[char_index])
+ styles.update(decoration_styles[char_index])
+ canonical_styles = _canonical_styles(styles)
+ compact_styles.extend([canonical_styles] * len(fragment))
text = "".join(compact_parts)
if not text:
return None
+ compact_ranges: list[PDFTextStyleRange] = []
+ active_start = 0
+ active_styles: tuple[PDFTextStyle, ...] = ()
+ for offset, styles in enumerate([*compact_styles, ()]):
+ if styles == active_styles:
+ continue
+ if active_styles:
+ compact_ranges.append(
+ PDFTextStyleRange(active_start, offset, active_styles)
+ )
+ active_start = offset
+ active_styles = styles
return PDFTextStyleLine(
bbox=line.bbox,
text=text,
- strikethrough_ranges=tuple(compact_ranges),
+ style_ranges=tuple(compact_ranges),
source_index=line.source_index,
)
-def _build_line_center_grid(
+def _build_line_geometry_grids(
candidates: Sequence[_LineCandidate],
-) -> tuple[float, dict[int, list[int]]]:
- """按删除线允许的纵向中带建立行索引,避免逐 drawing 扫描整页文本行。"""
+) -> tuple[
+ float,
+ dict[int, list[tuple[int, PDFTextDecoration]]],
+ dict[int, list[int]],
+]:
+ """按装饰线锚点和行顶坐标建立网格,限制每条 drawing 的局部比较范围。"""
grid_size = max(
1.0,
statistics.median(line.median_height for line in candidates),
)
- grid: dict[int, list[int]] = {}
+ anchor_grid: dict[int, list[tuple[int, PDFTextDecoration]]] = {}
+ top_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
+ top_grid.setdefault(math.floor(line.bbox[1] / grid_size), []).append(
+ line_index
+ )
+ for style, target_y, tolerance_ratio in (
+ (
+ "underline",
+ line.bottom_y,
+ UNDERLINE_BOTTOM_TOLERANCE_HEIGHT_RATIO,
+ ),
+ (
+ "strikethrough",
+ line.center_y,
+ STRIKETHROUGH_CENTER_TOLERANCE_HEIGHT_RATIO,
+ ),
+ ):
+ tolerance = tolerance_ratio * line.median_height
+ start_cell = math.floor((target_y - tolerance) / grid_size)
+ end_cell = math.floor((target_y + tolerance) / grid_size)
+ for cell in range(start_cell, end_cell + 1):
+ anchor_grid.setdefault(cell, []).append((line_index, style))
+ return grid_size, anchor_grid, top_grid
+
+
+def _is_fraction_bar_candidate(
+ candidates: Sequence[_LineCandidate],
+ top_grid: dict[int, list[int]],
+ grid_size: float,
+ line_index: int,
+ drawing_bbox: BBox,
+) -> bool:
+ """用紧邻且被横线覆盖的下方文本 run 排除公式分数线。"""
+
+ line = candidates[line_index]
+ drawing_center_y = (drawing_bbox[1] + drawing_bbox[3]) / 2
+ max_lower_top = (
+ drawing_center_y
+ + UNDERLINE_FRACTION_MAX_GAP_HEIGHT_RATIO * line.median_height
+ )
+ lower_indices: set[int] = set()
+ for cell in range(
+ math.floor(drawing_center_y / grid_size),
+ math.floor(max_lower_top / grid_size) + 1,
+ ):
+ lower_indices.update(top_grid.get(cell, ()))
+ for lower_index in lower_indices:
+ if lower_index == line_index:
+ continue
+ lower_line = candidates[lower_index]
+ if not drawing_center_y <= lower_line.bbox[1] <= max_lower_top:
+ continue
+ lower_width = lower_line.bbox[2] - lower_line.bbox[0]
+ horizontal_overlap = max(
+ 0.0,
+ min(drawing_bbox[2], lower_line.bbox[2])
+ - max(drawing_bbox[0], lower_line.bbox[0]),
+ )
+ if (
+ horizontal_overlap / max(0.01, lower_width)
+ >= UNDERLINE_FRACTION_MIN_LOWER_LINE_COVERAGE
+ ):
+ return True
+ return False
-def detect_pdf_strikethrough_lines(
+def detect_pdf_text_style_lines(
lines: Sequence[Any],
drawing_lines: Sequence[Any],
) -> list[PDFTextStyleLine]:
- """从视觉文本 run 与页面 drawing 中生成全部水平行及其删除线证据。"""
+ """从视觉文本 run 与页面 drawing 中生成全部水平行样式证据。"""
+ candidates = [
+ candidate
+ for line in lines
+ if (candidate := _build_line_candidate(line)) is not None
+ ]
+ if not candidates:
+ return []
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 horizontal_drawings:
+ grid_size, anchor_grid, top_grid = _build_line_geometry_grids(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_anchors = anchor_grid.get(
+ math.floor(drawing_center_y / grid_size),
+ [],
+ )
+ matches: list[tuple[int, _DrawingMatch]] = []
+ for line_index, style in candidate_anchors:
+ match = _drawing_match_for_line(
+ candidates[line_index],
+ drawing,
+ style,
+ )
+ if match is None:
+ continue
+ if style == "underline" and _is_fraction_bar_candidate(
+ candidates,
+ top_grid,
+ grid_size,
+ line_index,
+ drawing_bbox,
+ ):
+ continue
+ matches.append((line_index, match))
+ if not matches:
+ continue
+ line_index, best_match = min(
+ matches,
+ key=lambda item: (
+ item[1].target_distance_ratio,
+ -item[1].horizontal_overlap_ratio,
+ candidates[item[0]].source_index,
+ _PDF_TEXT_DECORATION_ORDER.index(item[1].style),
+ ),
+ )
+ candidates[line_index].decoration_ranges[best_match.style].append(
+ (best_match.start_index, best_match.end_index)
+ )
- if not any(line.ranges for line in candidates):
+ payloads = [
+ payload
+ for line in candidates
+ if (payload := _line_style_payload(line)) is not None
+ ]
+ if not any(line.style_ranges for line in payloads):
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))
+ return sorted(
+ payloads,
+ key=_style_line_reading_order_key,
+ )
def _block_bbox_to_page_bbox(value: Any, page_size: tuple[float, float]) -> BBox | None:
@@ -454,27 +769,90 @@ 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=lambda line: (line.bbox[1], line.bbox[0], line.source_index))
+ block_lines.sort(key=_style_line_reading_order_key)
return assignments
-def _text_tag_has_strikethrough(attrs: str) -> bool:
- """判断 text 标签是否已经显式携带删除线样式。"""
+def _filter_line_styles_for_block(
+ lines: Sequence[PDFTextStyleLine],
+ block_type: Any,
+) -> list[PDFTextStyleLine]:
+ """按目标 block 类型过滤样式区间,同时保留无样式物理行用于顺序对齐。"""
+
+ output: list[PDFTextStyleLine] = []
+ for line in lines:
+ filtered_ranges: list[PDFTextStyleRange] = []
+ for style_range in line.style_ranges:
+ styles = _canonical_styles(
+ style
+ for style in style_range.styles
+ if block_type
+ in _PDF_TEXT_STYLE_TARGET_BLOCK_TYPES.get(
+ style,
+ frozenset(),
+ )
+ )
+ if styles:
+ filtered_ranges.append(
+ PDFTextStyleRange(
+ style_range.start,
+ style_range.end,
+ styles,
+ )
+ )
+ output.append(
+ PDFTextStyleLine(
+ bbox=line.bbox,
+ text=line.text,
+ style_ranges=tuple(filtered_ranges),
+ source_index=line.source_index,
+ )
+ )
+ return output
+
+
+def _text_tag_styles(attrs: str) -> frozenset[PDFTextStyle]:
+ """提取 text 标签中已存在且属于 PDF 富化范围的样式。"""
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(",")
- }
+ return frozenset()
+ return frozenset(
+ cast(PDFTextStyle, style)
+ for raw_style in match.group("style").split(",")
+ if (style := raw_style.strip().lower()) in PDF_TEXT_STYLE_ORDER
+ )
+
+
+def _direct_tag_styles(tag: str) -> frozenset[PDFTextStyle]:
+ """把直接 HTML 风格标签转换为当前 PDF 富化识别的样式。"""
+
+ style = {
+ "strong": "bold",
+ "b": "bold",
+ "em": "italic",
+ "i": "italic",
+ "u": "underline",
+ "s": "strikethrough",
+ }.get(tag)
+ return frozenset({cast(PDFTextStyle, style)}) if style is not None else frozenset()
+
+
+def _active_inline_styles(stack: Sequence[_InlineTagState]) -> frozenset[PDFTextStyle]:
+ """合并当前位置全部已打开标签携带的字体样式。"""
+
+ return frozenset(
+ style
+ for state in stack
+ for style in state.styles
+ )
-def _pop_inline_tag(stack: list[tuple[str, bool, bool]], tag: str) -> None:
+def _pop_inline_tag(stack: list[_InlineTagState], tag: str) -> None:
"""从行内标签栈弹出最近的同名元素,容忍损坏嵌套。"""
for index in range(len(stack) - 1, -1, -1):
- if stack[index][0] == tag:
+ if stack[index].tag == tag:
del stack[index:]
return
@@ -483,43 +861,56 @@ def _project_content_chars(content: str) -> list[_ProjectedChar]:
"""把 model content 投影为忽略空白和公式的可比较字符,并保留原始 offset。"""
projected: list[_ProjectedChar] = []
- stack: list[tuple[str, bool, bool]] = []
+ stack: list[_InlineTagState] = []
+ pending_formula_gap = False
cursor = 0
while cursor < len(content):
- if not any(item[1] for item in stack) and content.startswith(r"\(", cursor):
+ if not any(state.excluded for state in stack) and content.startswith(r"\(", cursor):
formula_end = content.find(r"\)", cursor + 2)
if formula_end >= 0:
cursor = formula_end + 2
+ pending_formula_gap = True
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)
+ if tag == "eq":
+ pending_formula_gap = True
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)),
+ _InlineTagState(
+ tag=tag,
+ excluded=tag in {"eq", "url"},
+ styles=(
+ _text_tag_styles(attrs)
+ if tag == "text"
+ else _direct_tag_styles(tag)
+ ),
)
)
cursor = tag_match.end()
continue
raw_char = content[cursor]
- if not any(item[1] for item in stack):
+ if not any(state.excluded for state in stack):
fragment = _normalize_match_fragment(raw_char)
- for value in fragment:
+ for fragment_index, value in enumerate(fragment):
projected.append(
_ProjectedChar(
value=value,
raw_start=cursor,
raw_end=cursor + 1,
- styleable=not any(item[2] for item in stack),
+ existing_styles=_active_inline_styles(stack),
+ formula_gap_before=(
+ pending_formula_gap and fragment_index == 0
+ ),
)
)
+ if fragment:
+ pending_formula_gap = False
cursor += 1
return projected
@@ -541,12 +932,10 @@ def _resolve_fallback_occurrence(
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]
@@ -565,17 +954,142 @@ def _resolve_fallback_occurrence(
)
for position in occurrences
]
+ has_geometric_style = bool(
+ _PDF_GEOMETRIC_TEXT_STYLES.intersection(style_range.styles)
+ )
+ if len(occurrences) == 1 and (
+ has_geometric_style or len(target) >= 3
+ ):
+ return occurrences[0]
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
+ if has_geometric_style:
+ return best_positions[0] if best_score > 0 and len(best_positions) == 1 else None
+ required_context_score = int(bool(left_context)) + int(bool(right_context))
+ return (
+ best_positions[0]
+ if required_context_score > 0
+ and best_score == required_context_score
+ and len(best_positions) == 1
+ else None
+ )
+
+
+def _match_line_across_formula_gaps(
+ line_text: str,
+ projected: Sequence[_ProjectedChar],
+ start: int,
+) -> _LineProjectionMatch | None:
+ """用精确字符序列跨过公式空洞,将一个物理行对齐到 block 文本。"""
+
+ if (
+ not line_text
+ or start >= len(projected)
+ or not any(token.formula_gap_before for token in projected[start:])
+ ):
+ return None
+ for projected_start in range(max(0, start), len(projected)):
+ first_token = projected[projected_start]
+ if not first_token.formula_gap_before and first_token.value != line_text[0]:
+ continue
+ states: dict[int, tuple[int | None, ...]] = {0: ()}
+ for projected_index in range(projected_start, len(projected)):
+ token = projected[projected_index]
+ next_states: dict[int, tuple[int | None, ...]] = {}
+ for source_index, mapping in states.items():
+ if source_index >= len(line_text):
+ continue
+ if token.formula_gap_before:
+ candidate_source_indices = range(
+ source_index + 1,
+ len(line_text),
+ )
+ elif line_text[source_index] == token.value:
+ candidate_source_indices = (source_index,)
+ else:
+ continue
+ for matched_source_index in candidate_source_indices:
+ if line_text[matched_source_index] != token.value:
+ continue
+ next_source_index = matched_source_index + 1
+ next_mapping = (
+ *mapping,
+ *([None] * (matched_source_index - source_index)),
+ projected_index,
+ )
+ next_states.setdefault(next_source_index, next_mapping)
+ complete = next_states.get(len(line_text))
+ if complete is not None:
+ return _LineProjectionMatch(
+ start=projected_start,
+ end=projected_index + 1,
+ source_to_projected=complete,
+ )
+ if not next_states:
+ break
+ states = next_states
+ return None
+
+
+def _ranges_from_line_projection(
+ line: PDFTextStyleLine,
+ match: _LineProjectionMatch,
+) -> list[PDFTextStyleRange]:
+ """把物理行样式区间投影为公式字符被跳过后的 block 文本区间。"""
+
+ output: list[PDFTextStyleRange] = []
+ for style_range in line.style_ranges:
+ current_start: int | None = None
+ previous_index: int | None = None
+ for projected_index in match.source_to_projected[
+ style_range.start : style_range.end
+ ]:
+ if projected_index is None:
+ if current_start is not None and previous_index is not None:
+ output.append(
+ PDFTextStyleRange(
+ current_start,
+ previous_index + 1,
+ style_range.styles,
+ )
+ )
+ 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(
+ PDFTextStyleRange(
+ current_start,
+ previous_index + 1,
+ style_range.styles,
+ )
+ )
+ 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(
+ PDFTextStyleRange(
+ current_start,
+ previous_index + 1,
+ style_range.styles,
+ )
+ )
+ return output
def _match_style_ranges(
- projected_text: str,
+ projected: Sequence[_ProjectedChar],
lines: Sequence[PDFTextStyleLine],
) -> list[PDFTextStyleRange]:
- """按物理行顺序把删除线证据确定性对齐到 block 的可比较文本。"""
+ """按物理行顺序把字体与装饰线证据确定性对齐到 block 文本。"""
+ projected_text = "".join(token.value for token in projected)
output: list[PDFTextStyleRange] = []
cursor = 0
for line in lines:
@@ -585,12 +1099,23 @@ def _match_style_ranges(
PDFTextStyleRange(
line_start + style_range.start,
line_start + style_range.end,
+ style_range.styles,
)
- for style_range in line.strikethrough_ranges
+ for style_range in line.style_ranges
)
cursor = line_start + len(line.text)
continue
- for style_range in line.strikethrough_ranges:
+ formula_match = _match_line_across_formula_gaps(
+ line.text,
+ projected,
+ cursor,
+ )
+ if formula_match is not None:
+ output.extend(_ranges_from_line_projection(line, formula_match))
+ cursor = formula_match.end
+ continue
+ skipped_ranges: list[PDFTextStyleRange] = []
+ for style_range in line.style_ranges:
position = _resolve_fallback_occurrence(
projected_text,
line,
@@ -598,35 +1123,123 @@ def _match_style_ranges(
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}"
- )
+ skipped_ranges.append(style_range)
continue
output.append(
PDFTextStyleRange(
position,
position + style_range.end - style_range.start,
+ style_range.styles,
)
)
cursor = position + style_range.end - style_range.start
+ if skipped_ranges:
+ skipped_samples = [
+ (
+ line.text[style_range.start : style_range.end],
+ style_range.styles,
+ )
+ for style_range in skipped_ranges[:3]
+ ]
+ logger.debug(
+ "Skip ambiguous PDF text style mapping: "
+ f"line={line.text!r}, skipped={len(skipped_ranges)}, "
+ f"samples={skipped_samples!r}"
+ )
return _merge_style_ranges(output)
def _merge_style_ranges(ranges: Sequence[PDFTextStyleRange]) -> list[PDFTextStyleRange]:
- """合并可比较文本中重叠或直接相邻的样式区间。"""
+ """把重叠样式取并集,并合并相邻且样式集合相同的区间。"""
+ events: dict[int, dict[PDFTextStyle, int]] = {}
+ for style_range in ranges:
+ styles = _canonical_styles(style_range.styles)
+ if style_range.start >= style_range.end or not styles:
+ continue
+ for position, delta in (
+ (style_range.start, 1),
+ (style_range.end, -1),
+ ):
+ position_events = events.setdefault(position, {})
+ for style in styles:
+ position_events[style] = position_events.get(style, 0) + delta
+
+ active_counts: dict[PDFTextStyle, int] = {}
merged: list[PDFTextStyleRange] = []
- for style_range in sorted(ranges, key=lambda item: (item.start, item.end)):
- if style_range.start >= style_range.end:
+ previous_position: int | None = None
+ for position in sorted(events):
+ active_styles = _canonical_styles(
+ style
+ for style, count in active_counts.items()
+ if count > 0
+ )
+ if (
+ previous_position is not None
+ and previous_position < position
+ and active_styles
+ ):
+ if (
+ merged
+ and merged[-1].end == previous_position
+ and merged[-1].styles == active_styles
+ ):
+ merged[-1] = PDFTextStyleRange(
+ merged[-1].start,
+ position,
+ active_styles,
+ )
+ else:
+ merged.append(
+ PDFTextStyleRange(
+ previous_position,
+ position,
+ active_styles,
+ )
+ )
+ for style, delta in events[position].items():
+ active_counts[style] = active_counts.get(style, 0) + delta
+ previous_position = position
+ return merged
+
+
+def _append_raw_style_interval(
+ intervals: list[_RawStyleInterval],
+ start: int | None,
+ end: int,
+ styles: tuple[PDFTextStyle, ...],
+) -> None:
+ """向结果追加一个合法原字符串样式区间。"""
+
+ if start is not None and start < end and styles:
+ intervals.append(_RawStyleInterval(start, end, styles))
+
+
+def _merge_raw_style_intervals(
+ content: str,
+ intervals: Sequence[_RawStyleInterval],
+) -> list[_RawStyleInterval]:
+ """合并原字符串中相邻且样式一致、仅由普通空白隔开的区间。"""
+
+ merged: list[_RawStyleInterval] = []
+ for interval in sorted(intervals, key=lambda item: (item.start, item.end, item.styles)):
+ if interval.start >= interval.end or not interval.styles:
continue
- if merged and style_range.start <= merged[-1].end:
- merged[-1] = PDFTextStyleRange(
+ if (
+ merged
+ and merged[-1].styles == interval.styles
+ and (
+ interval.start <= merged[-1].end
+ or content[merged[-1].end : interval.start].isspace()
+ )
+ ):
+ merged[-1] = _RawStyleInterval(
merged[-1].start,
- max(merged[-1].end, style_range.end),
+ max(merged[-1].end, interval.end),
+ merged[-1].styles,
)
else:
- merged.append(style_range)
+ merged.append(interval)
return merged
@@ -634,84 +1247,111 @@ def _raw_style_intervals(
content: str,
projected: Sequence[_ProjectedChar],
ranges: Sequence[PDFTextStyleRange],
-) -> list[tuple[int, int]]:
- """把可比较文本区间转换为不跨公式或现有标签的原字符串区间。"""
+) -> list[_RawStyleInterval]:
+ """把样式区间转换为不跨公式或已有行内标签的原字符串区间。"""
- intervals: list[tuple[int, int]] = []
+ intervals: list[_RawStyleInterval] = []
for style_range in ranges:
current_start: int | None = None
current_end = 0
+ current_styles: tuple[PDFTextStyle, ...] = ()
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
+ missing_styles = _canonical_styles(
+ style
+ for style in style_range.styles
+ if style not in token.existing_styles
+ )
+ if not missing_styles:
+ _append_raw_style_interval(
+ intervals,
+ current_start,
+ current_end,
+ current_styles,
+ )
+ current_start = None
+ current_styles = ()
continue
if current_start is None:
current_start = token.raw_start
current_end = token.raw_end
+ current_styles = missing_styles
continue
gap = content[current_end : token.raw_start]
- if token.raw_start <= current_end or not gap or gap.isspace():
+ if (
+ missing_styles == current_styles
+ and (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))
+ _append_raw_style_interval(
+ intervals,
+ current_start,
+ current_end,
+ current_styles,
+ )
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
+ current_styles = missing_styles
+ _append_raw_style_interval(
+ intervals,
+ current_start,
+ current_end,
+ current_styles,
+ )
+ return _merge_raw_style_intervals(content, intervals)
-def _wrap_strikethrough_intervals(content: str, intervals: Sequence[tuple[int, int]]) -> str:
- """从右向左包装删除线区间,确保原 offset 在插入标签时保持有效。"""
+def _wrap_style_intervals(
+ content: str,
+ intervals: Sequence[_RawStyleInterval],
+) -> str:
+ """从右向左包装样式区间,确保插入标签时原 offset 保持有效。"""
output = content
- for start, end in reversed(intervals):
+ for interval in reversed(intervals):
+ style_attr = ",".join(interval.styles)
output = (
- f'{output[:start]}<text style="strikethrough">'
- f"{output[start:end]}</text>{output[end:]}"
+ f'{output[: interval.start]}<text style="{style_attr}">'
+ f"{output[interval.start : interval.end]}</text>"
+ f"{output[interval.end :]}"
)
return output
-def apply_pdf_strikethrough_styles(
+def apply_pdf_text_styles(
blocks: list[dict[str, Any]],
lines: Sequence[PDFTextStyleLine],
page_size: tuple[float, float],
) -> None:
- """把页面删除线证据写入自然语言 block content,无法唯一对齐时保持原文。"""
+ """把页面字体和装饰线证据写入自然语言 block,歧义时保持原文。"""
assignments = _assign_lines_to_blocks(blocks, lines, page_size)
for block_index, block_lines in assignments.items():
block = blocks[block_index]
+ block_lines = _filter_line_styles_for_block(
+ block_lines,
+ block.get("type"),
+ )
content = block.get("content")
if not isinstance(content, str) or not content or not any(
- line.strikethrough_ranges for line in block_lines
+ line.style_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)
+ style_ranges = _match_style_ranges(projected, block_lines)
if not style_ranges:
continue
intervals = _raw_style_intervals(content, projected, style_ranges)
if intervals:
- block["content"] = _wrap_strikethrough_intervals(content, intervals)
+ block["content"] = _wrap_style_intervals(content, intervals)
__all__ = [
+ "PDF_FONT_FORCE_BOLD_FLAG",
+ "PDF_FONT_ITALIC_FLAG",
+ "PDFTextStyle",
"PDFTextStyleLine",
"PDFTextStyleRange",
- "apply_pdf_strikethrough_styles",
- "detect_pdf_strikethrough_lines",
+ "apply_pdf_text_styles",
+ "detect_pdf_text_style_lines",
]
diff --git a/tests/unittest/test_content_list_render.py b/tests/unittest/test_content_list_render.py
index 930a81f6..965459ab 100644
--- a/tests/unittest/test_content_list_render.py
+++ b/tests/unittest/test_content_list_render.py
@@ -8,6 +8,7 @@ import pytest
from mineru.config import Config
from mineru.render import render_content_list, render_markdown
from mineru.types import (
+ ChartAnnotationBlock,
ChartBlock,
ChartBodyBlock,
CodeBlock,
@@ -136,9 +137,19 @@ def test_content_list_flattens_recursive_list_index_and_code_metadata() -> None:
"sub_type": "code",
"guess_lang": "python",
"content": [
- {"type": "code_caption", "index": 4, "content": '<text style="bold">Example</text>'},
+ {
+ "type": "code_caption",
+ "index": 4,
+ "bbox": [0.1, 0.1, 0.5, 0.2],
+ "content": '<text style="bold">Example</text>',
+ },
{"type": "code_body", "index": 2, "content": "print('x')\n```"},
- {"type": "code_footnote", "index": 5, "content": "note <eq>x</eq>"},
+ {
+ "type": "code_footnote",
+ "index": 5,
+ "bbox": [0.1, 0.8, 0.5, 0.9],
+ "content": "note <eq>x</eq>",
+ },
],
}
)
@@ -148,8 +159,8 @@ def test_content_list_flattens_recursive_list_index_and_code_metadata() -> None:
assert blocks[0]["content"] == "- outer\n - inner"
assert blocks[1]["content"] == "- [Section](#section-b)"
assert blocks[2]["content"] == "````python\nprint('x')\n```\n````"
- assert blocks[2]["captions"] == ["**Example**"]
- assert blocks[2]["footnotes"] == ["note $x$"]
+ assert blocks[2]["captions"] == [{"bbox": [0.1, 0.1, 0.5, 0.2], "content": "**Example**"}]
+ assert blocks[2]["footnotes"] == [{"bbox": [0.1, 0.8, 0.5, 0.9], "content": "note $x$"}]
assert "guess_lang" not in blocks[2]
_assert_output_field_contract(blocks)
@@ -170,13 +181,24 @@ def test_content_list_sorts_visual_annotations_and_selects_image_source() -> Non
"image_path": "images/a b.png",
"image_base64": "data:image/png;base64,AAAA",
},
- {"type": "image_caption", "index": 5, "content": ""},
+ {
+ "type": "image_caption",
+ "index": 5,
+ "bbox": [0.1, 0.5, 0.4, 0.6],
+ "content": "",
+ },
{
"type": "image_caption",
"index": 3,
+ "bbox": [0.1, 0.2, 0.4, 0.3],
"content": '<text style="bold">early</text>',
},
- {"type": "image_footnote", "index": 4, "content": "after"},
+ {
+ "type": "image_footnote",
+ "index": 4,
+ "bbox": [0.1, 0.7, 0.4, 0.8],
+ "content": "after",
+ },
],
}
)
@@ -188,8 +210,12 @@ def test_content_list_sorts_visual_annotations_and_selects_image_source() -> Non
assert result["content"] == "description"
assert result["image_source"] == "https://cdn.example/doc/images/a%20b.png"
- assert result["captions"] == ["**early**", "", "missing index"]
- assert result["footnotes"] == ["after"]
+ assert result["captions"] == [
+ {"bbox": [0.1, 0.2, 0.4, 0.3], "content": "**early**"},
+ {"bbox": [0.1, 0.5, 0.4, 0.6], "content": ""},
+ {"content": "missing index"},
+ ]
+ assert result["footnotes"] == [{"bbox": [0.1, 0.7, 0.4, 0.8], "content": "after"}]
assert "![](" not in result["content"]
assert "<details>" not in result["content"]
assert "data:image" not in json.dumps(result)
@@ -222,8 +248,18 @@ def test_content_list_keeps_table_image_source_and_cross_page_metadata() -> None
"index": 0,
"content": "<table><tr><th>A</th></tr><tr><td>2</td></tr></table>",
},
- {"type": "table_caption", "index": 2, "content": "Table 2"},
- {"type": "table_footnote", "index": 3, "content": "note"},
+ {
+ "type": "table_caption",
+ "index": 2,
+ "bbox": [0.1, 0.1, 0.9, 0.2],
+ "content": "Table 2",
+ },
+ {
+ "type": "table_footnote",
+ "index": 3,
+ "bbox": [0.1, 0.8, 0.9, 0.9],
+ "content": "note",
+ },
],
}
)
@@ -252,8 +288,8 @@ def test_content_list_keeps_table_image_source_and_cross_page_metadata() -> None
assert second_output["content"] == "| A |\n| --- |\n| 2 |"
assert second_output["continues_prev"] is True
assert second_output["cell_merge"] == [1]
- assert second_output["captions"] == ["Table 2"]
- assert second_output["footnotes"] == ["note"]
+ assert second_output["captions"] == [{"bbox": [0.1, 0.1, 0.9, 0.2], "content": "Table 2"}]
+ assert second_output["footnotes"] == [{"bbox": [0.1, 0.8, 0.9, 0.9], "content": "note"}]
assert image_only_output["content"] == ""
assert image_only_output["image_source"] == "images/image-only-table.png"
@@ -273,12 +309,21 @@ def test_content_list_keeps_chart_content_separate_from_base64_source(monkeypatc
type="chart",
index=0,
content=[
+ ChartAnnotationBlock(
+ type="chart_caption",
+ bbox=(0.1, 0.1, 0.9, 0.2),
+ content='<text style="bold">Chart</text>',
+ ),
ChartBodyBlock(
type="chart_body",
index=0,
content="<table><tr><th>A</th></tr><tr><td><eq>x</eq></td></tr></table>",
image_base64="data:image/png;base64,AAAA",
- )
+ ),
+ ChartAnnotationBlock(
+ type="chart_footnote",
+ content="source",
+ ),
],
)
@@ -286,6 +331,8 @@ def test_content_list_keeps_chart_content_separate_from_base64_source(monkeypatc
assert output["image_source"] == "data:image/png;base64,AAAA"
assert output["content"] == "| A |\n| --- |\n| \\(x\\) |"
+ assert output["captions"] == [{"bbox": [0.1, 0.1, 0.9, 0.2], "content": "**Chart**"}]
+ assert output["footnotes"] == [{"content": "source"}]
assert json.dumps(output).count("data:image/png;base64,AAAA") == 1
assert "![](" not in output["content"]
assert "<details>" not in output["content"]
diff --git a/tests/unittest/test_flash_pdf_code_blocks.py b/tests/unittest/test_flash_pdf_code_blocks.py
index 97961db8..10dc052f 100644
--- a/tests/unittest/test_flash_pdf_code_blocks.py
+++ b/tests/unittest/test_flash_pdf_code_blocks.py
@@ -7,8 +7,12 @@ import pytest
from mineru.model.flash import PdfModel
from mineru.model.flash.native_pdf import code_blocks, models, pipeline
-from mineru.utils.spatial_text import project_pdf_spatial_text
+from mineru.render._internal.common.inline import (
+ inline_plain_text,
+ parse_inline_content,
+)
from mineru.utils.pdf_document import PDFDocument, PDFPathInfo
+from mineru.utils.spatial_text import project_pdf_spatial_text
from _flash_pdf_test_utils import _text_line
@@ -311,7 +315,15 @@ def test_kvcache_algorithm_pdf_materializes_caption_and_code() -> None:
page = PdfModel().predict(pdf_doc)[0]
caption_text = "Algorithm 1 KVCache-centric Scheduling Algorithm"
- captions = [block for block in page if block["type"] == "caption" and block.get("content") == caption_text]
+ captions = [
+ block
+ for block in page
+ if block["type"] == "caption"
+ and inline_plain_text(
+ parse_inline_content(str(block.get("content") or ""))
+ )
+ == caption_text
+ ]
code = [block for block in page if block["type"] == "code"]
assert len(captions) == 1
@@ -319,7 +331,15 @@ def test_kvcache_algorithm_pdf_materializes_caption_and_code() -> None:
assert len(code) == 1
assert code[0]["bbox"] == [0.176, 0.108, 0.824, 0.539]
assert page.index(captions[0]) + 1 == page.index(code[0])
- assert not [block for block in page if block["type"] == "header" and block.get("content") == caption_text]
+ assert not [
+ block
+ for block in page
+ if block["type"] == "header"
+ and inline_plain_text(
+ parse_inline_content(str(block.get("content") or ""))
+ )
+ == caption_text
+ ]
code_content = str(code[0]["content"])
probes = (
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index 31d30a2d..daafa77d 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -19,6 +19,12 @@ from mineru.model.flash.native_pdf import (
native_text,
tables,
)
+from mineru.render import render_markdown
+from mineru.render._internal.common.inline import (
+ inline_plain_text,
+ parse_inline_content,
+)
+from mineru.types import MiddleJson
from mineru.utils.pdf_document import PDFDocument, get_lines_from_chars
@@ -129,9 +135,17 @@ def _grouped_visual_blocks(
return [block for block in process_page_blocks(deepcopy(page_blocks), use_bbox=True) if block.get("type") == block_type]
+def _visible_content(value: Any) -> str:
+ """返回 model block 或 content 字符串去除行内样式协议后的可见文本。"""
+
+ content = value.get("content") if isinstance(value, dict) else value
+ return inline_plain_text(parse_inline_content(str(content or "")))
+
+
def _normalized_content_probe(text: str) -> str:
"""还原 LaTeX tag 并去除排版差异,生成原生行内容覆盖检查使用的探针。"""
+ text = _visible_content(text)
text = re.sub(r"\\tag\{([^{}]+)\}", r"\1", text)
return "".join(char.casefold() for char in text if char.isalnum())
@@ -357,7 +371,7 @@ def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> Non
assert sum(block["type"] == "footnote" for page in model_list for block in page) == 2
page2 = model_list[1]
- page2_contents = [block["content"] for block in page2]
+ page2_contents = [_visible_content(block) for block in page2]
humans = next(content for content in page2_contents if content.startswith("Humans group shapes"))
matching = next(content for content in page2_contents if content.startswith("To identify a match"))
dissimilarity = next(content for content in page2_contents if content.startswith("where the pixel dissimilarity"))
@@ -369,8 +383,12 @@ def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> Non
assert "green, and blue" not in formula3
page3 = model_list[2]
- page3_contents = [block["content"] for block in page3]
- assert next(block for block in page3 if block["content"] == "B. Temporal cost aggregation")["type"] == "paragraph_title"
+ page3_contents = [_visible_content(block) for block in page3]
+ assert next(
+ block
+ for block in page3
+ if _visible_content(block) == "B. Temporal cost aggregation"
+ )["type"] == "paragraph_title"
assert page3_contents[12] == "D. Iterative Disparity Refinement"
assert all(block["bbox"][2] <= 0.5 for block in page3[:12])
assert "O(ω2) to O(ω)" in page3_contents[0]
@@ -391,7 +409,7 @@ def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> Non
assert "available at http://mc2.unl.edu/current-research/image-processing/. Figure 2" in page3_contents[-1]
assert "current-research /image-processing" not in page3_contents[-1]
- page4_contents = [block["content"] for block in model_list[3]]
+ page4_contents = [_visible_content(block) for block in model_list[3]]
figure2 = next(content for content in page4_contents if content.startswith("Figure 2:"))
figure3 = next(content for content in page4_contents if content.startswith("Figure 3:"))
results = next(content for content in page4_contents if content.startswith("The results of temporal stereo"))
@@ -402,16 +420,18 @@ def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> Non
assert improvements.endswith("has the effect")
page5 = model_list[4]
- page5_contents = [block["content"] for block in page5]
+ page5_contents = [_visible_content(block) for block in page5]
optimal_feedback = next(content for content in page5_contents if content.startswith("The optimal value"))
page5_references = [content for content in page5_contents if content.startswith("[")]
- references_title = next(block for block in page5 if block["content"] == "REFERENCES")
+ references_title = next(
+ block for block in page5 if _visible_content(block) == "REFERENCES"
+ )
assert "noise ranging between ±0 to ±40" in optimal_feedback
assert optimal_feedback.endswith("temporal stereo matching is used.")
assert references_title["type"] == "paragraph_title"
assert [content.partition("]")[0] + "]" for content in page5_references] == [f"[{number}]" for number in range(1, 6)]
- page6_contents = [block["content"] for block in model_list[5]]
+ page6_contents = [_visible_content(block) for block in model_list[5]]
assert len(page6_contents) == 16
assert [content.partition("]")[0] + "]" for content in page6_contents] == [f"[{number}]" for number in range(6, 22)]
@@ -467,7 +487,11 @@ def test_demo2_page4_groups_five_graphics_and_keeps_table1() -> None:
assert len({id(block) for block in graphic_blocks}) == 5
assert "Frame 90" in graphic_blocks[0]["content"]
assert all("Figure" not in block["content"] for block in graphic_blocks)
- body_tail_block = next(block for block in page if block["content"].startswith("of the synthetic stereo scene"))
+ body_tail_block = next(
+ block
+ for block in page
+ if _visible_content(block).startswith("of the synthetic stereo scene")
+ )
assert body_tail_block["type"] == "text"
assert body_tail_block["content"].endswith("discontinuity map.")
assert "discontinuity map." not in graphic_blocks[0]["content"]
@@ -490,16 +514,21 @@ def test_demo2_table_captions_and_numeric_footnotes_are_independent_blocks() ->
"1 Millions of Disparity Estimates per Second",
)[0]
residual_text = "\n".join(
- block["content"] for page_idx in (3, 4) for block in model_list[page_idx] if block["type"] == "text"
+ _visible_content(block)
+ for page_idx in (3, 4)
+ for block in model_list[page_idx]
+ if block["type"] == "text"
)
assert page4_caption["type"] == page5_caption["type"] == "caption"
assert page4_footnote["type"] == page5_footnote["type"] == "footnote"
- assert "ral stereo matching." in page4_caption["content"]
- assert "0.01, respectively." in page4_footnote["content"]
+ assert "ral stereo matching." in _visible_content(page4_caption)
+ assert "0.01, respectively." in _visible_content(page4_footnote)
assert "Noise: ±20" not in page4_table["content"]
- assert "2 Assumes 320 × 240 images with 32 disparity levels." in page5_footnote["content"]
- assert "the avgerage % of bad pixels." in page5_footnote["content"]
+ assert "2 Assumes 320 × 240 images with 32 disparity levels." in _visible_content(
+ page5_footnote
+ )
+ assert "the avgerage % of bad pixels." in _visible_content(page5_footnote)
assert "Table I:" not in page4_table["content"]
assert "To enable propagation" not in page4_table["content"]
assert "Table II:" not in page5_table["content"]
@@ -590,12 +619,28 @@ def test_demo3_keeps_tables_and_covers_every_native_source_line() -> None:
assert sum(block["type"] == "caption" for page in model_list for block in page) == 8
page7_tables = [block for block in model_list[6] if block["type"] == "table"]
page7_table4 = next(block for block in page7_tables if "Number of parameters" in block["content"])
- page7_table4_caption = next(block for block in model_list[6] if block["content"] == "Table 4: Model size comparison.")
+ page7_table4_caption = next(
+ block
+ for block in model_list[6]
+ if _visible_content(block) == "Table 4: Model size comparison."
+ )
page7_inline_body = next(
- block for block in model_list[6] if block["content"].startswith("Row, Column, & Global Positional IDs.")
+ block
+ for block in model_list[6]
+ if _visible_content(block).startswith(
+ "Row, Column, & Global Positional IDs."
+ )
+ )
+ page9_conclusion = next(
+ block
+ for block in model_list[8]
+ if _visible_content(block).startswith("In this paper, we identified")
+ )
+ page10_first_reference = next(
+ block
+ for block in model_list[9]
+ if _visible_content(block).startswith("Xiang Deng, Huan Sun")
)
- page9_conclusion = next(block for block in model_list[8] if block["content"].startswith("In this paper, we identified"))
- page10_first_reference = next(block for block in model_list[9] if block["content"].startswith("Xiang Deng, Huan Sun"))
assert all(
marker in page7_table4["content"]
for marker in (
@@ -662,7 +707,11 @@ def test_demo3_pages1_and2_fix_title_front_matter_and_embedding_formula() -> Non
"""验证首页标题稳定,第二页标题、公式和栏尾正文各自保持完整。"""
page1, page2 = _native_model_list("demo3.pdf")[:2]
- title = next(block for block in page1 if block["content"].startswith("TABLEFORMER:"))
+ title = next(
+ block
+ for block in page1
+ if _visible_content(block).startswith("TABLEFORMER:")
+ )
front_matter_contents = {
"Aditya Gupta† Rahul Goel†",
"Jingfeng Yang∗ Luheng He†",
@@ -672,34 +721,62 @@ def test_demo3_pages1_and2_fix_title_front_matter_and_embedding_formula() -> Non
}
- front_matter = [block for block in page1 if block["content"] in front_matter_contents]
- released_code = next(block for block in page1 if "TABLEFORMER.md" in block["content"])
+ front_matter = [
+ block for block in page1 if _visible_content(block) in front_matter_contents
+ ]
+ released_code = next(
+ block for block in page1 if "TABLEFORMER.md" in _visible_content(block)
+ )
aside = next(block for block in page1 if block["type"] == "aside_text")
- introduction = next(block for block in page1 if block["content"].startswith("Recently, semi-structured"))
- nutshell = next(block for block in page1 if block["content"].startswith("In a nutshell"))
- figure_caption = next(block for block in page1 if block["content"].startswith("Figure 1:"))
- tables_body = next(block for block in page1 if block["content"].startswith("tables or rows"))
+ introduction = next(
+ block
+ for block in page1
+ if _visible_content(block).startswith("Recently, semi-structured")
+ )
+ nutshell = next(
+ block
+ for block in page1
+ if _visible_content(block).startswith("In a nutshell")
+ )
+ figure_caption = next(
+ block
+ for block in page1
+ if _visible_content(block).startswith("Figure 1:")
+ )
+ tables_body = next(
+ block
+ for block in page1
+ if _visible_content(block).startswith("tables or rows")
+ )
assert title["type"] == "doc_title"
assert len(front_matter) == len(front_matter_contents)
assert all(block["type"] == "text" for block in front_matter)
- assert not [block for block in page1 if block["content"] == "∗"]
- assert next(block for block in page1 if block["content"] == "Abstract")["type"] == "paragraph_title"
+ assert not [block for block in page1 if _visible_content(block) == "∗"]
+ assert next(
+ block for block in page1 if _visible_content(block) == "Abstract"
+ )["type"] == "paragraph_title"
assert released_code["type"] == "page_footnote"
assert aside["angle"] == 270
assert aside["bbox"][2] <= 0.12
- assert introduction["content"].endswith("(Eisenschlos et al., 2021; Liu et al., 2021).")
+ assert _visible_content(introduction).endswith(
+ "(Eisenschlos et al., 2021; Liu et al., 2021)."
+ )
assert nutshell["type"] == "text"
- assert nutshell["content"].endswith("by serializing")
+ assert _visible_content(nutshell).endswith("by serializing")
assert figure_caption["type"] == "text"
- assert figure_caption["content"].endswith("both questions.")
- assert "tables or rows" not in figure_caption["content"]
+ assert _visible_content(figure_caption).endswith("both questions.")
+ assert "tables or rows" not in _visible_content(figure_caption)
assert tables_body["type"] == "text"
- section_title = next(block for block in page2 if block["content"].startswith("2 Preliminaries:"))
+ section_title = next(
+ block
+ for block in page2
+ if _visible_content(block).startswith("2 Preliminaries:")
+ )
equations = [block for block in page2 if block["type"] == "equation"]
assert section_title["type"] == "paragraph_title"
- assert section_title["content"] == "2 Preliminaries: TAPAS for Table Encoding"
+ assert _visible_content(section_title) == "2 Preliminaries: TAPAS for Table Encoding"
assert len(equations) == 1
assert equations[0]["content"].splitlines() == [
"token ids (W) = {wv1, wv2, · · · , wvn }",
@@ -718,9 +795,9 @@ def test_demo3_pages1_and2_fix_title_front_matter_and_embedding_formula() -> Non
]
assert len(as_model_blocks) == 1
assert as_model_blocks[0]["type"] == "text"
- assert as_model_blocks[0]["content"].startswith("As for the model")
- assert "attends to all the tokens." in as_model_blocks[0]["content"]
- assert "Let the layer input" in as_model_blocks[0]["content"]
+ assert _visible_content(as_model_blocks[0]).startswith("As for the model")
+ assert "attends to all the tokens." in _visible_content(as_model_blocks[0])
+ assert "Let the layer input" in _visible_content(as_model_blocks[0])
def test_demo3_pages6_7_and10_fix_caption_inline_titles_and_reference_tail() -> None:
@@ -731,37 +808,81 @@ def test_demo3_pages6_7_and10_fix_caption_inline_titles_and_reference_tail() ->
page7 = model_list[6]
page10 = model_list[9]
- table2_caption = next(block for block in page6 if block["content"].startswith("Table 2:"))
+ table2_caption = next(
+ block for block in page6 if _visible_content(block).startswith("Table 2:")
+ )
assert table2_caption["type"] == "caption"
- assert "Median of 5 independent runs are reported." in table2_caption["content"]
- assert table2_caption["content"].endswith("not reported in the original paper.")
- assert sum("not reported in the original paper." in block["content"] for block in page6) == 1
+ assert "Median of 5 independent runs are reported." in _visible_content(
+ table2_caption
+ )
+ assert _visible_content(table2_caption).endswith(
+ "not reported in the original paper."
+ )
+ assert sum(
+ "not reported in the original paper." in _visible_content(block)
+ for block in page6
+ ) == 1
- attention_bias = next(block for block in page7 if block["content"].startswith("Attention Bias Scaling."))
- positional_ids = next(block for block in page7 if block["content"].startswith("Row, Column, & Global Positional IDs."))
+ attention_bias = next(
+ block
+ for block in page7
+ if _visible_content(block).startswith("Attention Bias Scaling.")
+ )
+ positional_ids = next(
+ block
+ for block in page7
+ if _visible_content(block).startswith(
+ "Row, Column, & Global Positional IDs."
+ )
+ )
formula6 = next(
block
for block in page7
if block["type"] == "equation" and r"\tag{6}" in block["content"]
)
assert attention_bias["type"] == "text"
- assert attention_bias["content"].endswith("attention score by:")
+ assert str(attention_bias["content"]).startswith(
+ '<text style="bold">Attention Bias Scaling.</text> Unlike'
+ )
+ assert _visible_content(attention_bias).endswith("attention score by:")
assert positional_ids["type"] == "text"
- assert "With TAPASBASE" in positional_ids["content"]
+ assert "With TAPASBASE" in _visible_content(positional_ids)
assert formula6["content"].endswith(r"\tag{6}")
assert not [
block
for block in page7
if block["type"] == "paragraph_title"
- and block["content"].startswith(("Attention Bias Scaling.", "Row, Column, & Global Positional IDs."))
+ and _visible_content(block).startswith(
+ ("Attention Bias Scaling.", "Row, Column, & Global Positional IDs.")
+ )
]
+ page7_markdown = render_markdown(
+ MiddleJson(
+ pages=model_list_to_pages([page7], page_index_map=[6]),
+ file_suffix="pdf",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+ )
+ assert "**Attention Bias Scaling.** Unlike" in page7_markdown
- ying_reference = next(block for block in page10 if block["content"].startswith("Chengxuan Ying"))
- yu_reference = next(block for block in page10 if block["content"].startswith("Tao Yu"))
+ ying_reference = next(
+ block
+ for block in page10
+ if _visible_content(block).startswith("Chengxuan Ying")
+ )
+ yu_reference = next(
+ block
+ for block in page10
+ if _visible_content(block).startswith("Tao Yu")
+ )
assert ying_reference["type"] == yu_reference["type"] == "text"
- assert ying_reference["content"].endswith("arXiv:2106.05234.")
- assert "Tao Yu" not in ying_reference["content"]
- assert not [block for block in page10 if block["content"] == "arXiv:2106.05234."]
+ assert _visible_content(ying_reference).endswith("arXiv:2106.05234.")
+ assert "Tao Yu" not in _visible_content(ying_reference)
+ assert not [
+ block for block in page10 if _visible_content(block) == "arXiv:2106.05234."
+ ]
def test_demo3_page3_form_image_formulas_titles_and_inline_body_are_whole() -> None:
@@ -787,23 +908,46 @@ def test_demo3_page3_form_image_formulas_titles_and_inline_body_are_whole() -> N
for block in page
)
caption_blocks = [
- block for block in page if "Figure 2:" in block["content"] or "types of task independent biases" in block["content"]
+ block
+ for block in page
+ if "Figure 2:" in _visible_content(block)
+ or "types of task independent biases" in _visible_content(block)
]
assert len(caption_blocks) == 1
assert caption_blocks[0]["type"] == "caption"
- assert "This example corresponds to table (a)" in caption_blocks[0]["content"]
- assert "associated text." in caption_blocks[0]["content"]
+ assert "This example corresponds to table (a)" in _visible_content(
+ caption_blocks[0]
+ )
+ assert "associated text." in _visible_content(caption_blocks[0])
formula1 = next(block for block in page if r"\tag{1}" in block["content"])
- section3 = next(block for block in page if block["content"].startswith("3 TABLEFORMER:"))
- inline_item = next(block for block in page if block["content"].startswith("2) Per cell positional ids."))
- inline_heading = next(block for block in page if block["content"].startswith("Positional Encoding in TABLEFORMER."))
+ section3 = next(
+ block
+ for block in page
+ if _visible_content(block).startswith("3 TABLEFORMER:")
+ )
+ inline_item = next(
+ block
+ for block in page
+ if _visible_content(block).startswith("2) Per cell positional ids.")
+ )
+ inline_heading = next(
+ block
+ for block in page
+ if _visible_content(block).startswith(
+ "Positional Encoding in TABLEFORMER."
+ )
+ )
assert formula1["type"] == "equation"
assert "Q = HWQ" in formula1["content"] and "K = HWK" in formula1["content"]
assert section3["type"] == "paragraph_title"
- assert section3["content"] == "3 TABLEFORMER: Robust Structural Table Encoding"
- assert inline_item["type"] == "text" and "To further remove any" in inline_item["content"]
- assert inline_heading["type"] == "text" and "Transformer model" in inline_heading["content"]
+ assert _visible_content(section3) == "3 TABLEFORMER: Robust Structural Table Encoding"
+ assert inline_item["type"] == "text" and "To further remove any" in _visible_content(
+ inline_item
+ )
+ assert inline_heading["type"] == "text" and "Transformer model" in _visible_content(
+ inline_heading
+ )
def test_demo3_pages4_and5_fix_lists_formula_titles_italics_and_footnotes() -> None:
@@ -811,13 +955,21 @@ def test_demo3_pages4_and5_fix_lists_formula_titles_italics_and_footnotes() -> N
page4, page5 = _native_model_list("demo3.pdf")[3:5]
left_bullets = [
- block for block in page4 if block["type"] == "text" and block["content"].startswith("•") and block["bbox"][2] <= 0.5
+ block
+ for block in page4
+ if block["type"] == "text"
+ and _visible_content(block).startswith("•")
+ and block["bbox"][2] <= 0.5
]
assert len(left_bullets) == 6
- assert all(len(block["content"].split()) > 8 for block in left_bullets)
- attention_biases = next(block for block in page4 if block["content"].startswith("Attention Biases in TABLEFORMER."))
+ assert all(len(_visible_content(block).split()) > 8 for block in left_bullets)
+ attention_biases = next(
+ block
+ for block in page4
+ if _visible_content(block).startswith("Attention Biases in TABLEFORMER.")
+ )
assert attention_biases["type"] == "text"
- assert "13 bias types" in attention_biases["content"]
+ assert "13 bias types" in _visible_content(attention_biases)
formula3 = next(block for block in page4 if r"\tag{3}" in block["content"])
formula4 = next(block for block in page4 if r"\tag{4}" in block["content"])
@@ -829,38 +981,69 @@ def test_demo3_pages4_and5_fix_lists_formula_titles_italics_and_footnotes() -> N
relation_blocks = [
block
for block in page4
- if "Relation between TABLEFORMER and ETC." in block["content"] or "ETC (Ainslie et al., 2020)" in block["content"]
+ if "Relation between TABLEFORMER and ETC." in _visible_content(block)
+ or "ETC (Ainslie et al., 2020)" in _visible_content(block)
]
assert len(relation_blocks) == 1
assert relation_blocks[0]["type"] == "text"
- assert relation_blocks[0]["content"].startswith("Relation between TABLEFORMER and ETC.")
- assert "uses vectors to represent relative position labels" in relation_blocks[0]["content"]
+ assert _visible_content(relation_blocks[0]).startswith(
+ "Relation between TABLEFORMER and ETC."
+ )
+ assert "uses vectors to represent relative position labels" in _visible_content(
+ relation_blocks[0]
+ )
- title4 = next(block for block in page4 if block["content"] == "4 Experimental Setup")
- title41 = next(block for block in page4 if block["content"] == "4.1 Datasets and Evaluation")
+ title4 = next(
+ block for block in page4 if _visible_content(block) == "4 Experimental Setup"
+ )
+ title41 = next(
+ block
+ for block in page4
+ if _visible_content(block) == "4.1 Datasets and Evaluation"
+ )
assert title4["type"] == title41["type"] == "paragraph_title"
for prefix, continuation in (
("Table Question Answering.", "conducted experiments"),
("Table-Text Entailment.", "TABFACT dataset"),
):
- inline_block = next(block for block in page4 if block["content"].startswith(prefix))
+ inline_block = next(
+ block for block in page4 if _visible_content(block).startswith(prefix)
+ )
assert inline_block["type"] == "text"
- assert continuation in inline_block["content"]
+ assert continuation in _visible_content(inline_block)
- assert next(block for block in page5 if block["content"] == "4.2 Baselines")["type"] == "paragraph_title"
+ assert next(
+ block for block in page5 if _visible_content(block) == "4.2 Baselines"
+ )["type"] == "paragraph_title"
assert (
- next(block for block in page5 if block["content"] == "4.3 Perturbing Tables as Augmented Data")["type"]
+ next(
+ block
+ for block in page5
+ if _visible_content(block) == "4.3 Perturbing Tables as Augmented Data"
+ )["type"]
== "paragraph_title"
)
- italic_body = next(block for block in page5 if block["content"].startswith("Could we alleviate"))
+ italic_body = next(
+ block
+ for block in page5
+ if _visible_content(block).startswith("Could we alleviate")
+ )
assert italic_body["type"] == "text"
- assert italic_body["content"].endswith("without making any")
+ assert _visible_content(italic_body).endswith("without making any")
- final_bullet = next(block for block in page5 if block["content"].startswith("• How does TABLEFORMER compare"))
- final_footnote = next(block for block in page5 if block["content"].startswith("3By perturbation"))
+ final_bullet = next(
+ block
+ for block in page5
+ if _visible_content(block).startswith("• How does TABLEFORMER compare")
+ )
+ final_footnote = next(
+ block
+ for block in page5
+ if _visible_content(block).startswith("3By perturbation")
+ )
assert final_bullet["type"] == "text"
assert final_footnote["type"] == "page_footnote"
- assert "3By perturbation" not in final_bullet["content"]
+ assert "3By perturbation" not in _visible_content(final_bullet)
def test_demo4_nct00083083_targeted_flash_regressions() -> None:
@@ -873,9 +1056,11 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:
page1 = model_list[0]
assert any(block["type"] == "header" and "07388-8" in str(block["content"]) for block in page1)
- assert next(block for block in page1 if block["content"] == "ORIGINAL ARTICLE")["type"] == "text"
+ assert next(
+ block for block in page1 if _visible_content(block) == "ORIGINAL ARTICLE"
+ )["type"] == "text"
author_line = _blocks_containing(page1, "Rucha Ronghe1")[0]
- assert author_line["content"] == (
+ assert _visible_content(author_line) == (
"Rucha Ronghe1 · Teresa Crespo Gonzalez2 · Catriona Wimberley3,4,5 · Karla Suchacki3,6 · Adriana A. S. Tavares3,4"
)
assert _blocks_containing(page1, "contributed equally")[0]["type"] == "page_footnote"
@@ -1227,7 +1412,11 @@ def test_demo6_default3_targeted_title_regressions() -> None:
"八、监督部门",
"九、联系方式",
}
- assert {block["content"] for block in blocks if block["type"] == "paragraph_title"} == expected_titles
+ assert {
+ _visible_content(block)
+ for block in blocks
+ if block["type"] == "paragraph_title"
+ } == expected_titles
for probe in (
"招标编号",
@@ -1353,8 +1542,8 @@ def test_caibao_table_reclaims_repeated_dates_but_keeps_real_marginals() -> None
page_numbers = [block for block in page if block["type"] == "page_number"]
assert len(tables_on_page) == len(footers) == len(page_numbers) == 1
assert "2024 年 07 月" in str(tables_on_page[0]["content"])
- assert footers[0]["content"] == "免责声明和披露以及分析师声明是报告的一部分,请务必一起阅读。"
- assert "2024 年" not in str(footers[0]["content"])
+ assert _visible_content(footers[0]) == "免责声明和披露以及分析师声明是报告的一部分,请务必一起阅读。"
+ assert "2024 年" not in _visible_content(footers[0])
assert tables_on_page[0]["bbox"][3] < footers[0]["bbox"][1]
assert tables_on_page[0]["bbox"][3] < page_numbers[0]["bbox"][1]
assert not [block for block in page if block["type"] == "footnote"]
@@ -1369,16 +1558,26 @@ def test_caibao_page2_parallel_chart_captions_stay_separate() -> None:
model_list = _txt_model_list("caibao1.pdf")
page = model_list[1]
- first_caption = [block for block in page if block["type"] == "caption" and str(block["content"]).startswith("图表1")]
- second_caption = [block for block in page if block["type"] == "caption" and str(block["content"]).startswith("图表2")]
+ first_caption = [
+ block
+ for block in page
+ if block["type"] == "caption"
+ and _visible_content(block).startswith("图表1")
+ ]
+ second_caption = [
+ block
+ for block in page
+ if block["type"] == "caption"
+ and _visible_content(block).startswith("图表2")
+ ]
assert len(page) == 20
assert len(first_caption) == len(second_caption) == 1
assert first_caption[0]["type"] == second_caption[0]["type"] == "caption"
assert first_caption[0]["bbox"] == [0.073, 0.235, 0.485, 0.245]
assert second_caption[0]["bbox"] == [0.513, 0.235, 0.843, 0.245]
- assert "行业周涨幅" not in str(first_caption[0]["content"])
- assert "汽车指数上周下跌" not in str(second_caption[0]["content"])
+ assert "行业周涨幅" not in _visible_content(first_caption[0])
+ assert "汽车指数上周下跌" not in _visible_content(second_caption[0])
assert [block["bbox"] for block in page if block["type"] == "image" and block["bbox"][1] < 0.5] == [
[0.082, 0.267, 0.48, 0.447],
[0.522, 0.254, 0.92, 0.46],
@@ -1398,7 +1597,10 @@ def test_caibao_page2_parallel_chart_captions_stay_separate() -> None:
assert first_index + 3 == second_index
page3_captions = [
- block for block in model_list[2] if block["type"] == "caption" and str(block["content"]).startswith(("图表4", "图表5"))
+ block
+ for block in model_list[2]
+ if block["type"] == "caption"
+ and _visible_content(block).startswith(("图表4", "图表5"))
]
assert [block["bbox"] for block in page3_captions] == [
[0.073, 0.181, 0.298, 0.191],
@@ -1425,9 +1627,9 @@ def test_caibao_page2_parallel_chart_captions_stay_separate() -> None:
assert len(page7_table_note) == 1
assert page7_table_note[0]["type"] == "footnote"
assert page7_table_note[0]["bbox"] == [0.073, 0.483, 0.219, 0.504]
- assert "资料来源:Wind、华泰研究" in str(page7_table_note[0]["content"])
+ assert "资料来源:Wind、华泰研究" in _visible_content(page7_table_note[0])
assert all(
- str(block["content"]).startswith("资料来源:")
+ _visible_content(block).startswith("资料来源:")
for page_number in expected_new_footnotes
for block in model_list[page_number - 1]
if block["type"] == "footnote" and block is not page7_table_note[0]
@@ -1451,7 +1653,10 @@ def test_caibao_page2_parallel_chart_captions_stay_separate() -> None:
image_group = next(
group
for group in page2_image_groups
- if any(str(child["content"]).startswith(caption_prefix) for child in group["content"])
+ if any(
+ _visible_content(child).startswith(caption_prefix)
+ for child in group["content"]
+ )
)
assert [child["type"] for child in image_group["content"]] == [
"image_caption",
@@ -1662,7 +1867,10 @@ def test_mixed_elements_pages_07_10_force_txt_regressions() -> None:
algorithm_groups = [
group
for group in _grouped_visual_blocks(page8, "code")
- if any(str(child["content"]).startswith("Algorithm") for child in group["content"])
+ if any(
+ _visible_content(child).startswith("Algorithm")
+ for child in group["content"]
+ )
]
assert len(algorithm_groups) == 2
assert all([child["type"] for child in group["content"]] == ["code_caption", "code_body"] for group in algorithm_groups)
diff --git a/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.py
index 15910a45..02f6bacb 100644
--- a/tests/unittest/test_pdf_analyze_block_content.py
+++ b/tests/unittest/test_pdf_analyze_block_content.py
@@ -20,6 +20,10 @@ from mineru.backend.analysis.pdf.text.native import (
POST_OCR_FALLBACK_SCORE_KEY,
)
from mineru.model.flash import PdfModel
+from mineru.render._internal.common.inline import (
+ inline_plain_text,
+ parse_inline_content,
+)
from mineru.types import BlockType, ContentType, MiddleJson
from mineru.utils.pdf_document import PDFDocument
@@ -777,7 +781,10 @@ def test_npu_page_three_low_visual_runs_keep_index_line_structure() -> None:
)
flash_index_block = next(block for block in PdfModel().predict(document)[2] if block.get("type") == BlockType.INDEX)
- assert index_block["content"] == flash_index_block["content"]
+ flash_content = inline_plain_text(
+ parse_inline_content(str(flash_index_block["content"]))
+ )
+ assert index_block["content"] == flash_content
assert len(str(index_block["content"]).splitlines()) == 24
assert str(index_block["content"]).splitlines()[0] == "1 前言 1"
assert str(index_block["content"]).splitlines()[-1] == "5 附录: 19"
diff --git a/tests/unittest/test_pdf_text_styles.py b/tests/unittest/test_pdf_text_styles.py
index e5daa8a3..c0eda51a 100644
--- a/tests/unittest/test_pdf_text_styles.py
+++ b/tests/unittest/test_pdf_text_styles.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import math
from io import BytesIO
from types import SimpleNamespace
from unittest.mock import MagicMock
@@ -14,18 +15,20 @@ 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.types import RAW_CAPTION, RAW_FOOTNOTE, BlockType, ContentType, MiddleJson
from mineru.utils.pdf_document import PDFDocument
from mineru.utils.pdf_text_styles import (
+ PDF_FONT_FORCE_BOLD_FLAG,
+ PDF_FONT_ITALIC_FLAG,
PDFTextStyleLine,
PDFTextStyleRange,
- apply_pdf_strikethrough_styles,
- detect_pdf_strikethrough_lines,
+ apply_pdf_text_styles,
+ detect_pdf_text_style_lines,
)
def _build_native_text_style_pdf() -> bytes:
- """构造包含删除线、下划线、整栏横线和短横线的单页原生 PDF。"""
+ """构造包含字体、删除线、下划线及其反例的单页原生 PDF。"""
content = b"""0.8 w
BT /F1 12 Tf 50 250 Td (strike: alpha ) Tj (deleted) Tj ( omega) Tj ET
@@ -38,13 +41,20 @@ 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
+BT /F2 12 Tf 50 50 Td (bold sample) Tj ET
+BT /F3 12 Tf 50 30 Td (italic sample) Tj ET
+BT /F4 12 Tf 50 10 Td (bold italic sample) Tj ET
"""
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"/Resources << /Font << /F1 4 0 R /F2 5 0 R /F3 6 0 R /F4 7 0 R >> >> "
+ b"/Contents 8 0 R >>",
b"<< /Type /Font /Subtype /Type1 /BaseFont /Courier >>",
+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>",
+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique >>",
+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-BoldOblique >>",
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")
@@ -76,6 +86,10 @@ def _text_line(
height: float = 10.0,
angle: int = 0,
source_index: int = 0,
+ font_name: str = "",
+ font_flags: int = 0,
+ font_weight: object = None,
+ rotation_degrees: float = 0.0,
) -> SimpleNamespace:
"""构造带真实字符 bbox 的轻量视觉文本行。"""
@@ -88,6 +102,12 @@ def _text_line(
"char": char,
"bbox": (cursor, y, cursor + width, y + height),
"char_idx": char_index,
+ "rotation": math.radians(rotation_degrees),
+ "font": {
+ "name": font_name,
+ "flags": font_flags,
+ "weight": font_weight,
+ },
}
)
cursor += width
@@ -108,7 +128,7 @@ def _drawing(
width: float = 1.0,
orientation: str = "horizontal",
) -> SimpleNamespace:
- """构造删除线检测使用的轻量 drawing。"""
+ """构造文本装饰线检测使用的轻量 drawing。"""
return SimpleNamespace(
bbox=(x0, y - width / 2, x1, y + width / 2),
@@ -123,6 +143,189 @@ def _char_span(line: SimpleNamespace, start: int, end: int) -> tuple[float, floa
return line.chars[start]["bbox"][0], line.chars[end - 1]["bbox"][2]
+ ("line_options", "expected_styles"),
+ [
+ ({"font_flags": PDF_FONT_FORCE_BOLD_FLAG}, ("bold",)),
+ ({"font_weight": 599}, None),
+ ({"font_weight": 600}, ("bold",)),
+ ({"font_weight": -1}, None),
+ ({"font_weight": "invalid"}, None),
+ ({"font_name": "ABCDEF+FrankRuhlHofshi-Bold"}, ("bold",)),
+ ({"font_name": "SourceSansPro-Semibold"}, ("bold",)),
+ ({"font_name": "Arial-Black"}, ("bold",)),
+ ({"font_name": "HiraginoSansGB-W6"}, ("bold",)),
+ ({"font_name": "HiraginoSansGB-W3"}, None),
+ (
+ {
+ "font_name": "LinuxLibertineGBI",
+ "font_flags": PDF_FONT_ITALIC_FLAG,
+ },
+ ("bold",),
+ ),
+ ({"font_name": "MyriadPro-SemiCn"}, None),
+ ({"font_flags": PDF_FONT_ITALIC_FLAG}, None),
+ ({"font_name": "TimesNewRomanPS-ItalicMT"}, None),
+ ({"font_name": "Helvetica-Oblique"}, None),
+ ({"rotation_degrees": 4.9}, None),
+ ({"rotation_degrees": 5.0}, None),
+ ({"rotation_degrees": 19.0}, None),
+ ({"rotation_degrees": 30.0}, None),
+ ({"rotation_degrees": 30.1}, None),
+ ],
+)
+def test_detects_font_styles_only_from_approved_direct_evidence(
+ line_options: dict[str, object],
+ expected_styles: tuple[str, ...] | None,
+) -> None:
+ """验证 PDF 只从批准的直接证据生成粗体,所有斜体证据均被忽略。"""
+
+ line = _text_line("styled", **line_options)
+
+ detected = detect_pdf_text_style_lines([line], [])
+
+ if expected_styles is None:
+ assert detected == []
+ else:
+ assert detected == [
+ PDFTextStyleLine(
+ line.bbox,
+ "styled",
+ (PDFTextStyleRange(0, 6, expected_styles),),
+ 0,
+ )
+ ]
+
+
+def test_rotated_line_never_uses_local_rotation_as_italic_evidence() -> None:
+ """验证整行非标准方向即使字符角差落入区间也不会标为斜体。"""
+
+ line = _text_line(
+ "watermark",
+ angle=340,
+ rotation_degrees=20.0,
+ )
+
+ assert detect_pdf_text_style_lines([line], []) == []
+
+
+ ("text", "expected_text"),
+ [
+ ("A", None),
+ ("中", None),
+ ("AB", "AB"),
+ ("fi", "fi"),
+ ],
+)
+def test_filters_pdf_bold_runs_shorter_than_two_comparable_characters(
+ text: str,
+ expected_text: str | None,
+) -> None:
+ """验证单字符粗体被过滤,双字符和展开为双字符的 ligature 保留。"""
+
+ line = _text_line(text, font_name="Helvetica-Bold")
+
+ detected = detect_pdf_text_style_lines([line], [])
+
+ if expected_text is None:
+ assert detected == []
+ else:
+ assert detected == [
+ PDFTextStyleLine(
+ line.bbox,
+ expected_text,
+ (PDFTextStyleRange(0, len(expected_text), ("bold",)),),
+ 0,
+ )
+ ]
+
+
+def test_filters_isolated_leading_bold_list_marker_cluster() -> None:
+ """验证达到最小长度的行首项目符号簇仍不会污染普通正文。"""
+
+ line = _text_line("•• body")
+ for char in line.chars[:2]:
+ char["font"] = {
+ "name": "Helvetica-Bold",
+ "flags": 0,
+ "weight": 400,
+ }
+
+ assert detect_pdf_text_style_lines([line], []) == []
+
+
+def test_filters_bold_bullet_but_keeps_later_bold_list_text() -> None:
+ """验证真实列表形态只移除行首粗体圆点,保留后续粗体正文。"""
+
+ line = _text_line("• 无序列表项 1:bold 粗体文本")
+ bold_indices = {0}
+ bold_start = line.text.index("bold")
+ bold_indices.update(range(bold_start, len(line.text)))
+ for char_index in bold_indices:
+ line.chars[char_index]["font"] = {
+ "name": "Helvetica-Bold",
+ "flags": 0,
+ "weight": 400,
+ }
+
+ detected = detect_pdf_text_style_lines([line], [])
+ bold_fragments = [
+ detected[0].text[style_range.start : style_range.end]
+ for style_range in detected[0].style_ranges
+ if "bold" in style_range.styles
+ ]
+
+ assert bold_fragments == ["bold粗体文本"]
+
+
+def test_keeps_list_marker_when_it_is_part_of_a_full_bold_run() -> None:
+ """验证项目符号与后续正文同属完整粗体 run 时不会被单独删除。"""
+
+ line = _text_line("• bold", font_name="Helvetica-Bold")
+
+ detected = detect_pdf_text_style_lines([line], [])
+
+ assert detected[0].style_ranges == (
+ PDFTextStyleRange(0, 5, ("bold",)),
+ )
+
+
+def test_combines_bold_and_strikethrough_styles_per_character() -> None:
+ """验证斜体字体保持普通文本,粗体与删除线仍按字符正确组合。"""
+
+ line = _text_line("ABCDEF", height=5.0)
+ for char_index in (1, 2):
+ line.chars[char_index]["font"] = {
+ "name": "Helvetica-Bold",
+ "flags": 0,
+ "weight": 400,
+ }
+ line.chars[3]["font"] = {
+ "name": "Helvetica-Oblique",
+ "flags": 0,
+ "weight": 400,
+ }
+ for char_index in (4, 5):
+ line.chars[char_index]["font"] = {
+ "name": "Helvetica-BoldOblique",
+ "flags": 0,
+ "weight": 400,
+ }
+ x0, x1 = _char_span(line, 1, 6)
+
+ detected = detect_pdf_text_style_lines(
+ [line],
+ [_drawing(x0, x1, 12.5)],
+ )
+
+ assert detected[0].style_ranges == (
+ PDFTextStyleRange(1, 3, ("bold", "strikethrough")),
+ PDFTextStyleRange(3, 4, ("strikethrough",)),
+ PDFTextStyleRange(4, 6, ("bold", "strikethrough")),
+ )
+
+
def test_detects_long_strikethrough_and_preserves_internal_spaces() -> None:
"""验证长删除线按字符范围生成单个紧凑样式区间。"""
@@ -131,7 +334,7 @@ def test_detects_long_strikethrough_and_preserves_internal_spaces() -> None:
end = start + len("deleted text")
x0, x1 = _char_span(line, start, end)
- detected = detect_pdf_strikethrough_lines(
+ detected = detect_pdf_text_style_lines(
[line],
[_drawing(x0, x1, 15.0)],
)
@@ -139,12 +342,137 @@ def test_detects_long_strikethrough_and_preserves_internal_spaces() -> None:
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
+ detected[0].style_ranges[0].start : detected[0].style_ranges[0].end
] == "deletedtext"
-def test_rejects_underline_thick_short_and_column_rule() -> None:
- """验证下划线、粗线、短线和贯穿整栏的分隔线均不产生样式。"""
[email protected]("drawing_y", [18.0, 20.0, 22.0])
+def test_detects_underline_inside_strict_bottom_band(drawing_y: float) -> None:
+ """验证主体字符下边界上下 0.20h 内的长横线产生下划线。"""
+
+ line = _text_line("alpha underlined omega")
+ start = line.text.index("underlined")
+ end = start + len("underlined")
+ x0, x1 = _char_span(line, start, end)
+
+ detected = detect_pdf_text_style_lines(
+ [line],
+ [_drawing(x0, x1, drawing_y)],
+ )
+
+ assert detected[0].style_ranges == (
+ PDFTextStyleRange(5, 15, ("underline",)),
+ )
+
+
[email protected]("drawing_y", [17.99, 22.01])
+def test_rejects_underline_outside_strict_bottom_band(
+ drawing_y: float,
+) -> None:
+ """验证超过主体下边界 0.20h 的横线不产生下划线。"""
+
+ line = _text_line("alpha underlined omega")
+ start = line.text.index("underlined")
+ end = start + len("underlined")
+ x0, x1 = _char_span(line, start, end)
+
+ assert detect_pdf_text_style_lines(
+ [line],
+ [_drawing(x0, x1, drawing_y)],
+ ) == []
+
+
+def test_combines_bold_underline_and_strikethrough_in_protocol_order() -> None:
+ """验证同一字符范围的粗体、下划线和删除线按固定顺序合并。"""
+
+ line = _text_line("styled", font_name="Helvetica-Bold")
+ x0, x1 = _char_span(line, 0, len(line.text))
+
+ detected = detect_pdf_text_style_lines(
+ [line],
+ [
+ _drawing(x0, x1, 15.0),
+ _drawing(x0, x1, 20.0),
+ ],
+ )
+
+ assert detected[0].style_ranges == (
+ PDFTextStyleRange(
+ 0,
+ 6,
+ ("bold", "underline", "strikethrough"),
+ ),
+ )
+
+
+def test_merges_repeated_underline_drawings() -> None:
+ """验证双线或重复共线 drawing 只生成一个下划线语义区间。"""
+
+ line = _text_line("underlined")
+ x0, x1 = _char_span(line, 0, len(line.text))
+
+ detected = detect_pdf_text_style_lines(
+ [line],
+ [
+ _drawing(x0, x1, 19.0),
+ _drawing(x0, x1, 20.0),
+ ],
+ )
+
+ assert detected[0].style_ranges == (
+ PDFTextStyleRange(0, 10, ("underline",)),
+ )
+
+
+def test_rejects_fraction_bar_with_tightly_contained_lower_run() -> None:
+ """验证横线下方紧邻且被覆盖的分母 run 会阻止下划线误判。"""
+
+ numerator = _text_line("numerator", source_index=0)
+ denominator = _text_line(
+ "den",
+ x=28.0,
+ y=21.4,
+ height=8.0,
+ source_index=1,
+ )
+ x0, x1 = _char_span(numerator, 0, len(numerator.text))
+
+ assert detect_pdf_text_style_lines(
+ [numerator, denominator],
+ [_drawing(x0, x1, 20.0)],
+ ) == []
+
+
+def test_keeps_underline_when_following_text_is_outside_fraction_gap() -> None:
+ """验证普通下一行即使水平重叠也不会触发分数线排除。"""
+
+ first = _text_line("underlined", source_index=0)
+ second = _text_line(
+ "next",
+ x=28.0,
+ y=22.1,
+ height=8.0,
+ source_index=1,
+ )
+ x0, x1 = _char_span(first, 0, len(first.text))
+
+ detected = detect_pdf_text_style_lines(
+ [first, second],
+ [_drawing(x0, x1, 20.0)],
+ )
+
+ ranges_by_source = {
+ line.source_index: line.style_ranges
+ for line in detected
+ }
+ assert ranges_by_source[0] == (
+ PDFTextStyleRange(0, 10, ("underline",)),
+ )
+ assert ranges_by_source[1] == ()
+
+
+def test_rejects_thick_short_and_column_rules() -> None:
+ """验证粗线、短线和贯穿整栏的分隔线均不产生文本样式。"""
line = _text_line("alpha deleted omega")
start = line.text.index("deleted")
@@ -154,17 +482,16 @@ def test_rejects_underline_thick_short_and_column_rule() -> None:
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(
+ detected = detect_pdf_text_style_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)
+ assert all(not item.style_ranges for item in detected)
def test_accepts_one_aligned_endpoint_and_merges_adjacent_drawings() -> None:
@@ -178,7 +505,7 @@ def test_accepts_one_aligned_endpoint_and_merges_adjacent_drawings() -> None:
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(
+ detected = detect_pdf_text_style_lines(
[line],
[
_drawing(deleted_x0, deleted_x1 + 5.0, 15.0),
@@ -186,8 +513,8 @@ def test_accepts_one_aligned_endpoint_and_merges_adjacent_drawings() -> None:
],
)
- assert len(detected[0].strikethrough_ranges) == 1
- style_range = detected[0].strikethrough_ranges[0]
+ assert len(detected[0].style_ranges) == 1
+ style_range = detected[0].style_ranges[0]
assert detected[0].text[style_range.start : style_range.end] == "deletedtext"
@@ -208,7 +535,7 @@ def test_keeps_two_disjoint_strikethrough_ranges() -> None:
removed_start + len("removed"),
)
- detected = detect_pdf_strikethrough_lines(
+ detected = detect_pdf_text_style_lines(
[line],
[
_drawing(deleted_x0, deleted_x1, 15.0),
@@ -218,7 +545,7 @@ def test_keeps_two_disjoint_strikethrough_ranges() -> None:
assert [
detected[0].text[style_range.start : style_range.end]
- for style_range in detected[0].strikethrough_ranges
+ for style_range in detected[0].style_ranges
] == ["deleted", "removed"]
@@ -229,16 +556,18 @@ def test_drawing_is_assigned_to_the_closest_overlapping_line() -> None:
second = _text_line("deleted", y=11.0, source_index=1)
x0, x1 = _char_span(first, 0, len(first.text))
- detected = detect_pdf_strikethrough_lines(
+ detected = detect_pdf_text_style_lines(
[first, second],
[_drawing(x0, x1, 15.1)],
)
ranges_by_source = {
- line.source_index: line.strikethrough_ranges
+ line.source_index: line.style_ranges
for line in detected
}
- assert ranges_by_source[0] == (PDFTextStyleRange(0, 7),)
+ assert ranges_by_source[0] == (
+ PDFTextStyleRange(0, 7, ("strikethrough",)),
+ )
assert ranges_by_source[1] == ()
@@ -247,7 +576,7 @@ def test_rotated_text_is_not_a_style_candidate() -> None:
line = _text_line("rotated text", angle=90)
- assert detect_pdf_strikethrough_lines(
+ assert detect_pdf_text_style_lines(
[line],
[_drawing(10.0, 80.0, 15.0)],
) == []
@@ -263,7 +592,7 @@ def test_invalid_line_and_char_bboxes_are_ignored() -> None:
chars=[{"char": "x", "bbox": (10.0, 10.0, 10.0, 20.0)}],
)
- assert detect_pdf_strikethrough_lines(
+ assert detect_pdf_text_style_lines(
[invalid_line],
[_drawing(10.0, 40.0, 15.0)],
) == []
@@ -284,16 +613,66 @@ def test_applies_style_to_plain_content_and_duplicate_second_line() -> None:
PDFTextStyleLine(
(10.0, 30.0, 50.0, 40.0),
"deleted",
- (PDFTextStyleRange(0, 7),),
+ (PDFTextStyleRange(0, 7, ("strikethrough",)),),
1,
),
]
- apply_pdf_strikethrough_styles(blocks, lines, (100.0, 100.0))
+ apply_pdf_text_styles(blocks, lines, (100.0, 100.0))
assert blocks[0]["content"] == 'deleted <text style="strikethrough">deleted</text>'
+def test_same_visual_row_style_runs_follow_source_order_despite_bbox_jitter() -> None:
+ """验证同行 run 的细微顶边抖动不会把后方粗体片段提前映射。"""
+
+ attention = _text_line(
+ "Attention",
+ x=10.0,
+ y=10.01,
+ source_index=0,
+ font_name="Helvetica-Bold",
+ )
+ bias = _text_line(
+ "Bias",
+ x=80.0,
+ y=10.01,
+ source_index=1,
+ font_name="Helvetica-Bold",
+ )
+ scaling = _text_line(
+ "Scaling. Unlike",
+ x=120.0,
+ y=10.0,
+ source_index=2,
+ )
+ for char in scaling.chars[: len("Scaling.")]:
+ char["font"] = {
+ "name": "Helvetica-Bold",
+ "flags": 0,
+ "weight": 400,
+ }
+
+ style_lines = detect_pdf_text_style_lines(
+ [scaling, attention, bias],
+ [],
+ )
+ assert [line.source_index for line in style_lines] == [0, 1, 2]
+
+ blocks = [
+ {
+ "type": BlockType.TEXT,
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "Attention Bias Scaling. Unlike",
+ }
+ ]
+ apply_pdf_text_styles(blocks, style_lines, (250.0, 100.0))
+
+ assert blocks[0]["content"] == (
+ '<text style="bold">Attention Bias Scaling.</text> Unlike'
+ )
+
+
def test_applies_style_inside_superscript_without_crossing_tags() -> None:
"""验证删除线只包装 sup 内的文本叶子,不破坏原有上下标标签。"""
@@ -308,18 +687,318 @@ def test_applies_style_inside_superscript_without_crossing_tags() -> None:
PDFTextStyleLine(
(10.0, 10.0, 90.0, 20.0),
"valuedeletedtail",
- (PDFTextStyleRange(5, 12),),
+ (PDFTextStyleRange(5, 12, ("strikethrough",)),),
0,
)
]
- apply_pdf_strikethrough_styles(blocks, lines, (100.0, 100.0))
+ apply_pdf_text_styles(blocks, lines, (100.0, 100.0))
assert blocks[0]["content"] == (
'value <sup><text style="strikethrough">deleted</text></sup> tail'
)
+def test_filters_italic_before_merging_overlapping_style_ranges() -> None:
+ """验证过滤斜体后仍正确合并粗体、下划线与删除线区间。"""
+
+ blocks = [
+ {
+ "type": "text",
+ "bbox": [0.0, 0.0, 1.0, 0.4],
+ "content": "abcdef",
+ }
+ ]
+ lines = [
+ PDFTextStyleLine(
+ (10.0, 10.0, 90.0, 20.0),
+ "abcdef",
+ (
+ PDFTextStyleRange(0, 4, ("bold",)),
+ PDFTextStyleRange(2, 6, ("italic",)),
+ PDFTextStyleRange(1, 5, ("underline",)),
+ PDFTextStyleRange(3, 5, ("strikethrough",)),
+ ),
+ 0,
+ )
+ ]
+
+ apply_pdf_text_styles(blocks, lines, (100.0, 100.0))
+
+ assert blocks[0]["content"] == (
+ '<text style="bold">a</text>'
+ '<text style="bold,underline">bc</text>'
+ '<text style="bold,underline,strikethrough">d</text>'
+ '<text style="underline,strikethrough">e</text>f'
+ )
+
+
+def test_preserves_internal_spaces_and_is_idempotent() -> None:
+ """验证字体样式保留内部空格,重复富化不会增加嵌套标签。"""
+
+ blocks = [
+ {
+ "type": "text",
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "bold text",
+ }
+ ]
+ lines = [
+ PDFTextStyleLine(
+ (10.0, 10.0, 90.0, 20.0),
+ "boldtext",
+ (PDFTextStyleRange(0, 8, ("bold",)),),
+ 0,
+ )
+ ]
+
+ apply_pdf_text_styles(blocks, lines, (100.0, 100.0))
+ first_result = blocks[0]["content"]
+ apply_pdf_text_styles(blocks, lines, (100.0, 100.0))
+
+ assert first_result == '<text style="bold">bold text</text>'
+ assert blocks[0]["content"] == first_result
+
+
+def test_underline_does_not_wrap_boundary_spaces() -> None:
+ """验证下划线只保留命中字符之间的内部空格,不扩散到边界空格。"""
+
+ blocks = [
+ {
+ "type": BlockType.TEXT,
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": " under lined ",
+ }
+ ]
+ lines = [
+ PDFTextStyleLine(
+ (10.0, 10.0, 90.0, 20.0),
+ "underlined",
+ (PDFTextStyleRange(0, 10, ("underline",)),),
+ 0,
+ )
+ ]
+
+ apply_pdf_text_styles(blocks, lines, (100.0, 100.0))
+
+ assert blocks[0]["content"] == (
+ ' <text style="underline">under lined</text> '
+ )
+
+
+ "block_type",
+ [
+ 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,
+ ],
+)
+def test_applies_style_specific_scope_to_natural_language_blocks(
+ block_type: str,
+) -> None:
+ """验证粗体和下划线仅进入 text,删除线保持自然语言范围。"""
+
+ blocks = [
+ {
+ "type": block_type,
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "styled",
+ }
+ ]
+ lines = [
+ PDFTextStyleLine(
+ (10.0, 10.0, 90.0, 20.0),
+ "styled",
+ (
+ PDFTextStyleRange(
+ 0,
+ 6,
+ ("bold", "italic", "underline", "strikethrough"),
+ ),
+ ),
+ 0,
+ )
+ ]
+
+ apply_pdf_text_styles(blocks, lines, (100.0, 100.0))
+
+ expected_styles = (
+ "bold,underline,strikethrough"
+ if block_type == BlockType.TEXT
+ else "strikethrough"
+ )
+ assert blocks[0]["content"] == (
+ f'<text style="{expected_styles}">styled</text>'
+ )
+
+
+ "block_type",
+ [
+ BlockType.TABLE,
+ BlockType.CODE,
+ BlockType.EQUATION,
+ BlockType.IMAGE,
+ ],
+)
+def test_does_not_apply_styles_to_visual_or_code_blocks(block_type: str) -> None:
+ """验证表格、代码、公式和图片 block 不进入 PDF 文本样式富化。"""
+
+ blocks = [
+ {
+ "type": block_type,
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "styled",
+ }
+ ]
+ lines = [
+ PDFTextStyleLine(
+ (10.0, 10.0, 90.0, 20.0),
+ "styled",
+ (
+ PDFTextStyleRange(
+ 0,
+ 6,
+ ("bold", "italic", "underline", "strikethrough"),
+ ),
+ ),
+ 0,
+ )
+ ]
+
+ apply_pdf_text_styles(blocks, lines, (100.0, 100.0))
+
+ assert blocks[0]["content"] == "styled"
+
+
+def test_respects_existing_styles_and_skips_equation_and_url_payloads() -> None:
+ """验证已有样式保持幂等,公式和 URL 不进入 PDF 样式富化。"""
+
+ blocks = [
+ {
+ "type": "text",
+ "bbox": [0.0, 0.0, 1.0, 0.4],
+ "content": (
+ "A<sup>B</sup><eq>C</eq>"
+ "<hyperlink><text>D</text><url>u</url></hyperlink>"
+ ),
+ },
+ {
+ "type": "text",
+ "bbox": [0.0, 0.6, 1.0, 1.0],
+ "content": (
+ "<b>A</b><i>B</i><u>C</u><s>D</s>"
+ '<text style="underline">E</text>'
+ ),
+ },
+ ]
+ lines = [
+ PDFTextStyleLine(
+ (10.0, 10.0, 90.0, 20.0),
+ "ABCD",
+ (
+ PDFTextStyleRange(0, 1, ("bold",)),
+ PDFTextStyleRange(1, 2, ("italic",)),
+ PDFTextStyleRange(2, 3, ("bold",)),
+ PDFTextStyleRange(3, 4, ("bold", "italic", "underline")),
+ ),
+ 0,
+ ),
+ PDFTextStyleLine(
+ (10.0, 70.0, 90.0, 80.0),
+ "ABCDE",
+ (
+ PDFTextStyleRange(0, 1, ("bold",)),
+ PDFTextStyleRange(1, 2, ("italic",)),
+ PDFTextStyleRange(2, 3, ("underline",)),
+ PDFTextStyleRange(3, 4, ("strikethrough",)),
+ PDFTextStyleRange(4, 5, ("underline",)),
+ ),
+ 1,
+ ),
+ ]
+
+ apply_pdf_text_styles(blocks, lines[:1], (100.0, 100.0))
+ apply_pdf_text_styles(blocks[1:], lines[1:], (100.0, 100.0))
+ first_results = [block["content"] for block in blocks]
+ apply_pdf_text_styles(blocks, lines, (100.0, 100.0))
+
+ assert '<text style="bold">A</text>' in str(blocks[0]["content"])
+ assert "<sup>B</sup>" in str(blocks[0]["content"])
+ assert "<eq>C</eq>" in str(blocks[0]["content"])
+ assert '<text style="bold,underline">D</text>' in str(blocks[0]["content"])
+ assert "<url>u</url>" in str(blocks[0]["content"])
+ assert blocks[1]["content"] == (
+ "<b>A</b><i>B</i><u>C</u><s>D</s>"
+ '<text style="underline">E</text>'
+ )
+ assert [block["content"] for block in blocks] == first_results
+
+
+def test_formula_style_does_not_fall_back_to_same_plain_character() -> None:
+ """验证公式内字体样式不会误映射到同一 block 的同名普通字符。"""
+
+ blocks = [
+ {
+ "type": "text",
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "A<eq>C</eq>C",
+ }
+ ]
+ lines = [
+ PDFTextStyleLine(
+ (10.0, 10.0, 90.0, 20.0),
+ "ACC",
+ (PDFTextStyleRange(1, 2, ("bold",)),),
+ 0,
+ )
+ ]
+
+ apply_pdf_text_styles(blocks, lines, (100.0, 100.0))
+
+ assert blocks[0]["content"] == "A<eq>C</eq>C"
+
+
+def test_unique_long_style_range_survives_omitted_list_marker() -> None:
+ """验证 layout 省略行首项目符号时,较长唯一字体片段仍能安全对齐。"""
+
+ blocks = [
+ {
+ "type": "text",
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "无序列表项1:bold 粗体文本",
+ }
+ ]
+ lines = [
+ PDFTextStyleLine(
+ (10.0, 10.0, 90.0, 20.0),
+ "•无序列表项1:bold粗体文本",
+ (
+ PDFTextStyleRange(0, 1, ("bold",)),
+ PDFTextStyleRange(8, 16, ("bold",)),
+ ),
+ 0,
+ )
+ ]
+
+ apply_pdf_text_styles(blocks, lines, (100.0, 100.0))
+
+ assert blocks[0]["content"] == (
+ '无序列表项1:<text style="bold">bold 粗体文本</text>'
+ )
+
+
def test_never_styles_equations_or_excluded_blocks() -> None:
"""验证公式内容与 table block 不会被 PDF 删除线富化。"""
@@ -339,25 +1018,25 @@ def test_never_styles_equations_or_excluded_blocks() -> None:
PDFTextStyleLine(
(10.0, 10.0, 90.0, 20.0),
"beforedeletedafter",
- (PDFTextStyleRange(6, 13),),
+ (PDFTextStyleRange(6, 13, ("strikethrough",)),),
0,
),
PDFTextStyleLine(
(10.0, 60.0, 90.0, 70.0),
"deleted",
- (PDFTextStyleRange(0, 7),),
+ (PDFTextStyleRange(0, 7, ("strikethrough",)),),
1,
),
]
- apply_pdf_strikethrough_styles(blocks, lines, (100.0, 100.0))
+ apply_pdf_text_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 和三种渲染输出。"""
+def test_flash_native_pdf_styles_reach_model_middle_and_renderers() -> None:
+ """验证真实 PDF 字体和 drawing 样式贯穿 model、MiddleJson 与 renderer。"""
document = PDFDocument(_build_native_text_style_pdf())
try:
@@ -372,10 +1051,14 @@ def test_flash_native_pdf_strikethrough_reaches_model_middle_and_renderers() ->
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="underline">underlined</text>' 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
+ assert '<text style="bold">bold sample</text>' in joined_model_content
+ assert "italic sample" in joined_model_content
+ assert '<text style="italic">' not in joined_model_content
+ assert '<text style="bold">bold italic sample</text>' in joined_model_content
middle = MiddleJson(
pages=model_list_to_pages(model_list),
@@ -391,21 +1074,39 @@ def test_flash_native_pdf_strikethrough_reaches_model_middle_and_renderers() ->
).decode("utf-8")
assert "~~deleted~~" in markdown
+ assert "<u>underlined</u>" in markdown
+ assert "**bold sample**" in markdown
+ assert "*italic sample*" not in markdown
+ assert "**bold italic sample**" in markdown
assert "<s>deleted</s>" in html
+ assert "<u>underlined</u>" in html
+ assert "<strong>bold sample</strong>" in html
+ assert "<em>italic sample</em>" not in html
+ assert "<strong>bold italic sample</strong>" in html
assert "<w:strike" in document_xml
+ assert "<w:u" in document_xml
+ assert "<w:b" in document_xml
+ assert "<w:i/>" not in document_xml
+ assert '<w:i w:val="1"' not in document_xml
def test_hybrid_txt_reuses_loaded_chars_and_applies_styles(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """验证 Medium/High/XHigh 共用 TXT 回填入口复用 chars 并写入删除线。"""
+ """验证 Medium/High/XHigh 复用 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),),
+ (
+ PDFTextStyleRange(
+ 0,
+ 7,
+ ("bold", "italic", "underline", "strikethrough"),
+ ),
+ ),
0,
)
]
@@ -479,13 +1180,15 @@ def test_hybrid_txt_reuses_loaded_chars_and_applies_styles(
)
assert observed_chars == [page_chars]
- assert model_list[0][0]["content"] == '<text style="strikethrough">deleted</text>'
+ assert model_list[0][0]["content"] == (
+ '<text style="bold,underline,strikethrough">deleted</text>'
+ )
def test_low_txt_applies_styles_after_native_content_fill(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """验证 Low/TXT 在 block content 完成后应用同一删除线协议。"""
+ """验证 Low/TXT 在 block content 完成后应用相同的组合样式策略。"""
span = _AnalyzeSpan(
type=ContentType.TEXT,
@@ -496,7 +1199,13 @@ def test_low_txt_applies_styles_after_native_content_fill(
style_line = PDFTextStyleLine(
(10.0, 10.0, 52.0, 20.0),
"deleted",
- (PDFTextStyleRange(0, 7),),
+ (
+ PDFTextStyleRange(
+ 0,
+ 7,
+ ("bold", "italic", "underline", "strikethrough"),
+ ),
+ ),
0,
)
monkeypatch.setattr(
@@ -521,13 +1230,15 @@ def test_low_txt_applies_styles_after_native_content_fill(
[[]],
)
- assert model_list[0][0]["content"] == '<text style="strikethrough">deleted</text>'
+ assert model_list[0][0]["content"] == (
+ '<text style="bold,underline,strikethrough">deleted</text>'
+ )
def test_ocr_path_does_not_collect_or_apply_pdf_styles(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """验证 OCR 路径不会读取 drawing 或应用原生文本删除线。"""
+ """验证 OCR 路径不会读取 drawing 或应用 PDF 原生文本样式。"""
build_styles = MagicMock()
monkeypatch.setattr(
@@ -584,7 +1295,7 @@ def test_ocr_path_does_not_collect_or_apply_pdf_styles(
def test_native_span_fill_does_not_read_preloaded_page_chars_twice() -> None:
- """验证删除线检测已加载 chars 后,原生 span 回填不会再次读取当前页字符。"""
+ """验证样式检测已加载 chars 后,原生 span 回填不会再次读取当前页字符。"""
page_chars = [
{