Skip to content

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

fix: bound OFD parsing and standardize table styles

myhloli9cf1921567bd
diff --git a/docs/next/decisions/0033-middle-json-inline-spans.md b/docs/next/decisions/0033-middle-json-inline-spans.md
index 3035ca8c..9e6bbbd4 100644
--- a/docs/next/decisions/0033-middle-json-inline-spans.md
+++ b/docs/next/decisions/0033-middle-json-inline-spans.md
@@ -20,6 +20,8 @@ Schema 2.0 使用自然语言字符串中的 `<eq>`、`<text style>` 和
后处理只做结构化合并和裁剪;renderer 按 discriminator 分派。
- 算法正文新增 `algorithm_body` 并使用 Span;普通代码、行间公式、表格 HTML、
Chart HTML、图片专用内容和 Mermaid 继续使用专用字符串。
+- 表格 HTML 的文字样式直接使用受限标准标签 `strong/em/u/s/sup/sub`;不在表格
+ 字符串中恢复自然语言时代的私有 `<text style="...">` 协议。
- HTML v1 wire 使用明确 DOM metadata 精确恢复 Span,不从展示标签反推。
- 当前运行时仍严格使用 schema 3.0;仅对 MinerU 3.4.5 页面结构及对应的 1.0
pages 包装保留 `legacy_schema_adapter`,先转换为结构化 raw ModelJson 再进入统一后处理。
@@ -30,4 +32,6 @@ Schema 2.0 使用自然语言字符串中的 `<eq>`、`<text style>` 和
- `A&B`、`1<2`、实体外观与完整 `<script>`/`<eq>` 字面量可以无歧义保真;
- URL 安全策略只作用于 HyperlinkSpan.url;自动链接只作用于 TextSpan;
- parser、后处理和 renderer 之间不再存在自然语言私有标记协议;
+- 简单表格转 GFM 时,粗体、斜体、删除线及粗斜体使用 Markdown wrapper,其他
+ 组合整体保留为标准 HTML 标签;复杂表格继续原样保留安全 HTML;
- 这是有意的不兼容升级,调用方必须携带并校验 `schema_version="3.0"`。
diff --git a/docs/next/middle-json/current-medium.md b/docs/next/middle-json/current-medium.md
index 4f4d4485..f0415f95 100644
--- a/docs/next/middle-json/current-medium.md
+++ b/docs/next/middle-json/current-medium.md
@@ -118,7 +118,9 @@ TextSpan 中保持原文。renderer 在目标格式边界执行转义,不反
| `chart_body` | Chart HTML/文本 |
表格和 Chart HTML 中的公式继续使用受限安全 DOM 节点处理,不进入 InlineSpan
-流水线。图片 sidecar、bbox、score 和字体信息也不属于 InlineSpan。
+流水线。表格内文字样式使用 `strong/em/u/s/sup/sub` 标准 HTML 标签,不使用
+`<text style="...">` 私有协议。图片 sidecar、bbox、score 和字体信息也不属于
+InlineSpan。
## 容器约束
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.md
index e56022f7..8dddd036 100644
--- a/docs/next/middle-json/rendering.md
+++ b/docs/next/middle-json/rendering.md
@@ -472,7 +472,10 @@ text 合并允许跨越任意其他 block,后一个 text 的内容被吸收到
- `index`: 递归输出 GFM 列表;标题叶子使用 anchor 生成内部链接,不当作 heading 输出。
- `equation`: content 非空时输出行间 LaTeX,空 content 回退图片。
- `image/chart`: 图片优先,识别内容放入折叠 details;chart 的简单 HTML 表格转为 GFM,复杂表格保留 HTML,无图片时直接输出转换后的内容。
-- `table`: 简单单层 HTML 转 GFM;合并单元格或不可无损结构保留 HTML;空间投影文本使用动态 fenced block;空 content 回退图片。
+- `table`: 简单单层 HTML 转 GFM;`strong/em/s` 的简单样式组合使用 Markdown wrapper,
+ `u/sup/sub` 或其它复杂组合整体保留标准 HTML 标签;合并单元格或不可无损结构保留
+ HTML;空间投影文本使用动态 fenced block;空 content 回退图片。表格不解析旧
+ `<text style="...">` 私有标签。
- `code`: 使用 `guess_lang` 和动态 fenced block。
- `algorithm`: `algorithm_body` 使用等宽、`white-space: pre-wrap` 的 HTML div,并按 EquationInlineSpan 渲染公式。
diff --git a/mineru/model/flash/ofd/constants.py b/mineru/model/flash/ofd/constants.py
index cb12864d..23a7979f 100644
--- a/mineru/model/flash/ofd/constants.py
+++ b/mineru/model/flash/ofd/constants.py
@@ -22,7 +22,10 @@ MAX_ASSET_TOTAL_BYTES: Final = 128 * 1024 * 1024
MAX_EXPANDED_TEXT_BYTES: Final = 64 * 1024 * 1024
MAX_EXPANDED_GLYPHS: Final = 2_000_000
MAX_GLYPH_TOKENS: Final = 2_000_000
+MAX_DELTA_TOKENS: Final = MAX_EXPANDED_GLYPHS
MAX_PATH_COMMANDS: Final = 2_000_000
+MAX_PATH_TOKENS: Final = MAX_PATH_COMMANDS * 8
+MAX_TABLE_INTERSECTION_CHECKS: Final = MAX_PATH_COMMANDS
MAX_OBJECT_RECURSION: Final = 64
MAX_DRAW_PARAM_INHERITANCE: Final = 64
MAX_FONT_BYTES: Final = 32 * 1024 * 1024
@@ -33,6 +36,7 @@ MM_TO_POINTS: Final = 72.0 / 25.4
__all__ = [
"MAX_ASSET_TOTAL_BYTES",
"MAX_DOCUMENT_COUNT",
+ "MAX_DELTA_TOKENS",
"MAX_DRAW_PARAM_INHERITANCE",
"MAX_ENTRY_BYTES",
"MAX_ENTRY_COUNT",
@@ -43,6 +47,8 @@ __all__ = [
"MAX_OBJECT_RECURSION",
"MAX_PAGE_COUNT",
"MAX_PATH_COMMANDS",
+ "MAX_PATH_TOKENS",
+ "MAX_TABLE_INTERSECTION_CHECKS",
"MAX_TOTAL_BYTES",
"MAX_XML_DEPTH",
"MAX_XML_NODES",
diff --git a/mineru/model/flash/ofd/images.py b/mineru/model/flash/ofd/images.py
index bc92e9b2..0440c2c2 100644
--- a/mineru/model/flash/ofd/images.py
+++ b/mineru/model/flash/ofd/images.py
@@ -13,6 +13,7 @@ from lxml import etree # type: ignore[reportMissingImports]
from .._shared.image import image_to_b64str
from ....types import BBox
from ....utils.image_payload import validate_decoded_raster_size
+from .errors import OfdParseError
from .geometry import Affine, bbox_intersection, canonical_angle, parse_affine, parse_st_box, transform_angle, transform_bbox
from .models import ImageItem, ResourceRegistry
from .package import OfdPackage, parse_int
@@ -71,9 +72,14 @@ def build_image_item(
page_bbox = bbox_intersection(page_bbox, parent_clip)
if page_bbox is None:
return None
- resource_id = parse_int(image_object.get("ResourceID") or image_object.get("ResouceID"))
+ raw_resource_id = image_object.get("ResourceID") or image_object.get("ResouceID")
+ resource_id = parse_int(raw_resource_id)
media = resources.media.get(resource_id) if resource_id is not None else None
object_id = parse_int(image_object.get("ID"))
+ if raw_resource_id is not None and media is None:
+ raise OfdParseError(
+ f"Malformed OFD package: ImageObject id={object_id} references missing media resource {raw_resource_id!r}"
+ )
if media is None:
return ImageItem(
bbox=page_bbox,
@@ -84,11 +90,9 @@ def build_image_item(
template_id=template_id,
diagnostic="missing_media_resource",
)
- data = package.read_part(media.media_part, asset=True)
- if data is None:
- diagnostic = "missing_media_part"
- payload = None
- elif data.startswith(_JBIG2_SIGNATURE):
+ data = package.read_part(media.media_part, required=True, asset=True)
+ assert data is not None
+ if data.startswith(_JBIG2_SIGNATURE):
diagnostic = "unsupported_jbig2"
payload = None
else:
diff --git a/mineru/model/flash/ofd/path.py b/mineru/model/flash/ofd/path.py
index 7ca64d33..5a7056a6 100644
--- a/mineru/model/flash/ofd/path.py
+++ b/mineru/model/flash/ofd/path.py
@@ -11,7 +11,7 @@ from loguru import logger
from lxml import etree # type: ignore[reportMissingImports]
from ....types import BBox
-from .constants import MAX_PATH_COMMANDS
+from .constants import MAX_PATH_COMMANDS, MAX_PATH_TOKENS
from .errors import OfdResourceLimitError
from .geometry import Affine, bbox_intersection, parse_affine, parse_st_box, transform_bbox
from .models import AxisLine
@@ -22,13 +22,20 @@ _TOKEN_RE = re.compile(r"CM|[SMLQBAC]|[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d
@dataclass(slots=True)
class OfdPathBudget:
- """累计限制紧缩路径命令数量。"""
+ """累计限制紧缩路径 token 与命令数量。"""
command_count: int = 0
+ token_count: int = 0
- def charge(self, count: int) -> None:
- """累计本次路径命令并在超限时失败。"""
- self.command_count += count
+ def charge_token(self) -> None:
+ """累计实际扫描的路径 token 并在超限时失败。"""
+ self.token_count += 1
+ if self.token_count > MAX_PATH_TOKENS:
+ raise OfdResourceLimitError(f"OFD resource limit exceeded: max_path_tokens={MAX_PATH_TOKENS}")
+
+ def charge_command(self) -> None:
+ """累计实际扫描的路径命令并在超限时失败。"""
+ self.command_count += 1
if self.command_count > MAX_PATH_COMMANDS:
raise OfdResourceLimitError(f"OFD resource limit exceeded: max_path_commands={MAX_PATH_COMMANDS}")
@@ -42,11 +49,6 @@ def _finite_float(value: str) -> float | None:
return parsed if math.isfinite(parsed) else None
-def _tokenize(value: str) -> list[str]:
- """把紧缩路径文本拆成命令和数值 token。"""
- return _TOKEN_RE.findall(value)
-
-
def _line_bbox(first: tuple[float, float], second: tuple[float, float], width: float) -> tuple[BBox, str] | None:
"""把近似水平或垂直线段转换为非退化 bbox。"""
dx = second[0] - first[0]
@@ -80,37 +82,37 @@ def _line_bbox(first: tuple[float, float], second: tuple[float, float], width: f
def _segments(value: str, transform: Affine, budget: OfdPathBudget) -> list[tuple[tuple[float, float], tuple[float, float]]]:
- """提取 S/M/L/CM 产生的直线段,曲线命令只推进当前位置。"""
- tokens = _tokenize(value)
- command_count = sum(token in {"S", "M", "L", "Q", "B", "A", "C", "CM"} for token in tokens)
- budget.charge(command_count)
+ """流式提取 S/M/L/CM 直线段,曲线命令只推进当前位置。"""
result: list[tuple[tuple[float, float], tuple[float, float]]] = []
- index = 0
current: tuple[float, float] | None = None
subpath_start: tuple[float, float] | None = None
command: str | None = None
+ parameters: list[float] = []
+ commands = {"S", "M", "L", "Q", "B", "A", "C", "CM"}
arity = {"S": 2, "M": 2, "L": 2, "Q": 4, "B": 6, "A": 7, "CM": 2}
- while index < len(tokens):
- token = tokens[index]
- if token in {"S", "M", "L", "Q", "B", "A", "C", "CM"}:
+ for match in _TOKEN_RE.finditer(value):
+ budget.charge_token()
+ token = match.group()
+ if token in commands:
+ if parameters:
+ return []
+ budget.charge_command()
command = token
- index += 1
if command == "C":
if current is not None and subpath_start is not None and current != subpath_start:
result.append((transform.apply(current), transform.apply(subpath_start)))
current = subpath_start
- continue
+ command = None
+ continue
if command is None or command == "C":
return []
- needed = arity[command]
- if index + needed > len(tokens):
- break
- values = [_finite_float(item) for item in tokens[index : index + needed]]
- if any(item is None for item in values):
- index += needed
+ parsed = _finite_float(token)
+ if parsed is None:
+ return []
+ parameters.append(parsed)
+ if len(parameters) < arity[command]:
continue
- numbers = [float(item) for item in values if item is not None]
- endpoint = (numbers[-2], numbers[-1])
+ endpoint = (parameters[-2], parameters[-1])
if command in {"S", "M"}:
current = endpoint
subpath_start = endpoint
@@ -120,8 +122,8 @@ def _segments(value: str, transform: Affine, budget: OfdPathBudget) -> list[tupl
current = endpoint
else:
current = endpoint
- index += needed
- return result
+ parameters.clear()
+ return [] if parameters else result
def build_axis_lines(
diff --git a/mineru/model/flash/ofd/reading_order.py b/mineru/model/flash/ofd/reading_order.py
index 18f4b581..b1707a33 100644
--- a/mineru/model/flash/ofd/reading_order.py
+++ b/mineru/model/flash/ofd/reading_order.py
@@ -12,7 +12,7 @@ from .._shared.xycut import sort_entries
from ....types import BlockType
from .geometry import bbox_center, bbox_union, normalize_bbox
from .models import OfdPageScene, TextLine
-from .table import OfdTableRegion, recover_tables
+from .table import OfdTableBudget, OfdTableRegion, recover_tables
from .text import format_line_spans
_PAGE_NUMBER_RE = re.compile(r"^(?:\d+|[IVXLCDM]+)$", re.IGNORECASE)
@@ -175,6 +175,7 @@ class OfdReadingOrderProjector:
body_sizes = [line.font_size for scene in scenes for line in scene.text_lines if line.font_size > 0]
self.body_size = statistics.median(body_sizes) if body_sizes else 1.0
self.document_title_emitted = False
+ self.table_budget = OfdTableBudget()
def _text_block(self, line: TextLine, scene: OfdPageScene) -> dict[str, Any]:
"""把 TextLine 转换为尚未归一化的 raw block。"""
@@ -233,7 +234,7 @@ class OfdReadingOrderProjector:
def project_page(self, scene: OfdPageScene) -> list[dict[str, Any]]:
"""把一页场景投影为最终阅读顺序 raw model-list。"""
merged_lines = merge_same_baseline_lines(scene.text_lines)
- tables = recover_tables(scene.axis_lines, merged_lines)
+ tables = recover_tables(scene.axis_lines, merged_lines, self.table_budget)
consumed = {line_id for table in tables for line_id in table.consumed_line_ids}
blocks = [self._text_block(line, scene) for line in merged_lines if id(line) not in consumed]
blocks.extend(self._table_block(table) for table in tables)
diff --git a/mineru/model/flash/ofd/resources.py b/mineru/model/flash/ofd/resources.py
index 958ebfa7..cb9bd953 100644
--- a/mineru/model/flash/ofd/resources.py
+++ b/mineru/model/flash/ofd/resources.py
@@ -5,11 +5,11 @@ from __future__ import annotations
from loguru import logger
-from .constants import MAX_DRAW_PARAM_INHERITANCE
-from .errors import OfdResourceLimitError
+from .constants import MAX_DRAW_PARAM_INHERITANCE, OFD_NAMESPACES
+from .errors import OfdParseError, OfdResourceLimitError
from .geometry import parse_numbers
from .models import CompositeResource, FontResource, MediaResource, ResourceRegistry
-from .package import OfdPackage, element_text, first_child, local_name, parse_int
+from .package import OfdPackage, element_text, first_child, local_name, namespace_name, parse_int
def _bool_attr(value: str | None) -> bool:
@@ -36,10 +36,11 @@ def parse_resource_part(package: OfdPackage, resource_part: str | None) -> Resou
registry = ResourceRegistry()
if resource_part is None:
return registry
- root = package.xml_part(resource_part)
- if root is None:
- logger.warning(f"OFD_OPTIONAL_RESOURCE_MISSING: part={resource_part!r}")
- return registry
+ root = package.xml_part(resource_part, required=True)
+ assert root is not None
+ namespace = namespace_name(root.tag)
+ if namespace not in OFD_NAMESPACES:
+ raise OfdParseError(f"Malformed OFD package: unsupported namespace {namespace!r} in {resource_part!r}")
base_loc = (root.get("BaseLoc") or "").strip()
for element in root.iter():
name = local_name(element.tag)
diff --git a/mineru/model/flash/ofd/scene.py b/mineru/model/flash/ofd/scene.py
index 2b402177..ff09d42a 100644
--- a/mineru/model/flash/ofd/scene.py
+++ b/mineru/model/flash/ofd/scene.py
@@ -62,8 +62,14 @@ class OfdSceneBuilder:
def _document_resources(self, document_part: str, document_root: etree._Element) -> ResourceRegistry:
"""解析文档级 PublicRes 与 DocumentRes。"""
common_data = first_descendant(document_root, "CommonData")
- public_part = self._resolve_part(document_part, first_child(common_data, "PublicRes"))
- document_resource_part = self._resolve_part(document_part, first_child(common_data, "DocumentRes"))
+ public_element = first_child(common_data, "PublicRes")
+ document_resource_element = first_child(common_data, "DocumentRes")
+ public_part = self._resolve_part(document_part, public_element, required=public_element is not None)
+ document_resource_part = self._resolve_part(
+ document_part,
+ document_resource_element,
+ required=document_resource_element is not None,
+ )
return merge_registries(
parse_resource_part(self.package, public_part),
parse_resource_part(self.package, document_resource_part),
@@ -129,7 +135,12 @@ class OfdSceneBuilder:
if physical_box is None:
raise OfdParseError(f"Malformed OFD package: page {page_ref.page_part!r} has no PhysicalBox")
content_box = self._page_area(page_root, default_content, "ContentBox")
- page_resource_part = self._resolve_part(page_ref.page_part, first_descendant(page_root, "PageRes"))
+ page_resource_element = first_descendant(page_root, "PageRes")
+ page_resource_part = self._resolve_part(
+ page_ref.page_part,
+ page_resource_element,
+ required=page_resource_element is not None,
+ )
resources = merge_registries(document_resources, parse_resource_part(self.package, page_resource_part))
scene = OfdPageScene(
page_idx=page_index_offset + local_page_idx,
@@ -173,7 +184,12 @@ class OfdSceneBuilder:
logger.warning(f"OFD_TEMPLATE_MISSING: template_id={template_id}")
return
template_root = self._required_ofd_xml(template_ref.page_part)
- template_resource_part = self._resolve_part(template_ref.page_part, first_descendant(template_root, "PageRes"))
+ template_resource_element = first_descendant(template_root, "PageRes")
+ template_resource_part = self._resolve_part(
+ template_ref.page_part,
+ template_resource_element,
+ required=template_resource_element is not None,
+ )
template_resources = merge_registries(resources, parse_resource_part(self.package, template_resource_part))
content = first_descendant(template_root, "Content")
if content is None:
diff --git a/mineru/model/flash/ofd/table.py b/mineru/model/flash/ofd/table.py
index 60001d85..d8acb759 100644
--- a/mineru/model/flash/ofd/table.py
+++ b/mineru/model/flash/ofd/table.py
@@ -6,6 +6,8 @@ from __future__ import annotations
from dataclasses import dataclass
from ....types import BBox
+from .constants import MAX_TABLE_INTERSECTION_CHECKS
+from .errors import OfdResourceLimitError
from .geometry import bbox_area, bbox_center, bbox_intersection
from .models import AxisLine, TextLine
from .text import format_line_html
@@ -26,6 +28,21 @@ class OfdTableRegion:
consumed_line_ids: frozenset[int]
+@dataclass(slots=True)
+class OfdTableBudget:
+ """累计限制整份 OFD 的表格线段相交比较次数。"""
+
+ intersection_check_count: int = 0
+
+ def charge_intersection_check(self) -> None:
+ """累计一次线段相交比较并在超限时失败。"""
+ self.intersection_check_count += 1
+ if self.intersection_check_count > MAX_TABLE_INTERSECTION_CHECKS:
+ raise OfdResourceLimitError(
+ f"OFD resource limit exceeded: max_table_intersection_checks={MAX_TABLE_INTERSECTION_CHECKS}"
+ )
+
+
def _line_coord(line: AxisLine) -> float:
"""返回轴向线段在垂直方向上的中心坐标。"""
if line.orientation == "horizontal":
@@ -58,7 +75,7 @@ def _touches(first: AxisLine, second: AxisLine) -> bool:
)
-def _components(lines: list[AxisLine]) -> list[list[AxisLine]]:
+def _components(lines: list[AxisLine], budget: OfdTableBudget) -> list[list[AxisLine]]:
"""按线段相交关系构造确定性的连通分量。"""
parents = list(range(len(lines)))
@@ -78,6 +95,7 @@ def _components(lines: list[AxisLine]) -> list[list[AxisLine]]:
for first_index, first in enumerate(lines):
for second_index in range(first_index + 1, len(lines)):
+ budget.charge_intersection_check()
if _touches(first, lines[second_index]):
union(first_index, second_index)
grouped: dict[int, list[AxisLine]] = {}
@@ -179,12 +197,16 @@ def _serialize_grid(xs: list[float], ys: list[float], lines: list[TextLine]) ->
return "".join(output)
-def recover_tables(axis_lines: list[AxisLine], text_lines: list[TextLine]) -> list[OfdTableRegion]:
+def recover_tables(
+ axis_lines: list[AxisLine],
+ text_lines: list[TextLine],
+ budget: OfdTableBudget,
+) -> list[OfdTableRegion]:
"""从页面轴向线段中恢复互不重叠的高置信表格。"""
if len(axis_lines) < 4 or len(text_lines) < 2 or len(axis_lines) > _MAX_TABLE_AXIS_LINES:
return []
candidates: list[OfdTableRegion] = []
- for component in _components(axis_lines):
+ for component in _components(axis_lines, budget):
grid = _component_grid(component)
if grid is None:
continue
@@ -216,4 +238,4 @@ def recover_tables(axis_lines: list[AxisLine], text_lines: list[TextLine]) -> li
return sorted(selected, key=lambda item: (item.bbox[1], item.bbox[0], item.paint_order))
-__all__ = ["OfdTableRegion", "recover_tables"]
+__all__ = ["OfdTableBudget", "OfdTableRegion", "recover_tables"]
diff --git a/mineru/model/flash/ofd/text.py b/mineru/model/flash/ofd/text.py
index 8418d0d7..c30452e0 100644
--- a/mineru/model/flash/ofd/text.py
+++ b/mineru/model/flash/ofd/text.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import html
import math
import re
+from collections import deque
from dataclasses import dataclass
from io import BytesIO
@@ -15,7 +16,7 @@ from lxml import etree # type: ignore[reportMissingImports]
from .._shared.spans import text_spans
from ....types import BBox
-from .constants import MAX_EXPANDED_GLYPHS, MAX_EXPANDED_TEXT_BYTES, MAX_FONT_BYTES, MAX_GLYPH_TOKENS
+from .constants import MAX_DELTA_TOKENS, MAX_EXPANDED_GLYPHS, MAX_EXPANDED_TEXT_BYTES, MAX_FONT_BYTES, MAX_GLYPH_TOKENS
from .errors import OfdResourceLimitError
from .geometry import (
Affine,
@@ -35,6 +36,7 @@ from .package import OfdPackage, element_text, local_name, parse_int
_HEX_ESCAPE_RE = re.compile(r"\\([0-9A-Fa-f]{4})")
_GLYPH_TOKEN_RE = re.compile(r"\S+")
+_DELTA_TOKEN_RE = re.compile(r"[^,\s]+")
@dataclass(slots=True)
@@ -45,6 +47,7 @@ class OfdTextBudget:
glyph_count: int = 0
glyph_mapping_count: int = 0
glyph_token_count: int = 0
+ delta_token_count: int = 0
def charge(self, text: str) -> None:
"""为一次 TextCode 展开计费。"""
@@ -67,6 +70,12 @@ class OfdTextBudget:
if self.glyph_token_count > MAX_GLYPH_TOKENS:
raise OfdResourceLimitError(f"OFD resource limit exceeded: max_glyph_tokens={MAX_GLYPH_TOKENS}")
+ def charge_delta_token(self) -> None:
+ """累计实际扫描的 Delta token 数量并限制全文解析量。"""
+ self.delta_token_count += 1
+ if self.delta_token_count > MAX_DELTA_TOKENS:
+ raise OfdResourceLimitError(f"OFD resource limit exceeded: max_delta_tokens={MAX_DELTA_TOKENS}")
+
@dataclass(slots=True)
class _LoadedFont:
@@ -197,34 +206,52 @@ def decode_text_code(value: str) -> str:
return _HEX_ESCAPE_RE.sub(lambda match: chr(int(match.group(1), 16)), value)
-def parse_delta(value: str | None, count: int) -> list[float]:
- """展开普通与 g-count-value 压缩 Delta,并补齐不足项。"""
+def parse_delta(value: str | None, count: int, budget: OfdTextBudget) -> list[float]:
+ """流式展开普通与 g-count-value 压缩 Delta,并补齐不足项。"""
if count <= 0:
return []
- tokens = (value or "").replace(",", " ").split()
output: list[float] = []
- index = 0
- while index < len(tokens) and len(output) < count:
- token = tokens[index]
- if token.casefold() == "g" and index + 2 < len(tokens):
+ matches = iter(_DELTA_TOKEN_RE.finditer(value or ""))
+ pending: deque[str] = deque()
+
+ def next_token() -> str | None:
+ """返回下一个 Delta token,并只对首次扫描计费。"""
+ if pending:
+ return pending.popleft()
+ try:
+ match = next(matches)
+ except StopIteration:
+ return None
+ budget.charge_delta_token()
+ return match.group()
+
+ while len(output) < count:
+ token = next_token()
+ if token is None:
+ break
+ if token.casefold() == "g":
+ repeat_token = next_token()
+ value_token = next_token()
+ if repeat_token is None or value_token is None:
+ if repeat_token is not None:
+ pending.appendleft(repeat_token)
+ continue
try:
- repeat = max(0, int(tokens[index + 1]))
- repeated_value = float(tokens[index + 2])
+ repeat = max(0, int(repeat_token))
+ repeated_value = float(value_token)
except ValueError:
- index += 1
+ pending.appendleft(value_token)
+ pending.appendleft(repeat_token)
continue
if math.isfinite(repeated_value):
output.extend([repeated_value] * min(repeat, count - len(output)))
- index += 3
continue
try:
parsed = float(token)
except ValueError:
- index += 1
continue
if math.isfinite(parsed):
output.append(parsed)
- index += 1
if len(output) < count:
output.extend([output[-1] if output else 0.0] * (count - len(output)))
return output[:count]
@@ -293,10 +320,20 @@ def format_line_spans(text: str, styles: tuple[str, ...]) -> list[dict[str, obje
def format_line_html(text: str, styles: tuple[str, ...]) -> str:
"""把 OFD 表格单元格文字序列化为安全 HTML。"""
- escaped = html.escape(text, quote=False)
- if not styles:
- return escaped
- return f'<text style="{",".join(styles)}">{escaped}</text>'
+ rendered = html.escape(text, quote=False)
+ if "superscript" in styles:
+ rendered = f"<sup>{rendered}</sup>"
+ elif "subscript" in styles:
+ rendered = f"<sub>{rendered}</sub>"
+ if "underline" in styles:
+ rendered = f"<u>{rendered}</u>"
+ if "bold" in styles:
+ rendered = f"<strong>{rendered}</strong>"
+ if "italic" in styles:
+ rendered = f"<em>{rendered}</em>"
+ if "strikethrough" in styles:
+ rendered = f"<s>{rendered}</s>"
+ return rendered
def build_text_lines(
@@ -371,8 +408,8 @@ def build_text_lines(
global_position += len(text)
continue
delta_count = max(0, len(text) - 1)
- delta_x = parse_delta(text_code.get("DeltaX"), delta_count)
- delta_y = parse_delta(text_code.get("DeltaY"), delta_count)
+ delta_x = parse_delta(text_code.get("DeltaX"), delta_count, budget)
+ delta_y = parse_delta(text_code.get("DeltaY"), delta_count, budget)
origins: list[tuple[float, float]] = [(inherited_x, inherited_y)]
for index in range(delta_count):
previous = origins[-1]
diff --git a/mineru/render/_internal/docx/renderer.py b/mineru/render/_internal/docx/renderer.py
index 7ef36868..f8ea099f 100644
--- a/mineru/render/_internal/docx/renderer.py
+++ b/mineru/render/_internal/docx/renderer.py
@@ -722,11 +722,6 @@ class _DocxRenderer:
)
rendered = child_rendered or rendered
return paragraph, rendered
- if name == "text":
- spans = _html_inline_spans(node, inherited_styles=inherited_styles)
- append_inline_spans(paragraph, spans, context=context)
- return paragraph, bool(spans)
-
style = {
"strong": "bold",
"b": "bold",
@@ -864,9 +859,6 @@ def _html_inline_spans(node: Tag, *, inherited_styles: tuple[str, ...] = ()) ->
"sub": "subscript",
}.get(name)
styles = tuple(dict.fromkeys((*inherited_styles, style))) if style else inherited_styles
- if name == "text":
- declared = [item.strip() for item in str(child.get("style", "")).split(",") if item.strip()]
- styles = tuple(dict.fromkeys((*styles, *declared)))
children = _html_inline_spans(child, inherited_styles=styles)
if name == "a":
non_link_children = [item for item in children if not isinstance(item, HyperlinkSpan)]
diff --git a/mineru/render/_internal/markdown/inline.py b/mineru/render/_internal/markdown/inline.py
index 8fac0e6d..d648c70f 100644
--- a/mineru/render/_internal/markdown/inline.py
+++ b/mineru/render/_internal/markdown/inline.py
@@ -185,6 +185,16 @@ def _apply_style_wrappers(
return f"{leading}{_apply_html_styles(core, styles)}{trailing}"
+def render_styled_markdown_text(content: str, styles: Sequence[str]) -> str:
+ """按正文相同规则把已转义文字渲染为 Markdown 或安全 HTML 样式。"""
+ return _apply_style_wrappers(content, styles)
+
+
+def markdown_styles_require_html(styles: Sequence[str]) -> bool:
+ """判断样式组合是否必须整体使用 HTML 标签表达。"""
+ return bool(styles) and frozenset(styles) not in _SIMPLE_STYLE_WRAPPERS
+
+
def _render_visible_whitespace(content: str, styles: Sequence[str]) -> str:
"""使用原 HTML 规则保留非 ASCII marker 场景的可见空白。"""
visible = "".join("<br>" if char == "\n" else "&nbsp;" for char in content.expandtabs(4))
@@ -243,9 +253,11 @@ def _escape_markdown_link_label(label: str) -> str:
__all__ = [
+ "markdown_styles_require_html",
"render_inline_content",
"render_inline_spans",
"render_inline_spans_in_html_context",
"render_internal_link",
"render_joined_inline_contents",
+ "render_styled_markdown_text",
]
diff --git a/mineru/render/_internal/markdown/table.py b/mineru/render/_internal/markdown/table.py
index e35a5dc1..e3a2c10a 100644
--- a/mineru/render/_internal/markdown/table.py
+++ b/mineru/render/_internal/markdown/table.py
@@ -11,6 +11,7 @@ from bs4.element import NavigableString, Tag
from ....config import LatexDelimitersConfig
from .assets import prefix_html_image_sources
+from .inline import markdown_styles_require_html, render_styled_markdown_text
_INLINE_EQ_RE = re.compile(r"<eq>(?P<latex>.*?)</eq>", re.IGNORECASE | re.DOTALL)
_GFM_FORMULA_PIPE_RE = re.compile(r"(?P<slashes>\\*)\|")
@@ -51,6 +52,16 @@ _ALLOWED_INLINE_TAGS = {
"sup",
"u",
}
+_STYLE_TAGS = {
+ "b": "bold",
+ "strong": "bold",
+ "em": "italic",
+ "i": "italic",
+ "u": "underline",
+ "s": "strikethrough",
+ "sup": "superscript",
+ "sub": "subscript",
+}
def _strip_embedded_images(markup: str) -> str:
@@ -167,17 +178,24 @@ def _detect_header_index(table: Tag, header_flags: list[list[bool]]) -> int:
return 0
-def _render_inline_children(node: Tag, delimiters: LatexDelimitersConfig) -> str:
+def _render_inline_children(
+ node: Tag,
+ delimiters: LatexDelimitersConfig,
+ inherited_styles: tuple[str, ...] = (),
+) -> str:
"""递归渲染简单单元格中的安全行内 HTML。"""
parts: list[str] = []
for child in node.children:
if isinstance(child, NavigableString):
- parts.append(_escape_cell_text(str(child)))
+ escaped = _escape_cell_text(str(child))
+ parts.append(render_styled_markdown_text(escaped, inherited_styles))
continue
if not isinstance(child, Tag):
continue
name = child.name
- rendered = _render_inline_children(child, delimiters)
+ style = _STYLE_TAGS.get(name)
+ styles = tuple(dict.fromkeys((*inherited_styles, style))) if style is not None else inherited_styles
+ rendered = _render_inline_children(child, delimiters, styles)
if name in {"p", "span"}:
parts.append(rendered)
elif name == "br":
@@ -190,20 +208,35 @@ def _render_inline_children(node: Tag, delimiters: LatexDelimitersConfig) -> str
parts.append(f"{delimiters.inline.left}{escaped_latex}{delimiters.inline.right}" if escaped_latex else "")
elif name == "a":
href = str(child.get("href", "")).strip()
- parts.append(f"[{rendered}]({_escape_link_url(href)})" if href else rendered)
- elif name in {"b", "strong"}:
- parts.append(f"**{rendered.strip()}**")
- elif name in {"em", "i"}:
- parts.append(f"*{rendered.strip()}*")
- elif name == "s":
- parts.append(f"~~{rendered.strip()}~~")
- elif name in {"u", "sub", "sup"}:
- parts.append(f"<{name}>{rendered}</{name}>")
+ if not href:
+ parts.append(rendered)
+ elif _node_has_complex_text_style(child, inherited_styles):
+ parts.append(f'<a href="{html.escape(href, quote=True)}">{rendered}</a>')
+ else:
+ parts.append(f"[{rendered}]({_escape_link_url(href)})")
+ elif name in _STYLE_TAGS:
+ parts.append(rendered)
else:
parts.append(rendered)
return "".join(parts)
+def _node_has_complex_text_style(node: Tag, inherited_styles: tuple[str, ...]) -> bool:
+ """判断节点后代是否含必须用 HTML 表达的有效文字样式组合。"""
+ for child in node.children:
+ if isinstance(child, NavigableString):
+ if str(child) and markdown_styles_require_html(inherited_styles):
+ return True
+ continue
+ if not isinstance(child, Tag):
+ continue
+ style = _STYLE_TAGS.get(child.name)
+ styles = tuple(dict.fromkeys((*inherited_styles, style))) if style is not None else inherited_styles
+ if _node_has_complex_text_style(child, styles):
+ return True
+ return False
+
+
def _render_inline_code(content: str) -> str:
"""使用足够长的反引号包装表格单元格内代码。"""
longest = max((len(match.group(0)) for match in re.finditer(r"`+", content)), default=0)
diff --git a/tests/unittest/test_docx_render.py b/tests/unittest/test_docx_render.py
index 350bbfe9..8868a9ff 100644
--- a/tests/unittest/test_docx_render.py
+++ b/tests/unittest/test_docx_render.py
@@ -555,6 +555,26 @@ def test_html_table_materializes_merges_inline_content_link_and_image() -> None:
assert "https://example.com/table" in relationships
+def test_html_table_does_not_restore_legacy_text_style_tags() -> None:
+ """验证旧 text-style 容器只保留文字,标准 strong 标签继续恢复粗体。"""
+ table = TableBlock(
+ type="table",
+ index=0,
+ content=[
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content=('<table><tr><td><text style="bold">legacy</text><strong>standard</strong></td></tr></table>'),
+ )
+ ],
+ )
+
+ document = Document(BytesIO(render_docx(_middle(_page(0, table)))))
+ runs = [run for paragraph in document.tables[0].cell(0, 0).paragraphs for run in paragraph.runs if run.text]
+
+ assert [(run.text, bool(run.bold)) for run in runs] == [("legacy", False), ("standard", True)]
+
+
def test_html_table_cell_lists_keep_item_boundaries() -> None:
"""验证 HTML 单元格中的有序和无序列表不会串成连续文本。"""
html = (
diff --git a/tests/unittest/test_epub_render.py b/tests/unittest/test_epub_render.py
index d32557c3..7412cc89 100644
--- a/tests/unittest/test_epub_render.py
+++ b/tests/unittest/test_epub_render.py
@@ -171,6 +171,38 @@ def test_epub_package_is_single_spine_epub33_with_stable_metadata_and_mathml() -
assert later_identifier == first_identifier
+def test_epub_table_preserves_standard_inline_style_tags() -> None:
+ """验证表格中的标准文字样式标签安全复制为 XHTML。"""
+ table = TableBlock(
+ type="table",
+ index=0,
+ content=[
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content=(
+ "<table><tr><td><strong>bold</strong><em>italic</em><u>under</u>"
+ "<s>strike</s><sup>sup</sup><sub>sub</sub></td></tr></table>"
+ ),
+ )
+ ],
+ )
+
+ with _archive(render_epub(_middle(_page(0, table)), modified_at=_FIXED_TIME)) as archive:
+ content = _xml(archive, "EPUB/text/content.xhtml")
+
+ assert [
+ content.xpath(f"string(//xhtml:td/xhtml:{tag})", namespaces=_NS) for tag in ("strong", "em", "u", "s", "sup", "sub")
+ ] == [
+ "bold",
+ "italic",
+ "under",
+ "strike",
+ "sup",
+ "sub",
+ ]
+
+
def test_epub_uses_default_planner_without_source_page_boundaries() -> None:
"""验证固定默认 EPUB 连续阅读、隐藏辅助块且不保留源页边界。"""
middle = _middle(
diff --git a/tests/unittest/test_flash_ofd.py b/tests/unittest/test_flash_ofd.py
index 255c07bf..46b19b83 100644
--- a/tests/unittest/test_flash_ofd.py
+++ b/tests/unittest/test_flash_ofd.py
@@ -8,6 +8,8 @@ from pathlib import Path
from unittest.mock import MagicMock
from zipfile import ZIP_DEFLATED, ZipFile
+from bs4 import BeautifulSoup
+from docx import Document
from lxml import etree
from PIL import Image
import pytest
@@ -23,21 +25,24 @@ from mineru.model.flash.ofd import OfdParseError, OfdResourceLimitError, detect_
from mineru.model.flash.ofd import images as ofd_images
from mineru.model.flash.ofd import metadata as ofd_metadata
from mineru.model.flash.ofd import scene as ofd_scene
+from mineru.model.flash.ofd import table as ofd_table
from mineru.model.flash.ofd.constants import (
+ MAX_DELTA_TOKENS,
MAX_DOCUMENT_COUNT,
MAX_DRAW_PARAM_INHERITANCE,
MAX_EXPANDED_GLYPHS,
MAX_GLYPH_TOKENS,
MAX_PAGE_COUNT,
+ MAX_PATH_TOKENS,
)
from mineru.model.flash.ofd.geometry import Affine, canonical_angle
from mineru.model.flash.ofd.images import build_image_item
-from mineru.model.flash.ofd.models import MediaResource, OfdPageScene, ResourceRegistry
+from mineru.model.flash.ofd.models import AxisLine, MediaResource, OfdPageScene, ResourceRegistry, TextLine
from mineru.model.flash.ofd.package import OfdPackage
from mineru.model.flash.ofd.path import OfdPathBudget, _segments, build_axis_lines
from mineru.model.flash.ofd.reading_order import OfdReadingOrderProjector
-from mineru.model.flash.ofd.resources import resolve_draw_param
-from mineru.model.flash.ofd.text import FontMetricResolver, OfdTextBudget, build_text_lines
+from mineru.model.flash.ofd.resources import parse_resource_part, resolve_draw_param
+from mineru.model.flash.ofd.text import FontMetricResolver, OfdTextBudget, build_text_lines, parse_delta
from mineru.parser import MinerUParser
from mineru.parser import api_server
from mineru.parser.api_server import CreateJobRequest, FileStore
@@ -62,6 +67,20 @@ def _minimal_payload(*, namespace: str = "http://www.ofdspec.org/2016", version:
)
+def _replace_package_part(payload: bytes, part_name: str, replacement: bytes | None) -> bytes:
+ """替换或删除测试 OFD ZIP 中的单个成员。"""
+ source_buffer = BytesIO(payload)
+ output_buffer = BytesIO()
+ with ZipFile(source_buffer) as source, ZipFile(output_buffer, "w", ZIP_DEFLATED) as output:
+ for info in source.infolist():
+ if info.filename == part_name:
+ if replacement is not None:
+ output.writestr(info, replacement)
+ continue
+ output.writestr(info, source.read(info.filename))
+ return output_buffer.getvalue()
+
+
def test_ofd_model_analyze_detection_and_renderers(tmp_path: Path) -> None:
"""验证 OFD 从内容识别到统一四类 renderer 的完整链路。"""
payload = _minimal_payload()
@@ -351,6 +370,19 @@ def test_ofd_cgtransform_expands_only_actual_text_positions() -> None:
)
+def test_ofd_delta_tokens_are_streamed_and_bounded() -> None:
+ """验证 Delta 只扫描所需 token,并在全文累计超限时受控失败。"""
+ budget = OfdTextBudget()
+
+ assert parse_delta("1 " + "2 " * 100_000, 1, budget) == [1.0]
+ assert budget.delta_token_count == 1
+ assert parse_delta("g 3 2", 4, budget) == [2.0, 2.0, 2.0, 2.0]
+
+ exhausted = OfdTextBudget(delta_token_count=MAX_DELTA_TOKENS)
+ with pytest.raises(OfdResourceLimitError, match="max_delta_tokens"):
+ parse_delta("invalid 1", 1, exhausted)
+
+
def test_ofd_textcode_discards_glyphs_outside_object_boundary() -> None:
"""验证 TextObject Boundary 会裁掉完整位于边界外的字符和空行。"""
package_buffer = BytesIO()
@@ -505,6 +537,40 @@ def test_ofd_oversized_image_is_rejected_before_pixel_decode(monkeypatch: pytest
image.load.assert_not_called()
+def test_ofd_referenced_media_resource_and_part_are_required() -> None:
+ """验证正文 ImageObject 引用不存在的资源 ID 或成员时整份失败。"""
+ image_element = etree.fromstring(b'<ImageObject ID="7" Boundary="0 0 10 10" ResourceID="1"/>')
+ package_buffer = BytesIO()
+ with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:
+ archive.writestr("OFD.xml", "<OFD/>")
+
+ with OfdPackage(package_buffer.getvalue()) as package:
+ with pytest.raises(OfdParseError, match="missing media resource"):
+ build_image_item(
+ image_element,
+ parent_transform=Affine(),
+ parent_clip=(0.0, 0.0, 100.0, 100.0),
+ resources=ResourceRegistry(),
+ package=package,
+ paint_order=0,
+ layer_type="body",
+ template_id=None,
+ )
+
+ with OfdPackage(package_buffer.getvalue()) as package:
+ with pytest.raises(OfdParseError, match="missing required part"):
+ build_image_item(
+ image_element,
+ parent_transform=Affine(),
+ parent_clip=(0.0, 0.0, 100.0, 100.0),
+ resources=ResourceRegistry(media={1: MediaResource(1, "Image", "PNG", "Res/missing.png")}),
+ package=package,
+ paint_order=0,
+ layer_type="body",
+ template_id=None,
+ )
+
+
def test_ofd_path_rejects_unexpected_numeric_tokens_without_hanging() -> None:
"""验证无活动命令或 C 后的数字 token 直接使当前非法路径降级。"""
assert _segments("1 2", Affine(), OfdPathBudget()) == []
@@ -512,6 +578,19 @@ def test_ofd_path_rejects_unexpected_numeric_tokens_without_hanging() -> None:
assert _segments("M 0 0 L 10 0", Affine(), OfdPathBudget()) == [((0.0, 0.0), (10.0, 0.0))]
+def test_ofd_path_tokens_are_streamed_and_bounded() -> None:
+ """验证无活动命令时立即停止,并在路径 token 累计超限时失败。"""
+ stray_budget = OfdPathBudget()
+
+ assert _segments("1 " * 100_000, Affine(), stray_budget) == []
+ assert stray_budget.token_count == 1
+ assert stray_budget.command_count == 0
+
+ exhausted = OfdPathBudget(token_count=MAX_PATH_TOKENS)
+ with pytest.raises(OfdResourceLimitError, match="max_path_tokens"):
+ _segments("M 0 0", Affine(), exhausted)
+
+
def test_ofd_path_segments_are_clipped_to_object_boundary() -> None:
"""验证完全越界路径被丢弃,穿越路径裁到对象与父级裁剪交集。"""
outside = etree.fromstring(
@@ -585,6 +664,71 @@ def test_ofd_template_grid_recovers_table() -> None:
assert middle.pages[0].blocks[0].type == BlockType.TABLE
+def test_ofd_table_styles_use_standard_html_across_renderers() -> None:
+ """验证 OFD 表格直接输出标准标签,并由 Markdown、HTML、DOCX 保留样式。"""
+ paths = "".join(
+ [
+ path_object(10, boundary="10 20 80 0.2", data="M 0 0.1 L 80 0.1"),
+ path_object(11, boundary="10 50 80 0.2", data="M 0 0.1 L 80 0.1"),
+ path_object(12, boundary="10 80 80 0.2", data="M 0 0.1 L 80 0.1"),
+ path_object(13, boundary="10 20 0.2 60", data="M 0.1 0 L 0.1 60"),
+ path_object(14, boundary="50 20 0.2 60", data="M 0.1 0 L 0.1 60"),
+ path_object(15, boundary="90 20 0.2 60", data="M 0.1 0 L 0.1 60"),
+ ]
+ )
+ body = "".join(
+ [
+ text_object(21, "A", boundary="20 30 10 8", size=4, y=4),
+ text_object(22, "B", boundary="60 30 10 8", size=4, y=4),
+ text_object(23, "C", boundary="20 60 10 8", size=4, y=4),
+ text_object(24, "D", boundary="60 60 10 8", size=4, y=4),
+ ]
+ )
+ page_resource = (
+ '<ofd:Res xmlns:ofd="http://www.ofdspec.org/2016"><ofd:Fonts>'
+ '<ofd:Font ID="1" FontName="Styled" Bold="true" Italic="true"/></ofd:Fonts></ofd:Res>'
+ )
+ payload = build_ofd_package(
+ [("Pages/Page_0/Content.xml", page_xml(paths + body, page_res="PageRes.xml"))],
+ extra_parts={"Doc_0/Pages/Page_0/PageRes.xml": page_resource},
+ )
+
+ middle, model = doc_analyze(payload, file_suffix="ofd")
+ table_html = model.pages[0][0]["content"]
+
+ assert "<text" not in table_html
+ assert "<em><strong>A</strong></em>" in table_html
+ assert "***A***" in render_markdown(middle)
+ html_soup = BeautifulSoup(render_html(middle), "html.parser")
+ assert html_soup.select_one("td em strong").get_text() == "A"
+ document = Document(BytesIO(render_docx(middle)))
+ styled_run = next(run for paragraph in document.tables[0].cell(0, 0).paragraphs for run in paragraph.runs if run.text)
+ assert styled_run.text == "A" and styled_run.bold and styled_run.italic
+
+
+def test_ofd_table_intersection_budget_is_shared_across_pages(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证表格线段比较预算由同一 projector 跨页累计。"""
+
+ def scene(page_idx: int) -> OfdPageScene:
+ """构造需要六次两两比较的单格表页面。"""
+ axis_lines = [
+ AxisLine((0.0, 0.0, 10.0, 0.2), "horizontal", 0.2, 0, None),
+ AxisLine((0.0, 10.0, 10.0, 10.2), "horizontal", 0.2, 1, None),
+ AxisLine((0.0, 0.0, 0.2, 10.0), "vertical", 0.2, 2, None),
+ AxisLine((10.0, 0.0, 10.2, 10.0), "vertical", 0.2, 3, None),
+ ]
+ text_lines = [
+ TextLine("A", (2.0, 2.0, 4.0, 4.0), [], 0, 2.0, 4, 1, "Body", None),
+ TextLine("B", (2.0, 6.0, 4.0, 8.0), [], 0, 2.0, 5, 2, "Body", None),
+ ]
+ return OfdPageScene(page_idx, (0.0, 0.0, 20.0, 20.0), None, text_lines, axis_lines)
+
+ monkeypatch.setattr(ofd_table, "MAX_TABLE_INTERSECTION_CHECKS", 8)
+
+ with pytest.raises(OfdResourceLimitError, match="max_table_intersection_checks"):
+ OfdReadingOrderProjector([scene(0), scene(1)]).project()
+
+
def test_ofd_page_resource_overrides_document_resource() -> None:
"""验证异常重复资源 ID 按 PageRes 高于 PublicRes 的规则解析。"""
page_resource = (
@@ -605,6 +749,62 @@ def test_ofd_page_resource_overrides_document_resource() -> None:
assert model.pages[0][0]["content"] == [{"type": "text", "content": "page-style", "styles": ["bold"]}]
+ ("replacement", "error"),
+ [
+ (None, "invalid required location"),
+ (b"<broken", "invalid XML part"),
+ (b'<Res xmlns="urn:unsupported"/>', "unsupported namespace"),
+ ],
+)
+def test_ofd_declared_resource_part_is_required(replacement: bytes | None, error: str) -> None:
+ """验证已声明资源成员缺失、损坏或 namespace 错误时整份失败。"""
+ payload = _replace_package_part(_minimal_payload(), "Doc_0/PublicRes.xml", replacement)
+
+ with pytest.raises(OfdParseError, match=error):
+ OfdModel().predict(BytesIO(payload))
+
+
+def test_ofd_absent_resource_declaration_is_optional_but_empty_declaration_is_invalid() -> None:
+ """验证未声明资源合法,而显式空资源引用按损坏包处理。"""
+ payload = _minimal_payload()
+ with ZipFile(BytesIO(payload)) as package:
+ document_root = etree.fromstring(package.read("Doc_0/Document.xml"))
+ public_res = next(element for element in document_root.iter() if etree.QName(element).localname == "PublicRes")
+
+ parent = public_res.getparent()
+ assert parent is not None
+ parent.remove(public_res)
+ without_declaration = _replace_package_part(
+ payload,
+ "Doc_0/Document.xml",
+ etree.tostring(document_root, xml_declaration=True, encoding="UTF-8"),
+ )
+ assert OfdModel().predict(BytesIO(without_declaration))
+
+ public_res = etree.SubElement(parent, "{http://www.ofdspec.org/2016}PublicRes")
+ public_res.text = ""
+ empty_declaration = _replace_package_part(
+ payload,
+ "Doc_0/Document.xml",
+ etree.tostring(document_root, xml_declaration=True, encoding="UTF-8"),
+ )
+ with pytest.raises(OfdParseError, match="invalid required location"):
+ OfdModel().predict(BytesIO(empty_declaration))
+
+
+def test_parse_resource_part_none_returns_empty_registry() -> None:
+ """验证调用方明确传入未声明资源时不会读取可选成员。"""
+ package_buffer = BytesIO()
+ with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:
+ archive.writestr("OFD.xml", "<OFD/>")
+
+ with OfdPackage(package_buffer.getvalue()) as package:
+ registry = parse_resource_part(package, None)
+
+ assert not registry.fonts and not registry.media and not registry.composites and not registry.draw_params
+
+
def test_ofd_does_not_open_malformed_unreferenced_custom_tag() -> None:
"""验证损坏但未参与正文的扩展 XML 不会中断解析。"""
payload = build_ofd_package(
diff --git a/tests/unittest/test_html_render.py b/tests/unittest/test_html_render.py
index 7ffa1ef7..dc9b3469 100644
--- a/tests/unittest/test_html_render.py
+++ b/tests/unittest/test_html_render.py
@@ -704,6 +704,36 @@ def test_table_keeps_safe_html_and_spatial_or_image_fallbacks() -> None:
assert soup.select_one('[data-block-index="2"] img')["src"].startswith("data:image/png")
+def test_table_preserves_standard_inline_style_tags() -> None:
+ """验证表格安全 HTML 保留 renderer 支持的标准行内样式标签。"""
+ table = TableBlock(
+ type="table",
+ index=0,
+ content=[
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content=(
+ "<table><tr><td><strong>bold</strong><em>italic</em><u>under</u>"
+ "<s>strike</s><sup>sup</sup><sub>sub</sub></td></tr></table>"
+ ),
+ )
+ ],
+ )
+
+ soup = BeautifulSoup(render_html(_middle(_page(0, table)), standalone=False), "html.parser")
+ cell = soup.select_one("td")
+
+ assert [cell.select_one(tag).get_text() for tag in ("strong", "em", "u", "s", "sup", "sub")] == [
+ "bold",
+ "italic",
+ "under",
+ "strike",
+ "sup",
+ "sub",
+ ]
+
+
def test_discarded_invalid_table_math_does_not_load_mathjax() -> None:
"""验证无单元格表格回退图片后,已丢弃的 eq 不会误触发 MathJax。"""
table = TableBlock(
diff --git a/tests/unittest/test_pdf_render.py b/tests/unittest/test_pdf_render.py
index 5cdae468..f3c912a0 100644
--- a/tests/unittest/test_pdf_render.py
+++ b/tests/unittest/test_pdf_render.py
@@ -6,6 +6,7 @@ from io import BytesIO
from unittest.mock import MagicMock
import base64
+from bs4 import BeautifulSoup
from PIL import Image
from pypdf import PdfReader
import pytest
@@ -17,6 +18,7 @@ from mineru.render import render_pdf
from mineru.render._internal.pdf import assets as pdf_assets
from mineru.render._internal.pdf import formula as formula_module
from mineru.render._internal.pdf.formula import FormulaRenderer, FormulaVector, PdfFormulaError
+from mineru.render._internal.pdf.table import _html_cell_spans
from mineru.types import (
AlgorithmBodyBlock,
ChartAnnotationBlock,
@@ -398,6 +400,27 @@ def test_pdf_oversized_image_bytes_are_rejected_before_pillow(monkeypatch: pytes
open_image.assert_not_called()
+def test_pdf_table_parser_preserves_standard_inline_style_tags() -> None:
+ """验证 PDF 表格解析器把标准 HTML 标签恢复为结构化文字样式。"""
+ soup = BeautifulSoup(
+ "<td><strong>bold</strong><em>italic</em><u>under</u><s>strike</s><sup>sup</sup><sub>sub</sub></td>",
+ "html.parser",
+ )
+ cell = soup.td
+ assert cell is not None
+
+ spans = _html_cell_spans(cell)
+
+ assert [(span.content, list(getattr(span, "styles", []))) for span in spans] == [
+ ("bold", ["bold"]),
+ ("italic", ["italic"]),
+ ("under", ["underline"]),
+ ("strike", ["strikethrough"]),
+ ("sup", ["superscript"]),
+ ("sub", ["subscript"]),
+ ]
+
+
def test_pdf_renders_tables_lists_indices_code_algorithm_and_annotations() -> None:
"""验证原生表格合并、嵌套表、目录、列表、代码算法与说明的组合输出。"""
table = TableBlock.model_validate(
diff --git a/tests/unittest/test_render_html_table.py b/tests/unittest/test_render_html_table.py
index d4f874b5..14b5060c 100644
--- a/tests/unittest/test_render_html_table.py
+++ b/tests/unittest/test_render_html_table.py
@@ -35,6 +35,28 @@ def test_render_html_table_preserves_supported_inline_markup() -> None:
)
+def test_render_html_table_uses_markdown_only_for_simple_style_sets() -> None:
+ """验证标准 HTML 标签按有效样式集合选择 Markdown 或完整 HTML wrapper。"""
+ html = (
+ "<table><tr><td><strong>bold</strong></td><td><em>italic</em></td>"
+ "<td><s>strike</s></td><td><em><strong>both</strong></em></td>"
+ "<td><strong><u>complex</u></strong></td>"
+ "<td><s><strong>mixed</strong></s></td>"
+ "<td><sup><strong>script</strong></sup></td></tr></table>"
+ )
+
+ assert render_html_table(html, asset_base_url="", delimiters=DELIMITERS) == "\n".join(
+ [
+ (
+ "| **bold** | *italic* | ~~strike~~ | ***both*** | "
+ "<strong><u>complex</u></strong> | <s><strong>mixed</strong></s> | "
+ "<strong><sup>script</sup></strong> |"
+ ),
+ "| --- | --- | --- | --- | --- | --- | --- |",
+ ]
+ )
+
+
def test_render_html_table_escapes_angle_brackets_from_text_nodes() -> None:
"""验证实体解码后的文本尖括号不会重新变成可执行 Markdown HTML。"""
html = (
@@ -64,8 +86,7 @@ def test_render_html_table_escapes_formula_pipes_without_changing_latex() -> Non
r"\begin{array}{c|c}x\end{array}",
]
rows = "".join(
- f"<tr><td>F{index}</td><td><eq>{formula}</eq></td><td>ok</td></tr>"
- for index, formula in enumerate(formulas, start=1)
+ f"<tr><td>F{index}</td><td><eq>{formula}</eq></td><td>ok</td></tr>" for index, formula in enumerate(formulas, start=1)
)
html = f"<table><tr><th>Name</th><th>Formula</th><th>Note</th></tr>{rows}</table>"
@@ -79,6 +100,7 @@ def test_render_html_table_escapes_formula_pipes_without_changing_latex() -> Non
f"${formula}$" for formula in formulas
]
+
def test_render_html_table_falls_back_for_span_attribute_even_when_value_is_one() -> None:
"""验证只要显式出现 rowspan/colspan 就按复杂 HTML 输出。"""
html = '<table><tr><td colspan="1">A</td></tr></table>'
@@ -98,10 +120,7 @@ def test_format_embedded_html_rewrites_relative_images_and_equations() -> None:
def test_format_embedded_html_keeps_absolute_and_data_images() -> None:
"""验证已经可访问的绝对图片来源不会重复添加 base URL。"""
- html = (
- '<table><tr><td><img src="https://example.com/a.png">'
- '<img src="data:image/png;base64,AAAA"></td></tr></table>'
- )
+ html = '<table><tr><td><img src="https://example.com/a.png"><img src="data:image/png;base64,AAAA"></td></tr></table>'
formatted = format_embedded_html(html, asset_base_url="https://cdn.example/doc", delimiters=DELIMITERS)