Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: implement legacy Office binary parsing for Excel and PowerPoint formats
myhloli8f75ec5c4a01
diff --git a/docs/next/middle-json/current-medium.md b/docs/next/middle-json/current-medium.mdindex d559b649..4130df9f 100644--- a/docs/next/middle-json/current-medium.md+++ b/docs/next/middle-json/current-medium.md@@ -31,7 +31,7 @@|------|------|------|| `pages` | `list[list[dict]]` | 必填,保存 Analyze 产生的 raw blocks || `page_index_map` | `list[int]` | 必填;空列表表示整本默认顺序,非空时与 pages 等长且唯一递增 |-| `file_suffix` | `pdf/docx/pptx/xlsx` | 必填 |+| `file_suffix` | `pdf/docx/ppt/pptx/xls/xlsx` | 必填 || `effort` | `flash/low/medium/high/xhigh` | 必填,使用分析后实际值 || `parse_mode` | `txt/ocr` | 必填,使用分析后实际值 || `mineru_version` | 非空字符串 | 必填 |@@ -50,7 +50,7 @@ MiddleJson 并执行适用的 PDF 后处理。不再提供裸 model list 加独|------|------|------|| `pages` | `list[PageInfo]` | 必填,`page_idx` 唯一且严格递增 || `is_full_document` | `bool` | 必填,保存整本或抽页语义,不提供默认值 |-| `file_suffix` | `pdf/docx/pptx/xlsx` | 必填 |+| `file_suffix` | `pdf/docx/ppt/pptx/xls/xlsx` | 必填 || `effort` | `flash/low/medium/high/xhigh` | 必填 || `parse_mode` | `txt/ocr` | 必填 || `mineru_version` | 非空字符串 | 必填 |diff --git a/mineru/backend/analysis/contracts.py b/mineru/backend/analysis/contracts.pyindex 3918387f..b51f2fbc 100644--- a/mineru/backend/analysis/contracts.py+++ b/mineru/backend/analysis/contracts.py@@ -10,7 +10,7 @@ AnalyzeEffort: TypeAlias = Literal["flash", "low", "medium", "high", "xhigh"]# 请求阶段允许自动分类,分析结果中的模式必须已经收敛为 txt 或 ocr。ParseMode: TypeAlias = Literal["auto", "txt", "ocr"]ResolvedParseMode: TypeAlias = Literal["txt", "ocr"]-OfficeSuffix: TypeAlias = Literal["docx", "pptx", "xlsx"]+OfficeSuffix: TypeAlias = Literal["docx", "ppt", "pptx", "xls", "xlsx"]@dataclass(slots=True)diff --git a/mineru/backend/analysis/office.py b/mineru/backend/analysis/office.pyindex 4f1de08d..b857e365 100644--- a/mineru/backend/analysis/office.py+++ b/mineru/backend/analysis/office.py@@ -6,13 +6,15 @@ from __future__ import annotationsimport timefrom io import BytesIO-from mineru.model.flash import DocxModel, PptxModel, XlsxModel+from mineru.model.flash import DocxModel, PptModel, PptxModel, XlsModel, XlsxModelfrom .contracts import AnalysisResult, OfficeSuffix_OFFICE_MODEL_MAP = {"docx": DocxModel,+ "ppt": PptModel,"pptx": PptxModel,+ "xls": XlsModel,"xlsx": XlsxModel,}diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.pyindex c1d8176c..e97ba899 100644--- a/mineru/backend/analyze.py+++ b/mineru/backend/analyze.py@@ -16,7 +16,7 @@ from mineru.config import configfrom mineru.types import MiddleJson, ModelJsonfrom mineru.version import __version__ as mineru_version-_SUPPORTED_FILE_SUFFIXES = {"pdf", "docx", "pptx", "xlsx"}+_SUPPORTED_FILE_SUFFIXES = {"pdf", "docx", "ppt", "pptx", "xls", "xlsx"}def _log_infer_performance(file_suffix: str, page_count: int, elapsed: float) -> None:@@ -34,7 +34,7 @@ def doc_analyze(parse_mode: Literal["auto", "txt", "ocr"] = "auto",image_analysis: bool = True,page_index_map: list[int] | None = None,- file_suffix: Literal["pdf", "docx", "pptx", "xlsx"] = "pdf",+ file_suffix: Literal["pdf", "docx", "ppt", "pptx", "xls", "xlsx"] = "pdf",) -> tuple[MiddleJson, ModelJson]:"""生产严格 ModelJson,并在统一边界构造严格 MiddleJson。"""if file_suffix not in _SUPPORTED_FILE_SUFFIXES:@@ -72,7 +72,7 @@ async def aio_doc_analyze(parse_mode: Literal["auto", "txt", "ocr"] = "auto",image_analysis: bool = True,page_index_map: list[int] | None = None,- file_suffix: Literal["pdf", "docx", "pptx", "xlsx"] = "pdf",+ file_suffix: Literal["pdf", "docx", "ppt", "pptx", "xls", "xlsx"] = "pdf",) -> tuple[MiddleJson, ModelJson]:"""在线程中执行统一文档分析,避免阻塞调用方事件循环。"""return await asyncio.to_thread(diff --git a/mineru/model/flash/__init__.py b/mineru/model/flash/__init__.pyindex f3e20574..4992afac 100644--- a/mineru/model/flash/__init__.py+++ b/mineru/model/flash/__init__.py@@ -2,6 +2,6 @@"""Flash PDF 与 Office 模型公开入口。"""-from .model import DocxModel, PdfModel, PptxModel, XlsxModel+from .model import DocxModel, PdfModel, PptModel, PptxModel, XlsModel, XlsxModel-__all__ = ["PdfModel", "DocxModel", "PptxModel", "XlsxModel"]+__all__ = ["PdfModel", "DocxModel", "PptModel", "PptxModel", "XlsModel", "XlsxModel"]diff --git a/mineru/model/flash/legacy_office/__init__.py b/mineru/model/flash/legacy_office/__init__.pynew file mode 100644index 00000000..8368f720--- /dev/null+++ b/mineru/model/flash/legacy_office/__init__.py@@ -0,0 +1,19 @@+# Copyright (c) Opendatalab. All rights reserved.++"""旧版 Office 二进制格式共享基础设施。"""++from .errors import (+ LegacyOfficeEncryptedError,+ LegacyOfficeMalformedError,+ LegacyOfficeMissingPartError,+ LegacyOfficeResourceLimitError,+)+from .ole import BoundedOleReader++__all__ = [+ "BoundedOleReader",+ "LegacyOfficeEncryptedError",+ "LegacyOfficeMalformedError",+ "LegacyOfficeMissingPartError",+ "LegacyOfficeResourceLimitError",+]diff --git a/mineru/model/flash/legacy_office/errors.py b/mineru/model/flash/legacy_office/errors.pynew file mode 100644index 00000000..fb462b4f--- /dev/null+++ b/mineru/model/flash/legacy_office/errors.py@@ -0,0 +1,36 @@+# Copyright (c) Opendatalab. All rights reserved.++"""旧版 Office 解析过程中可稳定识别的错误类型。"""++from __future__ import annotations+++class LegacyOfficeError(ValueError):+ """旧版 Office 解析错误基类,并携带稳定错误码。"""++ code = "legacy_office_error"+++class LegacyOfficeMalformedError(LegacyOfficeError):+ """输入容器或核心二进制记录无法形成有效文档。"""++ code = "malformed"+++class LegacyOfficeMissingPartError(LegacyOfficeError):+ """缺少完成解析所必需的 OLE stream。"""++ code = "missing_part"+++class LegacyOfficeEncryptedError(LegacyOfficeError):+ """输入使用了当前纯 Python 解析链不支持的加密。"""++ code = "encrypted"+++class LegacyOfficeResourceLimitError(LegacyOfficeError):+ """输入超过固定安全限制。"""++ code = "resource_limit"+diff --git a/mineru/model/flash/legacy_office/limits.py b/mineru/model/flash/legacy_office/limits.pynew file mode 100644index 00000000..eead9877--- /dev/null+++ b/mineru/model/flash/legacy_office/limits.py@@ -0,0 +1,14 @@+# Copyright (c) Opendatalab. All rights reserved.++"""旧版 Office 解析使用的固定安全限制。"""++from typing import Final++MAX_ENTRY_BYTES: Final = 128 * 1024 * 1024+MAX_TOTAL_BYTES: Final = 512 * 1024 * 1024+MAX_ASSET_TOTAL_BYTES: Final = 128 * 1024 * 1024+MAX_GRID_SLOTS: Final = 4_000_000+MAX_RECORD_DEPTH: Final = 64+MAX_RECORDS: Final = 16_000_000+MAX_PICTURE_RECORDS: Final = 100_000+MAX_USER_EDIT_CHAIN: Final = 100diff --git a/mineru/model/flash/legacy_office/officeart.py b/mineru/model/flash/legacy_office/officeart.pynew file mode 100644index 00000000..ad4d7989--- /dev/null+++ b/mineru/model/flash/legacy_office/officeart.py@@ -0,0 +1,298 @@+# Copyright (c) Opendatalab. All rights reserved.++"""旧版 Office 二进制格式共享的 OfficeArt 记录与图片解码。"""++from __future__ import annotations++from collections.abc import Callable, Iterator+from dataclasses import dataclass+import struct+import zlib++from loguru import logger++from .errors import LegacyOfficeResourceLimitError+from .limits import (+ MAX_ASSET_TOTAL_BYTES,+ MAX_ENTRY_BYTES,+ MAX_PICTURE_RECORDS,+ MAX_RECORD_DEPTH,+)++OFFICEART_CONTAINER_VERSION = 0xF+OFFICEART_DGG_CONTAINER = 0xF000+OFFICEART_BSTORE_CONTAINER = 0xF001+OFFICEART_SP_CONTAINER = 0xF004+OFFICEART_BSE = 0xF007+OFFICEART_FSP = 0xF00A+OFFICEART_FOPT = 0xF00B+OFFICEART_CLIENT_ANCHOR = 0xF010+OFFICEART_TERTIARY_FOPT = 0xF122++FOPT_PIB = 0x0104+FOPT_GROUP_SHAPE = 0x03BF+F_HIDDEN = 0x0000_0002+F_USE_HIDDEN = 0x0002_0000+++@dataclass(frozen=True, slots=True)+class OfficeArtRecord:+ """一条已经通过长度边界校验的 OfficeArt 记录。"""++ offset: int+ version: int+ instance: int+ record_type: int+ payload: bytes+++@dataclass(frozen=True, slots=True)+class OfficeImagePayload:+ """从 BLIP 中恢复出的原始图片及其媒体类型。"""++ data: bytes+ extension: str+ content_type: str+++@dataclass(frozen=True, slots=True)+class OfficeArtShape:+ """Excel drawing 中可绑定到 OBJ 的形状属性。"""++ shape_id: int | None+ anchor: tuple[int, int, int, int] | None+ pib: int | None+ hidden: bool+++def record_at(+ data: bytes,+ offset: int,+ *,+ end: int | None = None,+ charge: Callable[[], None] | None = None,+) -> OfficeArtRecord | None:+ """从指定偏移读取一条 OfficeArt 记录,坏边界返回空值。"""++ limit = len(data) if end is None else min(end, len(data))+ if offset < 0 or offset + 8 > limit:+ return None+ version_instance, record_type, length = struct.unpack_from("<HHI", data, offset)+ payload_start = offset + 8+ payload_end = payload_start + int(length)+ if payload_end < payload_start or payload_end > limit:+ return None+ if charge is not None:+ charge()+ return OfficeArtRecord(+ offset=offset,+ version=version_instance & 0xF,+ instance=version_instance >> 4,+ record_type=record_type,+ payload=data[payload_start:payload_end],+ )+++def iter_records(+ data: bytes,+ *,+ start: int = 0,+ end: int | None = None,+ charge: Callable[[], None] | None = None,+) -> Iterator[OfficeArtRecord]:+ """顺序遍历同一 OfficeArt 容器内的直接子记录。"""++ limit = len(data) if end is None else min(end, len(data))+ cursor = start+ while cursor < limit:+ record = record_at(data, cursor, end=limit, charge=charge)+ if record is None:+ return+ yield record+ cursor += 8 + len(record.payload)+++def iter_descendants(+ data: bytes,+ *,+ charge: Callable[[], None] | None = None,+) -> Iterator[OfficeArtRecord]:+ """以显式栈深度优先遍历 OfficeArt 记录树并限制嵌套深度。"""++ stack: list[Iterator[OfficeArtRecord]] = [iter_records(data, charge=charge)]+ while stack:+ if len(stack) > MAX_RECORD_DEPTH:+ raise LegacyOfficeResourceLimitError(+ f"record nesting exceeds max_record_depth={MAX_RECORD_DEPTH}"+ )+ try:+ record = next(stack[-1])+ except StopIteration:+ stack.pop()+ continue+ yield record+ if record.version == OFFICEART_CONTAINER_VERSION:+ stack.append(iter_records(record.payload, charge=charge))+++def _simple_properties(record: OfficeArtRecord) -> dict[int, int]:+ """读取 FOPT 简单属性并让后出现的同名属性覆盖前值。"""++ properties: dict[int, int] = {}+ for index in range(record.instance):+ offset = index * 6+ if offset + 6 > len(record.payload):+ break+ opid, value = struct.unpack_from("<HI", record.payload, offset)+ properties[opid & 0x3FFF] = int(value)+ return properties+++def _excel_client_anchor(payload: bytes) -> tuple[int, int, int, int] | None:+ """把 OfficeArtClientAnchorChart 转成起止行列坐标。"""++ if len(payload) < 18:+ return None+ start_col = struct.unpack_from("<H", payload, 2)[0]+ start_row = struct.unpack_from("<H", payload, 6)[0]+ end_col = struct.unpack_from("<H", payload, 10)[0]+ end_row = struct.unpack_from("<H", payload, 14)[0]+ return int(start_row), int(start_col), int(end_row), int(end_col)+++def _shape_from_container(+ record: OfficeArtRecord,+ *,+ charge: Callable[[], None] | None = None,+) -> OfficeArtShape | None:+ """从单个 SpContainer 提取 shape id、anchor、pib 与隐藏状态。"""++ shape_id: int | None = None+ anchor: tuple[int, int, int, int] | None = None+ properties: dict[int, int] = {}+ for child in iter_records(record.payload, charge=charge):+ if child.record_type == OFFICEART_FSP and len(child.payload) >= 4:+ shape_id = int(struct.unpack_from("<I", child.payload, 0)[0])+ elif child.record_type in {OFFICEART_FOPT, OFFICEART_TERTIARY_FOPT}:+ properties.update(_simple_properties(child))+ elif child.record_type == OFFICEART_CLIENT_ANCHOR:+ anchor = _excel_client_anchor(child.payload)+ hidden_flags = properties.get(FOPT_GROUP_SHAPE, 0)+ hidden = bool(hidden_flags & F_USE_HIDDEN and hidden_flags & F_HIDDEN)+ pib = properties.get(FOPT_PIB)+ if anchor is None and pib is None:+ return None+ return OfficeArtShape(shape_id=shape_id, anchor=anchor, pib=pib, hidden=hidden)+++def extract_excel_shapes(+ data: bytes,+ *,+ charge: Callable[[], None] | None = None,+) -> list[OfficeArtShape]:+ """按 drawing 顺序提取可与 Excel OBJ 一一绑定的形状。"""++ shapes: list[OfficeArtShape] = []+ for record in iter_descendants(data, charge=charge):+ if record.record_type != OFFICEART_SP_CONTAINER:+ continue+ shape = _shape_from_container(record, charge=charge)+ if shape is not None:+ shapes.append(shape)+ return shapes+++def decode_blip(record: OfficeArtRecord) -> OfficeImagePayload | None:+ """解码 JPEG、PNG、EMF 或 WMF BLIP,并限制矢量解压输出。"""++ instance = record.instance+ body = record.payload+ if record.record_type in {0xF01D, 0xF01E}:+ doubled = instance in {0x46B, 0x6E3, 0x6E1}+ start = (32 if doubled else 16) + 1+ if start >= len(body):+ return None+ data = body[start:]+ if len(data) > MAX_ENTRY_BYTES:+ raise LegacyOfficeResourceLimitError("bitmap BLIP exceeds max_entry_bytes")+ if record.record_type == 0xF01D:+ return OfficeImagePayload(data=data, extension="jpg", content_type="image/jpeg")+ return OfficeImagePayload(data=data, extension="png", content_type="image/png")++ if record.record_type not in {0xF01A, 0xF01B}:+ return None+ doubled = instance in ({0x3D5} if record.record_type == 0xF01A else {0x217})+ header_offset = 32 if doubled else 16+ if header_offset + 34 > len(body):+ return None+ declared_size = int(struct.unpack_from("<I", body, header_offset)[0])+ compressed_size = int(struct.unpack_from("<I", body, header_offset + 28)[0])+ compression = body[header_offset + 32]+ payload_start = header_offset + 34+ payload = body[payload_start : payload_start + compressed_size]+ if declared_size > MAX_ENTRY_BYTES:+ raise LegacyOfficeResourceLimitError("metafile BLIP exceeds max_entry_bytes")+ if compression == 0:+ try:+ inflater = zlib.decompressobj(-zlib.MAX_WBITS)+ data = inflater.decompress(payload, MAX_ENTRY_BYTES + 1)+ data += inflater.flush(MAX_ENTRY_BYTES + 1 - len(data))+ except zlib.error:+ return None+ if len(data) > MAX_ENTRY_BYTES or not inflater.eof:+ raise LegacyOfficeResourceLimitError(+ "metafile BLIP decompression exceeded its limit"+ )+ else:+ data = payload+ if record.record_type == 0xF01A:+ return OfficeImagePayload(data=data, extension="emf", content_type="image/emf")+ if data.startswith(b"\xd7\xcd\xc6\x9a") and len(data) >= 22:+ data = data[22:]+ return OfficeImagePayload(data=data, extension="wmf", content_type="image/wmf")+++def _decode_bse_body(+ body: bytes,+ *,+ charge: Callable[[], None] | None = None,+) -> OfficeImagePayload | None:+ """从 FBSE body 的可选内嵌 BLIP 中恢复图片。"""++ if len(body) < 36:+ return None+ inner_offset = 36 + int(body[33])+ inner = record_at(body, inner_offset, charge=charge)+ return decode_blip(inner) if inner is not None else None+++def decode_bstore(+ data: bytes,+ *,+ charge: Callable[[], None] | None = None,+) -> dict[int, OfficeImagePayload]:+ """按一基 BSE 序号解码 drawing group 中的图片资源。"""++ bse_records = [+ record+ for record in iter_descendants(data, charge=charge)+ if record.record_type == OFFICEART_BSE+ ]+ result: dict[int, OfficeImagePayload] = {}+ asset_total = 0+ for index, bse in enumerate(bse_records[:MAX_PICTURE_RECORDS], start=1):+ decoded = _decode_bse_body(bse.payload, charge=charge)+ if decoded is None:+ continue+ asset_total += len(decoded.data)+ if asset_total > MAX_ASSET_TOTAL_BYTES:+ raise LegacyOfficeResourceLimitError(+ f"embedded assets exceed max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}"+ )+ result[index] = decoded+ if len(bse_records) > MAX_PICTURE_RECORDS:+ logger.warning(+ "LEGACY_OFFICE_PICTURE_LIMIT: ignored BSE records after {}",+ MAX_PICTURE_RECORDS,+ )+ return resultdiff --git a/mineru/model/flash/legacy_office/ole.py b/mineru/model/flash/legacy_office/ole.pynew file mode 100644index 00000000..30cde102--- /dev/null+++ b/mineru/model/flash/legacy_office/ole.py@@ -0,0 +1,113 @@+# Copyright (c) Opendatalab. All rights reserved.++"""基于 olefile 的有界 OLE2/CFB 只读包装。"""++from __future__ import annotations++from io import BytesIO+from typing import Any++import olefile # type: ignore[reportMissingModuleSource]++from .errors import (+ LegacyOfficeMalformedError,+ LegacyOfficeMissingPartError,+ LegacyOfficeResourceLimitError,+)+from .limits import MAX_ENTRY_BYTES, MAX_TOTAL_BYTES+++class BoundedOleReader:+ """限制输入、单流及累计读取量,并提供大小写无关的 stream 访问。"""++ def __init__(self, file_bytes: bytes) -> None:+ """校验输入大小并打开内存中的 OLE2 容器。"""++ if not isinstance(file_bytes, bytes):+ raise TypeError("legacy Office input must be bytes")+ if len(file_bytes) > MAX_TOTAL_BYTES:+ raise LegacyOfficeResourceLimitError(+ f"input exceeds max_total_bytes={MAX_TOTAL_BYTES}"+ )+ try:+ self._ole: Any = olefile.OleFileIO(BytesIO(file_bytes), raise_defects=olefile.DEFECT_FATAL)+ except Exception as exc:+ raise LegacyOfficeMalformedError(f"not a readable OLE2 compound file: {exc}") from exc+ self._total_read = 0+ self._stream_names = self._build_stream_name_map()++ def _build_stream_name_map(self) -> dict[str, tuple[str, ...]]:+ """建立大小写无关的完整 stream 名称索引。"""++ names: dict[str, tuple[str, ...]] = {}+ try:+ for parts in self._ole.listdir(streams=True, storages=False):+ normalized = tuple(str(part) for part in parts)+ names["/".join(normalized).casefold()] = normalized+ except Exception as exc:+ self.close()+ raise LegacyOfficeMalformedError(f"cannot enumerate OLE streams: {exc}") from exc+ return names++ def has_stream(self, name: str) -> bool:+ """返回容器是否含有指定 stream。"""++ return name.casefold() in self._stream_names++ def read_stream(self, name: str, *, required: bool = True) -> bytes:+ """有界读取指定 stream;可选 stream 不存在时返回空字节。"""++ parts = self._stream_names.get(name.casefold())+ if parts is None:+ if required:+ raise LegacyOfficeMissingPartError(f"missing required OLE stream: {name}")+ return b""+ try:+ size = int(self._ole.get_size(list(parts)))+ except Exception as exc:+ raise LegacyOfficeMalformedError(f"cannot read OLE stream size: {name}: {exc}") from exc+ if size > MAX_ENTRY_BYTES:+ raise LegacyOfficeResourceLimitError(+ f"stream {name!r} exceeds max_entry_bytes={MAX_ENTRY_BYTES}"+ )+ if self._total_read + size > MAX_TOTAL_BYTES:+ raise LegacyOfficeResourceLimitError(+ f"OLE streams exceed max_total_bytes={MAX_TOTAL_BYTES}"+ )+ try:+ with self._ole.openstream(list(parts)) as stream:+ payload = stream.read(MAX_ENTRY_BYTES + 1)+ except Exception as exc:+ raise LegacyOfficeMalformedError(f"cannot read OLE stream {name!r}: {exc}") from exc+ if len(payload) > MAX_ENTRY_BYTES:+ raise LegacyOfficeResourceLimitError(+ f"stream {name!r} exceeds max_entry_bytes={MAX_ENTRY_BYTES}"+ )+ self._total_read += len(payload)+ return payload++ def metadata(self) -> Any | None:+ """尽力读取 SummaryInformation,失败时不影响正文解析。"""++ try:+ return self._ole.get_metadata()+ except Exception:+ return None++ def close(self) -> None:+ """关闭底层 olefile 句柄。"""++ ole = getattr(self, "_ole", None)+ if ole is not None:+ ole.close()+ self._ole = None++ def __enter__(self) -> BoundedOleReader:+ """返回当前有界读取器。"""++ return self++ def __exit__(self, *_args: object) -> None:+ """离开上下文时关闭底层句柄。"""++ self.close()diff --git a/mineru/model/flash/model.py b/mineru/model/flash/model.pyindex 6cb9ef12..00ed38ed 100644--- a/mineru/model/flash/model.py+++ b/mineru/model/flash/model.py@@ -48,6 +48,34 @@ class PptxModel:return converter.pages+class PptModel:+ """将 PowerPoint 97–2003 Converter 包装为无状态模型。"""++ def predict(self, file_binary: BinaryIO) -> list[list[dict[str, Any]]]:+ """转换调用方持有的 PPT 二进制流,并返回逐幻灯片 model-list。"""++ # 延迟加载旧版 PPT 解析器,避免其他格式提前加载 olefile。+ from .ppt.ppt_converter import PptConverter++ converter = PptConverter()+ converter.convert(file_binary)+ return converter.pages+++class XlsModel:+ """将 Excel 97–2003 Converter 包装为无状态模型。"""++ def predict(self, file_binary: BinaryIO) -> list[list[dict[str, Any]]]:+ """转换调用方持有的 XLS 二进制流,并返回逐工作表 model-list。"""++ # 延迟加载旧版 XLS 解析器,避免其他格式提前加载 olefile/openpyxl。+ from .xls.xls_converter import XlsConverter++ converter = XlsConverter()+ converter.convert(file_binary)+ return converter.pages++class XlsxModel:"""将 XLSX Converter 包装为无状态模型。"""diff --git a/mineru/model/flash/ppt/__init__.py b/mineru/model/flash/ppt/__init__.pynew file mode 100644index 00000000..40ec1201--- /dev/null+++ b/mineru/model/flash/ppt/__init__.py@@ -0,0 +1,4 @@+# Copyright (c) Opendatalab. All rights reserved.++"""PowerPoint 97–2003 二进制解析实现。"""+diff --git a/mineru/model/flash/ppt/models.py b/mineru/model/flash/ppt/models.pynew file mode 100644index 00000000..9a3bc5d8--- /dev/null+++ b/mineru/model/flash/ppt/models.py@@ -0,0 +1,99 @@+# Copyright (c) Opendatalab. All rights reserved.++"""旧版 PPT 解析阶段使用的内部语义模型。"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Literal, TypeAlias+++@dataclass(frozen=True, slots=True)+class PptTextRun:+ """一个样式与超链接均已解析的文本片段。"""++ text: str+ bold: bool = False+ italic: bool = False+ underline: bool = False+ strike: bool = False+ baseline: int | None = None+ hyperlink: str | None = None+++@dataclass(frozen=True, slots=True)+class PptParagraph:+ """一个段落及其列表层级和编号属性。"""++ runs: tuple[PptTextRun, ...]+ depth: int = 0+ list_kind: Literal["ordered", "unordered"] | None = None+ start: int | None = None+ pp9rt: int = 0+++@dataclass(frozen=True, slots=True)+class PptTextElement:+ """带幻灯片坐标的文本形状。"""++ paragraphs: tuple[PptParagraph, ...]+ text_type: int+ bbox: tuple[float, float, float, float]+ order: int+ shape_offset: int+ is_placeholder: bool = False+++@dataclass(frozen=True, slots=True)+class PptImageElement:+ """已经绑定到具体幻灯片形状的图片。"""++ image_base64: str+ bbox: tuple[float, float, float, float]+ order: int+ shape_offset: int+++@dataclass(frozen=True, slots=True)+class PptTableCell:+ """表格原点单元格及其跨行跨列范围。"""++ row: int+ col: int+ row_span: int+ col_span: int+ paragraphs: tuple[PptParagraph, ...]+++@dataclass(frozen=True, slots=True)+class PptTableElement:+ """由 OfficeArt 表格组重建出的规则网格。"""++ rows: int+ cols: int+ cells: tuple[PptTableCell, ...]+ bbox: tuple[float, float, float, float]+ order: int+ shape_offsets: frozenset[tuple[int, ...]]+++PptSlideElement: TypeAlias = PptTextElement | PptImageElement | PptTableElement+++@dataclass(slots=True)+class PptSlide:+ """一张幻灯片的语义内容与备注。"""++ slide_id: int | None+ elements: list[PptSlideElement] = field(default_factory=list)+ notes: list[PptParagraph] = field(default_factory=list)+ hidden: bool = False+++@dataclass(slots=True)+class PptPresentation:+ """旧版 PPT 的分页内部表示。"""++ slides: list[PptSlide]+ width: int = 5760+ height: int = 4320diff --git a/mineru/model/flash/ppt/parser.py b/mineru/model/flash/ppt/parser.pynew file mode 100644index 00000000..c4619bc9--- /dev/null+++ b/mineru/model/flash/ppt/parser.py@@ -0,0 +1,1719 @@+# Copyright (c) Opendatalab. All rights reserved.++"""PowerPoint 97–2003 二进制文档的分页语义解析器。"""++from __future__ import annotations++from dataclasses import dataclass, replace+import struct+from typing import Iterable+import unicodedata+from urllib.parse import urlparse++from loguru import logger++from mineru.model.flash.legacy_office import (+ LegacyOfficeEncryptedError,+ LegacyOfficeMalformedError,+ LegacyOfficeResourceLimitError,+)+from mineru.model.flash.legacy_office.limits import (+ MAX_ASSET_TOTAL_BYTES,+ MAX_GRID_SLOTS,+ MAX_PICTURE_RECORDS,+ MAX_USER_EDIT_CHAIN,+)+from mineru.model.flash.legacy_office.officeart import (+ OfficeArtRecord,+ OfficeImagePayload,+ decode_blip as decode_officeart_blip,+)+from mineru.model.flash.office.image import serialize_office_image++from .models import (+ PptImageElement,+ PptParagraph,+ PptPresentation,+ PptSlide,+ PptTableCell,+ PptTableElement,+ PptTextElement,+ PptTextRun,+)+from .records import (+ CONTAINER_VERSION,+ PptRecord,+ RecordBudget,+ get_i16,+ get_u16,+ get_u32,+ iter_descendants,+ iter_records,+ record_at,+ utf16_text,+)+from .style_text import CharacterRun, MasterLevel, ParagraphRun, StyleRuns, parse_master_style, parse_style_text++# MS-PPT records.+RT_DOCUMENT = 0x03E8+RT_DOCUMENT_ATOM = 0x03E9+RT_SLIDE = 0x03EE+RT_SLIDE_ATOM = 0x03EF+RT_NOTES = 0x03F0+RT_NOTES_ATOM = 0x03F1+RT_SLIDE_PERSIST_ATOM = 0x03F3+RT_MAIN_MASTER = 0x03F8+RT_SLIDE_SHOW_SLIDE_INFO_ATOM = 0x03F9+RT_TEXT_HEADER_ATOM = 0x0F9F+RT_TEXT_CHARS_ATOM = 0x0FA0+RT_STYLE_TEXT_PROP_ATOM = 0x0FA1+RT_TEXT_MASTER_STYLE_ATOM = 0x0FA3+RT_TEXT_BYTES_ATOM = 0x0FA8+RT_CSTRING = 0x0FBA+RT_TEXT_INTERACTIVE_INFO_ATOM = 0x0FDF+RT_EXTERNAL_HYPERLINK = 0x0FD7+RT_EXTERNAL_HYPERLINK_ATOM = 0x0FD3+RT_SLIDE_LIST_WITH_TEXT = 0x0FF0+RT_INTERACTIVE_INFO = 0x0FF2+RT_INTERACTIVE_INFO_ATOM = 0x0FF3+RT_USER_EDIT_ATOM = 0x0FF5+RT_OUTLINE_TEXT_REF_ATOM = 0x0F9E+RT_PERSIST_DIRECTORY_ATOM = 0x1772+RT_CRYPT_SESSION10_CONTAINER = 0x2F14++# OfficeArt records and properties.+RT_OFFICEART_DGG_CONTAINER = 0xF000+RT_OFFICEART_BSTORE_CONTAINER = 0xF001+RT_OFFICEART_SPGR_CONTAINER = 0xF003+RT_OFFICEART_SP_CONTAINER = 0xF004+RT_OFFICEART_BSE = 0xF007+RT_OFFICEART_FSPGR = 0xF009+RT_OFFICEART_FSP = 0xF00A+RT_OFFICEART_FOPT = 0xF00B+RT_OFFICEART_CLIENT_TEXTBOX = 0xF00D+RT_OFFICEART_CHILD_ANCHOR = 0xF00F+RT_OFFICEART_CLIENT_ANCHOR = 0xF010+RT_OFFICEART_CLIENT_DATA = 0xF011+RT_OFFICEART_TERTIARY_FOPT = 0xF122+RT_OE_PLACEHOLDER_ATOM = 0x0BC3++FOPT_PIB = 0x0104+FOPT_TABLE_PROPERTIES = 0x039F+FOPT_TABLE_ROW_PROPERTIES = 0x03A0++DEFAULT_SLIDE_WIDTH = 5760+DEFAULT_SLIDE_HEIGHT = 4320+_ALLOWED_LINK_SCHEMES = frozenset({"http", "https", "mailto"})+++@dataclass(frozen=True, slots=True)+class _TextContent:+ """一个 TextHeaderAtom 对应的完整段落集合。"""++ paragraphs: tuple[PptParagraph, ...]+ text_type: int+++@dataclass(frozen=True, slots=True)+class _PersistLayout:+ """最新 UserEdit 解析出的文档与 persist 映射。"""++ document: PptRecord+ persist: dict[int, int]+ recovered: bool = False+++@dataclass(frozen=True, slots=True)+class _GroupSpace:+ """嵌套 OfficeArt group 到幻灯片坐标的线性映射。"""++ coord_left: int+ coord_top: int+ coord_right: int+ coord_bottom: int+ abs_left: float+ abs_top: float+ abs_right: float+ abs_bottom: float+++@dataclass(frozen=True, slots=True)+class _ShapeInfo:+ """带唯一遍历路径、坐标和 z-order 的 OfficeArt shape。"""++ key: tuple[int, ...]+ record: PptRecord+ space: _GroupSpace | None+ bbox: tuple[float, float, float, float]+ order: int+ group_key: tuple[int, ...] | None+++@dataclass(frozen=True, slots=True)+class _TableGroup:+ """一个由 fIsTable 标记的 group 及其所有叶子 shape。"""++ key: tuple[int, ...]+ group_shape: PptRecord+ shapes: tuple[_ShapeInfo, ...]+ order: int+ authoritative: bool+++_ImagePayload = OfficeImagePayload+++@dataclass(frozen=True, slots=True)+class _NumberingStyle:+ """一个 pp9rt 槽位的自动编号覆盖。"""++ enabled: bool | None+ start: int | None+++@dataclass(frozen=True, slots=True)+class _ShapeCollection:+ """一次遍历得到的叶子 shape 与表格 group。"""++ shapes: tuple[_ShapeInfo, ...]+ table_groups: tuple[_TableGroup, ...]+++def _direct_children(record: PptRecord, budget: RecordBudget) -> list[PptRecord]:+ """返回容器的直接子记录,普通 atom 返回空列表。"""++ if record.version != CONTAINER_VERSION:+ return []+ return list(iter_records(record.payload, budget=budget))+++def _find_latest_user_edit_offset(data: bytes, current_user: bytes) -> int | None:+ """从 Current User stream 读取最新 UserEditAtom 偏移。"""++ offset = get_u32(current_user, 16)+ return int(offset) if offset else None+++def _merge_persist_directory(+ mapping: dict[int, int],+ payload: bytes,+) -> None:+ """合并一个 PersistDirectoryAtom;调用顺序保证较新记录优先。"""++ cursor = 0+ while cursor < len(payload):+ head = get_u32(payload, cursor)+ if head is None:+ raise LegacyOfficeMalformedError("PowerPoint persist directory is truncated")+ cursor += 4+ first_id = head & 0x000F_FFFF+ count = head >> 20+ if count <= 0 or cursor + count * 4 > len(payload):+ raise LegacyOfficeMalformedError("PowerPoint persist directory entry is invalid")+ for index in range(count):+ offset = get_u32(payload, cursor)+ if offset is None:+ raise LegacyOfficeMalformedError("PowerPoint persist offset is truncated")+ mapping.setdefault(first_id + index, int(offset))+ cursor += 4+++def _latest_document_fallback(data: bytes, budget: RecordBudget) -> PptRecord | None:+ """在 persist 链损坏时选择最后一个完整 DocumentContainer。"""++ candidates = [+ record+ for record in iter_records(data, budget=budget)+ if record.record_type == RT_DOCUMENT and record.version == CONTAINER_VERSION+ ]+ return candidates[-1] if candidates else None+++def _locate_document(+ data: bytes,+ current_user: bytes,+ budget: RecordBudget,+) -> _PersistLayout:+ """解析最新 UserEdit 链,失败时回退到顶层 DocumentContainer。"""++ edit_offset = _find_latest_user_edit_offset(data, current_user)+ persist: dict[int, int] = {}+ document_persist_id: int | None = None+ seen: set[int] = set()+ try:+ for _ in range(MAX_USER_EDIT_CHAIN):+ if not edit_offset:+ break+ if edit_offset in seen:+ raise LegacyOfficeMalformedError("PowerPoint UserEdit chain is cyclic")+ seen.add(edit_offset)+ edit = record_at(data, edit_offset, strict=True, budget=budget)+ if edit is None or edit.record_type != RT_USER_EDIT_ATOM:+ raise LegacyOfficeMalformedError("PowerPoint UserEditAtom is invalid")+ if document_persist_id is None:+ document_persist_id = get_u32(edit.payload, 16)+ directory_offset = get_u32(edit.payload, 12)+ if directory_offset is None:+ raise LegacyOfficeMalformedError("PowerPoint persist directory offset is missing")+ directory = record_at(data, directory_offset, strict=True, budget=budget)+ if directory is None or directory.record_type != RT_PERSIST_DIRECTORY_ATOM:+ raise LegacyOfficeMalformedError("PowerPoint PersistDirectoryAtom is invalid")+ _merge_persist_directory(persist, directory.payload)+ previous = get_u32(edit.payload, 8)+ if previous == edit_offset:+ raise LegacyOfficeMalformedError("PowerPoint UserEdit chain points to itself")+ edit_offset = int(previous or 0)+ else:+ raise LegacyOfficeResourceLimitError(+ f"UserEdit chain exceeds max_user_edit_chain={MAX_USER_EDIT_CHAIN}"+ )+ if document_persist_id is not None:+ document_offset = persist.get(int(document_persist_id))+ if document_offset is not None:+ document = record_at(data, document_offset, strict=True, budget=budget)+ if document is not None and document.record_type == RT_DOCUMENT:+ return _PersistLayout(document=document, persist=persist)+ except (LegacyOfficeMalformedError, LegacyOfficeResourceLimitError) as exc:+ if isinstance(exc, LegacyOfficeResourceLimitError):+ raise+ logger.warning(f"PPT_PERSIST_RECOVERY: {exc}")++ document = _latest_document_fallback(data, budget)+ if document is None:+ raise LegacyOfficeMalformedError("PowerPoint DocumentContainer is missing")+ # 顶层 persist 记录仍可帮助恢复同一保存版本中的 slide。+ recovered_persist: dict[int, int] = {}+ for record in iter_records(data, budget=budget):+ if record.record_type == RT_PERSIST_DIRECTORY_ATOM:+ try:+ _merge_persist_directory(recovered_persist, record.payload)+ except LegacyOfficeMalformedError:+ continue+ return _PersistLayout(document=document, persist=recovered_persist, recovered=True)+++def _slide_entries(document: PptRecord, budget: RecordBudget) -> list[tuple[int, int]]:+ """按 SlideListWithText 的保存顺序返回 persist 引用与稳定 slide id。"""++ entries: list[tuple[int, int]] = []+ for container in iter_descendants(document, budget=budget):+ if container.record_type != RT_SLIDE_LIST_WITH_TEXT or container.instance != 0:+ continue+ for record in iter_records(container.payload, budget=budget):+ if record.record_type != RT_SLIDE_PERSIST_ATOM:+ continue+ reference = get_u32(record.payload, 0)+ slide_id = get_u32(record.payload, 12)+ if reference:+ entries.append((int(reference), int(slide_id or 0)))+ break+ return entries+++def _master_entries(document: PptRecord, budget: RecordBudget) -> list[tuple[int, int]]:+ """返回 master persist 引用与 master id。"""++ entries: list[tuple[int, int]] = []+ for container in iter_descendants(document, budget=budget):+ if container.record_type != RT_SLIDE_LIST_WITH_TEXT or container.instance != 1:+ continue+ for record in iter_records(container.payload, budget=budget):+ if record.record_type != RT_SLIDE_PERSIST_ATOM:+ continue+ reference = get_u32(record.payload, 0)+ master_id = get_u32(record.payload, 12)+ if reference and master_id:+ entries.append((int(reference), int(master_id)))+ break+ return entries+++def _notes_entries(document: PptRecord, budget: RecordBudget) -> list[int]:+ """返回 notes list 中的 persist 引用。"""++ references: list[int] = []+ for container in iter_descendants(document, budget=budget):+ if container.record_type != RT_SLIDE_LIST_WITH_TEXT or container.instance != 2:+ continue+ for record in iter_records(container.payload, budget=budget):+ if record.record_type == RT_SLIDE_PERSIST_ATOM:+ reference = get_u32(record.payload, 0)+ if reference:+ references.append(int(reference))+ break+ return references+++def _slide_master_id(slide: PptRecord, budget: RecordBudget) -> int | None:+ """读取 SlideAtom.masterIdRef。"""++ for child in iter_descendants(slide, budget=budget):+ if child.record_type == RT_SLIDE_ATOM:+ master_id = get_u32(child.payload, 12)+ return int(master_id) if master_id else None+ return None+++def _presentation_size(document: PptRecord, budget: RecordBudget) -> tuple[int, int]:+ """从 DocumentAtom 读取页面 master units 尺寸。"""++ for child in iter_descendants(document, budget=budget):+ if child.record_type != RT_DOCUMENT_ATOM or len(child.payload) < 8:+ continue+ width = get_u32(child.payload, 0)+ height = get_u32(child.payload, 4)+ if width and height and width < 100_000 and height < 100_000:+ return int(width), int(height)+ return DEFAULT_SLIDE_WIDTH, DEFAULT_SLIDE_HEIGHT+++def _decode_text_atom(record: PptRecord) -> str | None:+ """解码 TextCharsAtom 或 TextBytesAtom。"""++ if record.record_type == RT_TEXT_CHARS_ATOM:+ return utf16_text(record.payload)+ if record.record_type == RT_TEXT_BYTES_ATOM:+ return record.payload.decode("cp1252", "replace").rstrip("\x00")+ return None+++def _safe_hyperlink_target(target: str) -> str | None:+ """仅允许公开输出中可安全表达的外部链接 scheme。"""++ normalized = target.strip()+ if not normalized:+ return None+ scheme = urlparse(normalized).scheme.lower()+ return normalized if scheme in _ALLOWED_LINK_SCHEMES else None+++def _hyperlink_targets(document: PptRecord, budget: RecordBudget) -> dict[int, str]:+ """建立 ExHyperlinkId 到安全外链目标的映射。"""++ result: dict[int, str] = {}+ for container in iter_descendants(document, budget=budget):+ if container.record_type != RT_EXTERNAL_HYPERLINK or container.version != CONTAINER_VERSION:+ continue+ link_id = None+ strings: list[str] = []+ for child in iter_records(container.payload, budget=budget):+ if child.record_type == RT_EXTERNAL_HYPERLINK_ATOM:+ link_id = get_u32(child.payload, 0)+ elif child.record_type == RT_CSTRING:+ strings.append(utf16_text(child.payload))+ if link_id is None or not strings:+ continue+ safe_target = _safe_hyperlink_target(strings[-1])+ if safe_target is None:+ logger.warning(+ f"PPT_UNSAFE_HYPERLINK: hyperlink id={link_id} was downgraded"+ )+ continue+ result[int(link_id)] = safe_target+ return result+++def _interactive_spans(+ related_records: Iterable[PptRecord],+ hyperlinks: dict[int, str],+ budget: RecordBudget,+) -> list[tuple[int, int, str]]:+ """解析一段文本之后的 InteractiveInfo 与 UTF-16 范围。"""++ flattened: list[PptRecord] = []+ for record in related_records:+ flattened.append(record)+ if record.version == CONTAINER_VERSION:+ flattened.extend(iter_descendants(record, budget=budget))+ spans: list[tuple[int, int, str]] = []+ pending_id: int | None = None+ for record in flattened:+ if record.record_type == RT_INTERACTIVE_INFO_ATOM:+ pending_id = get_u32(record.payload, 4)+ continue+ if record.record_type != RT_TEXT_INTERACTIVE_INFO_ATOM or pending_id is None:+ continue+ start = get_u32(record.payload, 0)+ end = get_u32(record.payload, 4)+ target = hyperlinks.get(int(pending_id))+ if start is not None and end is not None and target and end > start:+ spans.append((int(start), int(end), target))+ pending_id = None+ return spans+++def _utf16_width(text: str) -> int:+ """返回字符串占用的 UTF-16 code unit 数。"""++ return len(text.encode("utf-16-le", "surrogatepass")) // 2+++def _master_level(levels: list[MasterLevel], depth: int) -> MasterLevel:+ """按深度取得母版默认值,超界时回退最后一个可用层级。"""++ if not levels:+ return MasterLevel()+ return levels[min(max(depth, 0), len(levels) - 1)]+++def _paragraph_run_at(runs: list[ParagraphRun], offset: int) -> ParagraphRun:+ """返回覆盖指定 UTF-16 偏移的段落 run。"""++ cursor = 0+ for run in runs:+ if cursor <= offset < cursor + run.count:+ return run+ cursor += run.count+ return ParagraphRun(count=0, depth=0)+++def _character_run_at(runs: list[CharacterRun], offset: int) -> CharacterRun:+ """返回覆盖指定 UTF-16 偏移的字符 run。"""++ cursor = 0+ for run in runs:+ if cursor <= offset < cursor + run.count:+ return run+ cursor += run.count+ return CharacterRun(count=0)+++def _hyperlink_at(spans: list[tuple[int, int, str]], offset: int) -> str | None:+ """返回覆盖当前 UTF-16 偏移的超链接目标。"""++ return next((target for start, end, target in spans if start <= offset < end), None)+++def _resolve_run(+ text: str,+ explicit: CharacterRun,+ master: MasterLevel,+ hyperlink: str | None,+) -> PptTextRun:+ """把字符异常属性覆盖到母版默认值上。"""++ return PptTextRun(+ text=text,+ bold=explicit.bold if explicit.bold is not None else bool(master.bold),+ italic=explicit.italic if explicit.italic is not None else bool(master.italic),+ underline=(+ explicit.underline+ if explicit.underline is not None+ else bool(master.underline) or hyperlink is not None+ ),+ strike=bool(explicit.strike),+ baseline=explicit.baseline if explicit.baseline is not None else master.baseline,+ hyperlink=hyperlink,+ )+++def _flush_text_run(+ output: list[PptTextRun],+ text: str,+ style: PptTextRun | None,+) -> None:+ """追加非空文本,并合并相邻同样式 run。"""++ if not text or style is None:+ return+ candidate = replace(style, text=text)+ if output and replace(output[-1], text="") == replace(candidate, text=""):+ output[-1] = replace(output[-1], text=f"{output[-1].text}{text}")+ return+ output.append(candidate)+++def _build_paragraphs(+ text: str,+ styles: StyleRuns,+ master_levels: list[MasterLevel],+ hyperlinks: list[tuple[int, int, str]],+) -> tuple[PptParagraph, ...]:+ """把 UTF-16 属性范围转换为带样式 run 的段落。"""++ paragraphs: list[PptParagraph] = []+ current_runs: list[PptTextRun] = []+ run_text: list[str] = []+ active_style: PptTextRun | None = None+ utf16_offset = 0+ paragraph_start = 0++ def flush_run() -> None:+ """把当前相同样式字符提交到段落。"""++ nonlocal run_text+ _flush_text_run(current_runs, "".join(run_text), active_style)+ run_text = []++ def flush_paragraph() -> None:+ """完成当前段落并解析列表属性。"""++ flush_run()+ paragraph_style = _paragraph_run_at(styles.paragraphs, paragraph_start)+ character_style = _character_run_at(styles.characters, paragraph_start)+ master = _master_level(master_levels, paragraph_style.depth)+ bullet = paragraph_style.bullet if paragraph_style.bullet is not None else bool(master.bullet)+ visible = any(run.text.strip() for run in current_runs)+ if visible:+ paragraphs.append(+ PptParagraph(+ runs=tuple(current_runs),+ depth=max(0, int(paragraph_style.depth)),+ list_kind="unordered" if bullet else None,+ pp9rt=character_style.pp9rt,+ )+ )+ current_runs.clear()++ for character in text:+ paragraph_style = _paragraph_run_at(styles.paragraphs, utf16_offset)+ master = _master_level(master_levels, paragraph_style.depth)+ explicit = _character_run_at(styles.characters, utf16_offset)+ hyperlink = _hyperlink_at(hyperlinks, utf16_offset)+ style = _resolve_run("", explicit, master, hyperlink)+ if active_style is None or replace(active_style, text="") != replace(style, text=""):+ flush_run()+ active_style = style+ if character == "\r":+ flush_paragraph()+ paragraph_start = utf16_offset + 1+ active_style = None+ elif character in {"\x0b", "\n"}:+ run_text.append("\n")+ elif not unicodedata.category(character).startswith("C") or character == "\t":+ run_text.append(character)+ utf16_offset += _utf16_width(character)+ if run_text or current_runs:+ flush_paragraph()+ return tuple(paragraphs)+++def _parse_text_contents(+ records: list[PptRecord],+ master_styles: dict[int, list[MasterLevel]],+ hyperlinks: dict[int, str],+ budget: RecordBudget,+) -> list[_TextContent]:+ """从一组相邻记录中解析所有文本形状内容。"""++ result: list[_TextContent] = []+ text_type = 4+ for index, record in enumerate(records):+ if record.record_type == RT_TEXT_HEADER_ATOM:+ text_type = int(get_u32(record.payload, 0) or 4)+ continue+ text = _decode_text_atom(record)+ if text is None:+ continue+ tail = records[index + 1 :]+ next_text_index = next(+ (+ position+ for position, candidate in enumerate(tail)+ if candidate.record_type+ in {RT_TEXT_CHARS_ATOM, RT_TEXT_BYTES_ATOM, RT_SLIDE_PERSIST_ATOM}+ ),+ len(tail),+ )+ related = tail[:next_text_index]+ style_atom = next(+ (candidate for candidate in related if candidate.record_type == RT_STYLE_TEXT_PROP_ATOM),+ None,+ )+ styles = (+ parse_style_text(style_atom.payload, _utf16_width(text))+ if style_atom is not None+ else StyleRuns()+ )+ spans = _interactive_spans(related, hyperlinks, budget)+ paragraphs = _build_paragraphs(+ text,+ styles,+ master_styles.get(text_type, []),+ spans,+ )+ result.append(_TextContent(paragraphs=paragraphs, text_type=text_type))+ return result+++def _external_text_records(+ document: PptRecord,+ budget: RecordBudget,+) -> dict[int, list[PptRecord]]:+ """按 slide persist 引用收集 SlideListWithText 中的外置文本记录。"""++ grouped: dict[int, list[PptRecord]] = {}+ for container in iter_descendants(document, budget=budget):+ if container.record_type != RT_SLIDE_LIST_WITH_TEXT or container.instance != 0:+ continue+ current_reference: int | None = None+ for record in iter_records(container.payload, budget=budget):+ if record.record_type == RT_SLIDE_PERSIST_ATOM:+ reference = get_u32(record.payload, 0)+ current_reference = int(reference) if reference else None+ if current_reference is not None:+ grouped.setdefault(current_reference, [])+ continue+ if current_reference is not None:+ grouped[current_reference].append(record)+ break+ return grouped+++def _master_styles(record: PptRecord, budget: RecordBudget) -> dict[int, list[MasterLevel]]:+ """解析一个 master container 的逐文本类型默认样式。"""++ result: dict[int, list[MasterLevel]] = {}+ for child in iter_descendants(record, budget=budget):+ if child.record_type != RT_TEXT_MASTER_STYLE_ATOM:+ continue+ result.setdefault(+ int(child.instance),+ parse_master_style(child.payload, int(child.instance)),+ )+ return result+++def _collect_masters(+ layout: _PersistLayout,+ data: bytes,+ budget: RecordBudget,+) -> tuple[dict[int, tuple[PptRecord, dict[int, list[MasterLevel]]]], tuple[PptRecord, dict[int, list[MasterLevel]]] | None]:+ """按 master id 建立容器与样式映射,并返回确定性 fallback。"""++ masters: dict[int, tuple[PptRecord, dict[int, list[MasterLevel]]]] = {}+ for reference, master_id in _master_entries(layout.document, budget):+ offset = layout.persist.get(reference)+ if offset is None:+ continue+ record = record_at(data, offset, budget=budget)+ if record is None or record.record_type not in {RT_MAIN_MASTER, RT_SLIDE}:+ continue+ masters.setdefault(master_id, (record, _master_styles(record, budget)))++ if not masters:+ for root in iter_records(data, budget=budget):+ if root.record_type != RT_MAIN_MASTER:+ continue+ masters.setdefault(0, (root, _master_styles(root, budget)))+ fallback = next(iter(masters.values()), None)+ return masters, fallback+++def _fopt_properties(record: PptRecord) -> dict[int, int]:+ """读取 OfficeArt FOPT 的简单属性,重复属性以后者覆盖。"""++ count = int(record.instance)+ properties: dict[int, int] = {}+ for index in range(count):+ offset = index * 6+ if offset + 6 > len(record.payload):+ break+ opid, value = struct.unpack_from("<HI", record.payload, offset)+ properties[opid & 0x3FFF] = int(value)+ return properties+++def _fopt_complex_properties(record: PptRecord) -> dict[int, bytes]:+ """读取 OfficeArt FOPT 中紧随属性数组的复杂载荷。"""++ count = int(record.instance)+ cursor = count * 6+ result: dict[int, bytes] = {}+ entries: list[tuple[int, int, bool]] = []+ for index in range(count):+ offset = index * 6+ if offset + 6 > len(record.payload):+ break+ opid, value = struct.unpack_from("<HI", record.payload, offset)+ entries.append((opid & 0x3FFF, int(value), bool(opid & 0x8000)))+ for property_id, size, is_complex in entries:+ if not is_complex:+ continue+ end = cursor + size+ if size < 0 or end < cursor or end > len(record.payload):+ break+ result[property_id] = record.payload[cursor:end]+ cursor = end+ return result+++def _shape_properties(shape: PptRecord, budget: RecordBudget) -> dict[int, int]:+ """合并 shape 的 primary 与 tertiary FOPT 属性。"""++ properties: dict[int, int] = {}+ for child in _direct_children(shape, budget):+ if child.record_type in {RT_OFFICEART_FOPT, RT_OFFICEART_TERTIARY_FOPT}:+ properties.update(_fopt_properties(child))+ return properties+++def _shape_complex_properties(shape: PptRecord, budget: RecordBudget) -> dict[int, bytes]:+ """合并 shape 的复杂 FOPT 属性。"""++ properties: dict[int, bytes] = {}+ for child in _direct_children(shape, budget):+ if child.record_type in {RT_OFFICEART_FOPT, RT_OFFICEART_TERTIARY_FOPT}:+ properties.update(_fopt_complex_properties(child))+ return properties+++def _shape_type(shape: PptRecord, budget: RecordBudget) -> int | None:+ """返回 OfficeArtFSP header 中的 MSOSPT 类型。"""++ for child in _direct_children(shape, budget):+ if child.record_type == RT_OFFICEART_FSP:+ return int(child.instance)+ return None+++def _is_background_shape(shape: PptRecord, budget: RecordBudget) -> bool:+ """判断 FSP 标志是否把 shape 标记为背景。"""++ for child in _direct_children(shape, budget):+ if child.record_type != RT_OFFICEART_FSP or len(child.payload) < 8:+ continue+ return bool(int(get_u32(child.payload, 4) or 0) & 0x0000_0400)+ return False+++def _is_placeholder(shape: PptRecord, budget: RecordBudget) -> bool:+ """判断 shape 的 ClientData 是否包含 OEPlaceholderAtom。"""++ for child in _direct_children(shape, budget):+ if child.record_type != RT_OFFICEART_CLIENT_DATA:+ continue+ if child.version == CONTAINER_VERSION:+ candidates: Iterable[PptRecord] = iter_descendants(child, budget=budget)+ else:+ candidates = iter_records(child.payload, budget=budget)+ if any(candidate.record_type == RT_OE_PLACEHOLDER_ATOM for candidate in candidates):+ return True+ return False+++def _client_rect(payload: bytes) -> tuple[float, float, float, float] | None:+ """把 OfficeArtClientAnchor 转成 left/top/right/bottom。"""++ if len(payload) < 8:+ return None+ top, left, right, bottom = struct.unpack_from("<4h", payload)+ return float(left), float(top), float(right), float(bottom)+++def _child_rect(payload: bytes) -> tuple[float, float, float, float] | None:+ """把 OfficeArtChildAnchor 转成 left/top/right/bottom。"""++ if len(payload) < 16:+ return None+ left, top, right, bottom = struct.unpack_from("<4i", payload)+ return float(left), float(top), float(right), float(bottom)+++def _map_group_rect(+ rect: tuple[float, float, float, float],+ space: _GroupSpace,+) -> tuple[float, float, float, float]:+ """把 group 子坐标线性映射到幻灯片坐标。"""++ coord_width = max(1.0, float(space.coord_right - space.coord_left))+ coord_height = max(1.0, float(space.coord_bottom - space.coord_top))+ scale_x = (space.abs_right - space.abs_left) / coord_width+ scale_y = (space.abs_bottom - space.abs_top) / coord_height+ left, top, right, bottom = rect+ return (+ space.abs_left + (left - space.coord_left) * scale_x,+ space.abs_top + (top - space.coord_top) * scale_y,+ space.abs_left + (right - space.coord_left) * scale_x,+ space.abs_top + (bottom - space.coord_top) * scale_y,+ )+++def _shape_bbox(+ shape: PptRecord,+ space: _GroupSpace | None,+ budget: RecordBudget,+) -> tuple[float, float, float, float] | None:+ """解析 shape anchor,并应用父 group 坐标映射。"""++ children = _direct_children(shape, budget)+ for child in children:+ if child.record_type == RT_OFFICEART_CLIENT_ANCHOR:+ rect = _client_rect(child.payload)+ if rect is not None:+ return rect+ for child in children:+ if child.record_type != RT_OFFICEART_CHILD_ANCHOR:+ continue+ rect = _child_rect(child.payload)+ if rect is None:+ continue+ if space is not None:+ return _map_group_rect(rect, space)+ if max(abs(value) for value in rect) > 100_000:+ return tuple(value * 576.0 / 914_400.0 for value in rect) # type: ignore[return-value]+ return rect+ return None+++def _group_space(+ group_shape: PptRecord,+ parent: _GroupSpace | None,+ budget: RecordBudget,+) -> _GroupSpace | None:+ """解析 group 自身坐标系与它在父坐标系中的外框。"""++ children = _direct_children(group_shape, budget)+ fspgr = next(+ (+ child+ for child in children+ if child.record_type == RT_OFFICEART_FSPGR and len(child.payload) >= 16+ ),+ None,+ )+ if fspgr is None:+ return parent+ coord_left, coord_top, coord_right, coord_bottom = struct.unpack_from("<4i", fspgr.payload)+ if coord_right <= coord_left or coord_bottom <= coord_top:+ return parent+ raw_rect = None+ for child in children:+ if child.record_type == RT_OFFICEART_CLIENT_ANCHOR:+ raw_rect = _client_rect(child.payload)+ break+ if child.record_type == RT_OFFICEART_CHILD_ANCHOR:+ raw_rect = _child_rect(child.payload)+ break+ if raw_rect is None:+ return parent+ rect = _map_group_rect(raw_rect, parent) if parent is not None else raw_rect+ left, top, right, bottom = rect+ return _GroupSpace(+ coord_left=int(coord_left),+ coord_top=int(coord_top),+ coord_right=int(coord_right),+ coord_bottom=int(coord_bottom),+ abs_left=left,+ abs_top=top,+ abs_right=right,+ abs_bottom=bottom,+ )+++def _is_table_group(group_shape: PptRecord, budget: RecordBudget) -> bool:+ """读取 tableProperties.fIsTable 标志。"""++ return bool(_shape_properties(group_shape, budget).get(FOPT_TABLE_PROPERTIES, 0) & 0x1)+++def _collect_shapes(slide: PptRecord, budget: RecordBudget) -> _ShapeCollection:+ """单次遍历收集叶子 shape,并保留 table group 的成员边界。"""++ shapes: list[_ShapeInfo] = []+ groups: dict[tuple[int, ...], tuple[PptRecord, list[_ShapeInfo], int, bool]] = {}+ order = 0++ def walk(+ record: PptRecord,+ space: _GroupSpace | None,+ path: tuple[int, ...],+ active_table: tuple[int, ...] | None,+ ) -> None:+ """递归遍历 OfficeArt 容器并传播 group 空间与 table 身份。"""++ nonlocal order+ if record.record_type == RT_OFFICEART_SPGR_CONTAINER and record.version == CONTAINER_VERSION:+ children = _direct_children(record, budget)+ if not children:+ return+ group_shape = children[0]+ group_key = path + (0,)+ nested_space = _group_space(group_shape, space, budget)+ authoritative = _is_table_group(group_shape, budget)+ groups[group_key] = (group_shape, [], order, authoritative)+ table_key = group_key+ for index, child in enumerate(children[1:], start=1):+ walk(child, nested_space, path + (index,), table_key)+ return+ if record.record_type == RT_OFFICEART_SP_CONTAINER:+ bbox = _shape_bbox(record, space, budget)+ if bbox is None or bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:+ return+ info = _ShapeInfo(+ key=path,+ record=record,+ space=space,+ bbox=bbox,+ order=order,+ group_key=active_table,+ )+ order += 1+ shapes.append(info)+ if active_table in groups:+ groups[active_table][1].append(info)+ return+ if record.version == CONTAINER_VERSION:+ for index, child in enumerate(_direct_children(record, budget)):+ walk(child, space, path + (index,), active_table)++ walk(slide, None, (), None)+ table_groups = tuple(+ _TableGroup(+ key=key,+ group_shape=group_shape,+ shapes=tuple(members),+ order=group_order,+ authoritative=authoritative,+ )+ for key, (group_shape, members, group_order, authoritative) in groups.items()+ )+ return _ShapeCollection(shapes=tuple(shapes), table_groups=table_groups)+++def _shape_text_content(+ shape: _ShapeInfo,+ external_text: list[_TextContent],+ master_styles: dict[int, list[MasterLevel]],+ hyperlinks: dict[int, str],+ budget: RecordBudget,+) -> _TextContent | None:+ """解析 shape 的 ClientTextbox,必要时回退到 OutlineTextRefAtom。"""++ textbox = next(+ (+ child+ for child in _direct_children(shape.record, budget)+ if child.record_type == RT_OFFICEART_CLIENT_TEXTBOX+ ),+ None,+ )+ if textbox is None:+ return None+ textbox_records = list(iter_descendants(textbox, budget=budget))+ contents = _parse_text_contents(textbox_records, master_styles, hyperlinks, budget)+ if contents:+ return _apply_shape_numbering(contents[0], shape.record, budget)+ reference = next(+ (+ child+ for child in textbox_records+ if child.record_type == RT_OUTLINE_TEXT_REF_ATOM and len(child.payload) >= 4+ ),+ None,+ )+ if reference is None:+ return None+ index = int(get_u32(reference.payload, 0) or 0)+ for candidate in ((index, index - 1) if index else (0,)):+ if 0 <= candidate < len(external_text):+ return _apply_shape_numbering(external_text[candidate], shape.record, budget)+ return None+++def _skip_style_text9_cf(payload: bytes, position: int) -> int | None:+ """跳过 TextCFException9;未知扩展位时停止该 atom 的解析。"""++ mask = get_u32(payload, position)+ if mask is None:+ return None+ position += 4+ if mask == 0:+ return position+ # 当前只需要自动编号,复杂 CF9 不影响已解析文本样式,安全终止后续槽位。+ return None+++def _skip_style_text9_si(payload: bytes, position: int) -> int | None:+ """跳过 TextSIException 中固定长度的语言与拼写字段。"""++ mask = get_u32(payload, position)+ if mask is None:+ return None+ position += 4+ for bit, size in ((0, 2), (1, 2), (2, 2), (5, 4), (6, 2)):+ if mask & (1 << bit):+ position += size+ if mask & (1 << 9) or position > len(payload):+ return None+ return position+++def _parse_style_text9_numbering(payload: bytes) -> dict[int, _NumberingStyle]:+ """解析 StyleTextProp9 数组中与自动编号有关的三个字段。"""++ result: dict[int, _NumberingStyle] = {}+ position = 0+ slot = 0+ while position + 12 <= len(payload) and slot < 16:+ mask = get_u32(payload, position)+ if mask is None or mask & ~0x0380_0000:+ break+ position += 4+ if mask & 0x0080_0000:+ position += 2+ enabled = None+ if mask & 0x0200_0000:+ value = get_i16(payload, position)+ if value is None:+ break+ enabled = value == 1+ position += 2+ start = None+ if mask & 0x0100_0000:+ scheme = get_u16(payload, position)+ start_value = get_u16(payload, position + 2)+ if scheme is None or start_value is None:+ break+ start = max(0, int(start_value))+ position += 4+ position = _skip_style_text9_cf(payload, position) or -1+ if position < 0:+ break+ position = _skip_style_text9_si(payload, position) or -1+ if position < 0:+ break+ result[slot] = _NumberingStyle(enabled=enabled, start=start)+ slot += 1+ return result+++def _shape_numbering_styles(+ shape: PptRecord,+ budget: RecordBudget,+) -> dict[int, _NumberingStyle]:+ """从 PP9ShapeBinaryTagExtension 取出 StyleTextProp9 自动编号。"""++ for tag in iter_descendants(shape, budget=budget):+ if tag.record_type != 0x138A or tag.version != CONTAINER_VERSION:+ continue+ children = list(iter_records(tag.payload, budget=budget))+ marker = next(+ (+ child+ for child in children+ if child.record_type == RT_CSTRING and utf16_text(child.payload) == "___PPT9"+ ),+ None,+ )+ blob = next((child for child in children if child.record_type == 0x138B), None)+ if marker is None or blob is None:+ continue+ atom = record_at(blob.payload, 0, budget=budget)+ if atom is not None and atom.record_type == 0x0FAC:+ return _parse_style_text9_numbering(atom.payload)+ return {}+++def _apply_shape_numbering(+ content: _TextContent,+ shape: PptRecord,+ budget: RecordBudget,+) -> _TextContent:+ """按 paragraph 起始字符的 pp9rt 槽位覆盖列表类型和起始编号。"""++ numbering = _shape_numbering_styles(shape, budget)+ if not numbering:+ return content+ paragraphs: list[PptParagraph] = []+ for paragraph in content.paragraphs:+ style = numbering.get(paragraph.pp9rt)+ if style is None or style.enabled is None:+ paragraphs.append(paragraph)+ continue+ paragraphs.append(+ replace(+ paragraph,+ list_kind="ordered" if style.enabled else None,+ start=style.start if style.enabled else None,+ )+ )+ return replace(content, paragraphs=tuple(paragraphs))+++def _cluster_coordinates(values: list[float], tolerance: float = 8.0) -> list[float]:+ """把生产器舍入误差导致的近邻坐标合并为稳定边界。"""++ if not values:+ return []+ clusters: list[list[float]] = []+ for value in sorted(values):+ if clusters and abs(value - sum(clusters[-1]) / len(clusters[-1])) <= tolerance:+ clusters[-1].append(value)+ else:+ clusters.append([value])+ return [sum(cluster) / len(cluster) for cluster in clusters]+++def _boundary_index(boundaries: list[float], value: float, tolerance: float = 16.0) -> int | None:+ """返回与坐标最近的边界索引,偏差过大时拒绝映射。"""++ if not boundaries:+ return None+ index = min(range(len(boundaries)), key=lambda candidate: abs(boundaries[candidate] - value))+ return index if abs(boundaries[index] - value) <= tolerance else None+++def _table_from_group(+ group: _TableGroup,+ external_text: list[_TextContent],+ master_styles: dict[int, list[MasterLevel]],+ hyperlinks: dict[int, str],+ budget: RecordBudget,+) -> PptTableElement | None:+ """从 fIsTable group 的矩形单元格恢复含合并信息的完整网格。"""++ cell_shapes: list[tuple[_ShapeInfo, _TextContent | None]] = []+ x_values: list[float] = []+ y_values: list[float] = []+ for shape in group.shapes:+ shape_type = _shape_type(shape.record, budget)+ left, top, right, bottom = shape.bbox+ width = right - left+ height = bottom - top+ # 线条只贡献边界,不成为单元格。+ if shape_type in {20, 32, 33, 34, 35, 36, 37, 38, 39, 40} or width <= 2 or height <= 2:+ if width <= 2:+ x_values.extend((left, right))+ if height <= 2:+ y_values.extend((top, bottom))+ continue+ if shape_type != 1:+ continue+ content = _shape_text_content(+ shape,+ external_text,+ master_styles,+ hyperlinks,+ budget,+ )+ cell_shapes.append((shape, content))+ x_values.extend((left, right))+ y_values.extend((top, bottom))+ if len(cell_shapes) < 4:+ return None++ x_boundaries = _cluster_coordinates(x_values)+ y_boundaries = _cluster_coordinates(y_values)+ cols = len(x_boundaries) - 1+ rows = len(y_boundaries) - 1+ if rows < 2 or cols < 2 or rows * cols > MAX_GRID_SLOTS:+ return None++ coverage: dict[tuple[int, int], tuple[int, int]] = {}+ cells: list[PptTableCell] = []+ for shape, content in cell_shapes:+ left, top, right, bottom = shape.bbox+ col_start = _boundary_index(x_boundaries, left)+ col_end = _boundary_index(x_boundaries, right)+ row_start = _boundary_index(y_boundaries, top)+ row_end = _boundary_index(y_boundaries, bottom)+ if (+ col_start is None+ or col_end is None+ or row_start is None+ or row_end is None+ or col_end <= col_start+ or row_end <= row_start+ ):+ return None+ for row in range(row_start, row_end):+ for col in range(col_start, col_end):+ if (row, col) in coverage:+ return None+ coverage[(row, col)] = (row_start, col_start)+ cells.append(+ PptTableCell(+ row=row_start,+ col=col_start,+ row_span=row_end - row_start,+ col_span=col_end - col_start,+ paragraphs=content.paragraphs if content is not None else (),+ )+ )+ if len(coverage) != rows * cols:+ return None++ cells.sort(key=lambda cell: (cell.row, cell.col))+ return PptTableElement(+ rows=rows,+ cols=cols,+ cells=tuple(cells),+ bbox=(x_boundaries[0], y_boundaries[0], x_boundaries[-1], y_boundaries[-1]),+ order=group.order,+ shape_offsets=frozenset(shape.key for shape in group.shapes),+ )+++def _decode_blip(record: PptRecord) -> _ImagePayload | None:+ """通过 legacy-office 共享层解码一个 OfficeArt BLIP。"""++ return decode_officeart_blip(+ OfficeArtRecord(+ offset=record.offset,+ version=record.version,+ instance=record.instance,+ record_type=record.record_type,+ payload=record.payload,+ )+ )+++def _decode_bse_body(body: bytes, budget: RecordBudget) -> _ImagePayload | None:+ """从 FBSE body 的可选内嵌 BLIP 中提取图片。"""++ if len(body) < 36:+ return None+ name_length = body[33]+ inner_offset = 36 + int(name_length)+ inner = record_at(body, inner_offset, budget=budget)+ return _decode_blip(inner) if inner is not None else None+++def _picture_map(+ document: PptRecord,+ pictures: bytes,+ budget: RecordBudget,+) -> dict[int, _ImagePayload]:+ """按 BStore 中 1-based BSE 序号建立图片资源映射。"""++ result: dict[int, _ImagePayload] = {}+ asset_total = 0+ bse_records = [+ record+ for record in iter_descendants(document, budget=budget)+ if record.record_type == RT_OFFICEART_BSE+ ]+ for index, bse in enumerate(bse_records[:MAX_PICTURE_RECORDS], start=1):+ decoded = None+ picture_offset = get_u32(bse.payload, 28)+ if picture_offset is not None and picture_offset < len(pictures):+ picture_record = record_at(pictures, int(picture_offset), budget=budget)+ if picture_record is not None:+ if picture_record.record_type == RT_OFFICEART_BSE:+ decoded = _decode_bse_body(picture_record.payload, budget)+ else:+ decoded = _decode_blip(picture_record)+ if decoded is None:+ decoded = _decode_bse_body(bse.payload, budget)+ if decoded is None:+ continue+ asset_total += len(decoded.data)+ if asset_total > MAX_ASSET_TOTAL_BYTES:+ raise LegacyOfficeResourceLimitError(+ f"embedded assets exceed max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}"+ )+ result[index] = decoded+ if len(bse_records) > MAX_PICTURE_RECORDS:+ logger.warning(+ f"PPT_PICTURE_LIMIT: ignored BSE records after {MAX_PICTURE_RECORDS}"+ )+ return result+++def _image_from_shape(+ shape: _ShapeInfo,+ image_map: dict[int, _ImagePayload],+ budget: RecordBudget,+) -> PptImageElement | None:+ """把 shape 的 pib 属性解析为可输出的 slide 图片。"""++ reference = _shape_properties(shape.record, budget).get(FOPT_PIB)+ if reference is None:+ return None+ image = image_map.get(int(reference))+ if image is None:+ logger.warning(+ f"PPT_IMAGE_REFERENCE_MISSING: shape={shape.key}, pib={reference}"+ )+ return None+ data_uri = serialize_office_image(+ image.data,+ part_name=f"picture.{image.extension}",+ content_type=image.content_type,+ )+ if not data_uri:+ logger.warning(+ f"PPT_IMAGE_UNSUPPORTED: shape={shape.key}, type={image.content_type}"+ )+ return None+ return PptImageElement(+ image_base64=data_uri,+ bbox=shape.bbox,+ order=shape.order,+ shape_offset=shape.order,+ )+++def _is_small_picture(+ bbox: tuple[float, float, float, float],+ slide_width: int,+ slide_height: int,+) -> bool:+ """复用现代 PPTX 的尺寸阈值过滤装饰性小图。"""++ width = bbox[2] - bbox[0]+ height = bbox[3] - bbox[1]+ if width <= 0 or height <= 0 or slide_width <= 0 or slide_height <= 0:+ return False+ if width < 0.1 * slide_width or height < 0.1 * slide_height:+ return True+ return width * height / float(slide_width * slide_height) < 0.01+++def _slide_elements(+ slide: PptRecord,+ external_text: list[_TextContent],+ master_styles: dict[int, list[MasterLevel]],+ hyperlinks: dict[int, str],+ image_map: dict[int, _ImagePayload],+ slide_width: int,+ slide_height: int,+ budget: RecordBudget,+) -> list[PptTextElement | PptImageElement | PptTableElement]:+ """把一张 slide 的 shapes 转换为文本、表格和图片语义元素。"""++ collection = _collect_shapes(slide, budget)+ tables: list[PptTableElement] = []+ consumed_keys: set[tuple[int, ...]] = set()+ for group in sorted(+ collection.table_groups,+ key=lambda candidate: (not candidate.authoritative, candidate.order),+ ):+ if any(shape.key in consumed_keys for shape in group.shapes):+ continue+ table = _table_from_group(+ group,+ external_text,+ master_styles,+ hyperlinks,+ budget,+ )+ if table is None and group.authoritative:+ logger.warning(f"PPT_TABLE_RECOVERY_FAILED: group={group.key}")+ continue+ if table is None:+ continue+ tables.append(table)+ consumed_keys.update(shape.key for shape in group.shapes)++ elements: list[PptTextElement | PptImageElement | PptTableElement] = list(tables)+ for shape in collection.shapes:+ if shape.key in consumed_keys or _is_background_shape(shape.record, budget):+ continue+ content = _shape_text_content(+ shape,+ external_text,+ master_styles,+ hyperlinks,+ budget,+ )+ if content is not None and content.paragraphs:+ elements.append(+ PptTextElement(+ paragraphs=content.paragraphs,+ text_type=content.text_type,+ bbox=shape.bbox,+ order=shape.order,+ shape_offset=shape.order,+ is_placeholder=_is_placeholder(shape.record, budget),+ )+ )+ image = _image_from_shape(shape, image_map, budget)+ if image is not None and not _is_small_picture(image.bbox, slide_width, slide_height):+ elements.append(image)+ if not any(isinstance(element, PptTextElement) for element in elements):+ # Handmade、早期生产器或恢复路径可能把文本直接放在 SlideContainer 中。+ raw_contents = _parse_text_contents(+ list(iter_descendants(slide, budget=budget)),+ master_styles,+ hyperlinks,+ budget,+ )+ for offset, content in enumerate(raw_contents):+ if not content.paragraphs:+ continue+ elements.append(+ PptTextElement(+ paragraphs=content.paragraphs,+ text_type=content.text_type,+ bbox=(+ 288.0,+ 288.0 + offset * 432.0,+ float(max(slide_width - 288, 576)),+ 576.0 + offset * 432.0,+ ),+ order=len(elements) + offset,+ shape_offset=len(elements) + offset,+ )+ )+ return elements+++def _slide_hidden(slide: PptRecord, budget: RecordBudget) -> bool:+ """读取 SlideShowSlideInfoAtom 的隐藏标志。"""++ for child in iter_descendants(slide, budget=budget):+ if child.record_type != RT_SLIDE_SHOW_SLIDE_INFO_ATOM or len(child.payload) < 12:+ continue+ flags = get_u16(child.payload, 10)+ return bool(int(flags or 0) & 0x0004)+ return False+++def _plain_paragraph_text(paragraph: PptParagraph) -> str:+ """返回一个内部段落的纯文本。"""++ return "".join(run.text for run in paragraph.runs)+++def _note_paragraphs(+ note_record: PptRecord,+ master_styles: dict[int, list[MasterLevel]],+ hyperlinks: dict[int, str],+ budget: RecordBudget,+) -> list[PptParagraph]:+ """提取 notes container 中的正文,排除占位符字段。"""++ paragraphs: list[PptParagraph] = []+ collection = _collect_shapes(note_record, budget)+ for shape in collection.shapes:+ content = _shape_text_content(shape, [], master_styles, hyperlinks, budget)+ if content is None:+ continue+ for paragraph in content.paragraphs:+ text = _plain_paragraph_text(paragraph).strip()+ if text and text != "*":+ paragraphs.append(paragraph)+ if paragraphs:+ return paragraphs++ # 少数生产器不把 notes 文本包在 OfficeArtClientTextbox 中。+ all_records = list(iter_descendants(note_record, budget=budget))+ for content in _parse_text_contents(all_records, master_styles, hyperlinks, budget):+ for paragraph in content.paragraphs:+ text = _plain_paragraph_text(paragraph).strip()+ if text and text != "*":+ paragraphs.append(paragraph)+ return paragraphs+++def _notes_by_slide_id(+ layout: _PersistLayout,+ data: bytes,+ fallback_master_styles: dict[int, list[MasterLevel]],+ hyperlinks: dict[int, str],+ budget: RecordBudget,+) -> tuple[dict[int, list[PptParagraph]], list[list[PptParagraph]]]:+ """按 NotesAtom.slideIdRef 绑定备注,并保留无主备注的顺序。"""++ bound: dict[int, list[PptParagraph]] = {}+ unbound: list[list[PptParagraph]] = []+ for reference in _notes_entries(layout.document, budget):+ offset = layout.persist.get(reference)+ if offset is None:+ continue+ note = record_at(data, offset, budget=budget)+ if note is None or note.record_type != RT_NOTES:+ continue+ slide_id = None+ for child in iter_descendants(note, budget=budget):+ if child.record_type == RT_NOTES_ATOM:+ slide_id = get_u32(child.payload, 0)+ break+ paragraphs = _note_paragraphs(+ note,+ fallback_master_styles,+ hyperlinks,+ budget,+ )+ if not paragraphs:+ continue+ if slide_id:+ bound[int(slide_id)] = paragraphs+ else:+ unbound.append(paragraphs)+ return bound, unbound+++def _root_slide_records(data: bytes, budget: RecordBudget) -> list[PptRecord]:+ """恢复 persist 不可用时直接位于文档 stream 顶层的 slide records。"""++ return [+ record+ for record in iter_records(data, budget=budget)+ if record.record_type == RT_SLIDE and record.version == CONTAINER_VERSION+ ]+++def _fallback_slide_from_text(+ data: bytes,+ master_styles: dict[int, list[MasterLevel]],+ hyperlinks: dict[int, str],+ budget: RecordBudget,+) -> PptSlide | None:+ """没有可靠 slide 边界时,把可恢复文本放入单个逻辑页。"""++ contents = _parse_text_contents(+ list(iter_records(data, budget=budget)),+ master_styles,+ hyperlinks,+ budget,+ )+ elements: list[PptTextElement] = []+ for order, content in enumerate(contents):+ if not content.paragraphs:+ continue+ elements.append(+ PptTextElement(+ paragraphs=content.paragraphs,+ text_type=content.text_type,+ bbox=(288.0, 288.0 + order * 432.0, 5472.0, 576.0 + order * 432.0),+ order=order,+ shape_offset=order,+ )+ )+ return PptSlide(slide_id=None, elements=list(elements)) if elements else None+++def parse_ppt_document(+ powerpoint_document: bytes,+ *,+ current_user: bytes = b"",+ pictures: bytes = b"",+) -> PptPresentation:+ """把三个核心 PPT streams 解析为分页内部语义模型。"""++ if current_user:+ record_type = get_u16(current_user, 2)+ if record_type not in {None, 0x0FF6}:+ raise LegacyOfficeMalformedError(+ "PowerPoint 95 or earlier Current User stream is unsupported"+ )+ if get_u32(current_user, 12) == 0xF3D1_C4DF:+ raise LegacyOfficeEncryptedError("password-protected PPT is unsupported")++ budget = RecordBudget()+ # 先完整验证可递归记录深度,避免无 Document 的攻击形状被误报为普通坏文件。+ for root_record in iter_records(+ powerpoint_document,+ budget=budget,+ strict_first=True,+ ):+ for _ in iter_descendants(root_record, budget=budget):+ pass+ layout = _locate_document(powerpoint_document, current_user, budget)+ if any(+ child.record_type == RT_CRYPT_SESSION10_CONTAINER+ for child in iter_descendants(layout.document, budget=budget)+ ):+ raise LegacyOfficeEncryptedError("encrypted PPT record stream is unsupported")++ width, height = _presentation_size(layout.document, budget)+ hyperlinks = _hyperlink_targets(layout.document, budget)+ image_map = _picture_map(layout.document, pictures, budget)+ master_map, fallback_master = _collect_masters(+ layout,+ powerpoint_document,+ budget,+ )+ fallback_styles = fallback_master[1] if fallback_master is not None else {}+ external_records = _external_text_records(layout.document, budget)+ bound_notes, unbound_notes = _notes_by_slide_id(+ layout,+ powerpoint_document,+ fallback_styles,+ hyperlinks,+ budget,+ )++ slides: list[PptSlide] = []+ resolved_offsets: set[int] = set()+ resolved_slide_count = 0+ unbound_note_index = 0+ for reference, slide_id in _slide_entries(layout.document, budget):+ offset = layout.persist.get(reference)+ notes = bound_notes.get(slide_id)+ if notes is None and unbound_note_index < len(unbound_notes):+ notes = unbound_notes[unbound_note_index]+ unbound_note_index += 1+ if offset is None or offset in resolved_offsets:+ logger.warning(+ f"PPT_SLIDE_MISSING: persist_ref={reference}, slide_id={slide_id}"+ )+ slides.append(+ PptSlide(slide_id=slide_id or None, notes=list(notes or []))+ )+ continue+ slide = record_at(powerpoint_document, offset, budget=budget)+ if slide is None or slide.record_type != RT_SLIDE:+ logger.warning(+ f"PPT_SLIDE_MALFORMED: persist_ref={reference}, slide_id={slide_id}"+ )+ slides.append(+ PptSlide(slide_id=slide_id or None, notes=list(notes or []))+ )+ continue+ resolved_offsets.add(offset)+ resolved_slide_count += 1+ master = master_map.get(_slide_master_id(slide, budget) or -1, fallback_master)+ master_styles = master[1] if master is not None else {}+ external_text = _parse_text_contents(+ external_records.get(reference, []),+ master_styles,+ hyperlinks,+ budget,+ )+ slides.append(+ PptSlide(+ slide_id=slide_id or None,+ elements=_slide_elements(+ slide,+ external_text,+ master_styles,+ hyperlinks,+ image_map,+ width,+ height,+ budget,+ ),+ notes=list(notes or []),+ hidden=_slide_hidden(slide, budget),+ )+ )++ if resolved_slide_count == 0:+ slides = []+ logger.warning("PPT_SLIDE_RECOVERY: persist mapping did not resolve slide records")+ for slide in _root_slide_records(powerpoint_document, budget):+ master = master_map.get(_slide_master_id(slide, budget) or -1, fallback_master)+ master_styles = master[1] if master is not None else {}+ slides.append(+ PptSlide(+ slide_id=None,+ elements=_slide_elements(+ slide,+ [],+ master_styles,+ hyperlinks,+ image_map,+ width,+ height,+ budget,+ ),+ hidden=_slide_hidden(slide, budget),+ )+ )+ if not slides:+ fallback_slide = _fallback_slide_from_text(+ powerpoint_document,+ fallback_styles,+ hyperlinks,+ budget,+ )+ if fallback_slide is not None:+ logger.warning("PPT_SINGLE_PAGE_RECOVERY: slide boundaries were not recoverable")+ slides.append(fallback_slide)+ if not slides:+ raise LegacyOfficeMalformedError("PPT contains no recoverable slides or text")+ return PptPresentation(slides=slides, width=width, height=height)diff --git a/mineru/model/flash/ppt/ppt_converter.py b/mineru/model/flash/ppt/ppt_converter.pynew file mode 100644index 00000000..f368c0c3--- /dev/null+++ b/mineru/model/flash/ppt/ppt_converter.py@@ -0,0 +1,275 @@+# Copyright (c) Opendatalab. All rights reserved.++"""把旧版 PPT 内部语义模型转换为 MinerU 分页 model-list。"""++from __future__ import annotations++from html import escape+from typing import Any, BinaryIO++from mineru.model.flash.legacy_office import BoundedOleReader+from mineru.model.flash.xycut import sort_entries+from mineru.model.office_stream import read_stream_bytes_from_start+from mineru.types import BlockType+from mineru.utils.office_rich_text import OfficeRichTextSegment, build_rich_text_from_segments++from .models import (+ PptImageElement,+ PptParagraph,+ PptPresentation,+ PptSlide,+ PptTableCell,+ PptTableElement,+ PptTextElement,+ PptTextRun,+)+from .parser import parse_ppt_document++PPT_XYCUT_BETA = 2.0+PPT_XYCUT_DENSITY_THRESHOLD = 0.9+++class PptConverter:+ """将 PowerPoint 97–2003 二进制流转换为分页 raw blocks。"""++ def __init__(self) -> None:+ """初始化无状态转换器输出。"""++ self.pages: list[list[dict[str, Any]]] = []++ def convert(self, file_binary: BinaryIO) -> None:+ """读取输入流、解析三个核心 OLE streams 并生成 model-list。"""++ file_bytes = read_stream_bytes_from_start(file_binary)+ with BoundedOleReader(file_bytes) as ole:+ presentation = parse_ppt_document(+ ole.read_stream("PowerPoint Document"),+ current_user=ole.read_stream("Current User", required=False),+ pictures=ole.read_stream("Pictures", required=False),+ )+ self.pages = self._presentation_to_pages(presentation)++ @staticmethod+ def _run_styles(run: PptTextRun) -> list[str]:+ """把内部字符属性转换为 MinerU 富文本样式名。"""++ styles: list[str] = []+ if run.bold:+ styles.append("bold")+ if run.italic:+ styles.append("italic")+ if run.underline:+ styles.append("underline")+ if run.strike:+ styles.append("strikethrough")+ if run.baseline is not None and run.baseline > 0:+ styles.append("superscript")+ elif run.baseline is not None and run.baseline < 0:+ styles.append("subscript")+ return styles++ @classmethod+ def _paragraph_content(cls, paragraph: PptParagraph) -> str:+ """把段落 run 构建为已转义的 MinerU Office 富文本。"""++ segments = [+ OfficeRichTextSegment(+ text=escape(run.text, quote=False).replace("\n", " "),+ style=cls._run_styles(run),+ hyperlink=escape(run.hyperlink, quote=False) if run.hyperlink else None,+ )+ for run in paragraph.runs+ if run.text+ ]+ return build_rich_text_from_segments(segments, trim_plain_edges=True)++ @classmethod+ def _append_list_paragraph(+ cls,+ root_blocks: list[dict[str, Any]],+ stack: list[dict[str, Any]],+ paragraph: PptParagraph,+ ) -> None:+ """把一个列表段落放入对应层级,并按需创建中间列表。"""++ depth = max(0, int(paragraph.depth))+ while len(stack) > depth + 1:+ stack.pop()+ while len(stack) < depth + 1:+ attribute = paragraph.list_kind or "unordered"+ new_list: dict[str, Any] = {+ "type": BlockType.LIST,+ "attribute": attribute,+ "ilevel": len(stack),+ "content": [],+ }+ if attribute == "ordered" and paragraph.start is not None:+ new_list["start"] = paragraph.start+ if stack:+ stack[-1]["content"].append(new_list)+ else:+ root_blocks.append(new_list)+ stack.append(new_list)+ current = stack[depth]+ expected_attribute = paragraph.list_kind or "unordered"+ if current.get("attribute") != expected_attribute:+ del stack[depth:]+ cls._append_list_paragraph(root_blocks, stack, paragraph)+ return+ content = cls._paragraph_content(paragraph)+ if content:+ current["content"].append({"type": BlockType.TEXT, "content": content})++ @classmethod+ def _text_element_blocks(+ cls,+ element: PptTextElement,+ *,+ title_candidate: bool,+ ) -> list[dict[str, Any]]:+ """把文本形状转换为标题、正文和嵌套列表 raw blocks。"""++ blocks: list[dict[str, Any]] = []+ list_stack: list[dict[str, Any]] = []+ title_consumed = False+ for paragraph in element.paragraphs:+ content = cls._paragraph_content(paragraph)+ if not content:+ continue+ if title_candidate and not title_consumed and paragraph.list_kind is None:+ blocks.append(+ {+ "type": BlockType.PARAGRAPH_TITLE,+ "content": content,+ "level": 2,+ "_ppt_title_candidate": True,+ }+ )+ title_consumed = True+ list_stack.clear()+ continue+ if paragraph.list_kind is not None:+ cls._append_list_paragraph(blocks, list_stack, paragraph)+ continue+ list_stack.clear()+ blocks.append({"type": BlockType.TEXT, "content": content})+ return blocks++ @classmethod+ def _table_cell_content(cls, cell: PptTableCell) -> str:+ """把表格单元格内的多个段落连接为 HTML 内容。"""++ return "<br/>".join(+ content+ for paragraph in cell.paragraphs+ if (content := cls._paragraph_content(paragraph))+ )++ @classmethod+ def _table_html(cls, table: PptTableElement) -> str:+ """按原点单元格生成带 rowspan/colspan 的稳定 HTML 表格。"""++ origins = {(cell.row, cell.col): cell for cell in table.cells}+ covered: set[tuple[int, int]] = set()+ rows: list[str] = []+ for row in range(table.rows):+ cells: list[str] = []+ for col in range(table.cols):+ if (row, col) in covered:+ continue+ cell = origins.get((row, col))+ if cell is None:+ cells.append("<td></td>")+ continue+ attributes: list[str] = []+ if cell.row_span > 1:+ attributes.append(f'rowspan="{cell.row_span}"')+ if cell.col_span > 1:+ attributes.append(f'colspan="{cell.col_span}"')+ attribute_text = f" {' '.join(attributes)}" if attributes else ""+ cells.append(f"<td{attribute_text}>{cls._table_cell_content(cell)}</td>")+ for covered_row in range(row, row + cell.row_span):+ for covered_col in range(col, col + cell.col_span):+ if (covered_row, covered_col) != (row, col):+ covered.add((covered_row, covered_col))+ rows.append(f"<tr>{''.join(cells)}</tr>")+ return f'<table border="1">{"".join(rows)}</table>'++ @classmethod+ def _element_blocks(+ cls,+ element: PptTextElement | PptImageElement | PptTableElement,+ *,+ slide_height: int,+ is_first_text_element: bool,+ ) -> list[dict[str, Any]]:+ """把一个语义元素转换为 raw blocks。"""++ if isinstance(element, PptImageElement):+ return [{"type": BlockType.IMAGE, "image_base64": element.image_base64}]+ if isinstance(element, PptTableElement):+ return [{"type": BlockType.TABLE, "content": cls._table_html(element)}]++ authoritative_title = element.text_type in {0, 6}+ first_paragraph = element.paragraphs[0] if element.paragraphs else None+ heuristic_title = bool(+ is_first_text_element+ and element.is_placeholder+ and first_paragraph is not None+ and first_paragraph.list_kind is None+ and element.bbox[1] <= slide_height * 0.35+ and len("".join(run.text for run in first_paragraph.runs).strip()) <= 200+ )+ return cls._text_element_blocks(+ element,+ title_candidate=authoritative_title or heuristic_title,+ )++ @classmethod+ def _slide_to_page(cls, slide: PptSlide, presentation: PptPresentation) -> list[dict[str, Any]]:+ """按 XYCut++ 排序一张幻灯片,并把备注稳定追加到末尾。"""++ entries: list[dict[str, Any]] = []+ text_seen = False+ for element in slide.elements:+ is_first_text = isinstance(element, PptTextElement) and not text_seen+ blocks = cls._element_blocks(+ element,+ slide_height=presentation.height,+ is_first_text_element=is_first_text,+ )+ if isinstance(element, PptTextElement) and blocks:+ text_seen = True+ if blocks:+ entries.append({"bbox": element.bbox, "blocks": blocks, "order": element.order})+ ordered_entries = sort_entries(+ entries,+ beta=PPT_XYCUT_BETA,+ density_threshold=PPT_XYCUT_DENSITY_THRESHOLD,+ )+ page = [block for entry in ordered_entries for block in entry["blocks"]]+ for paragraph in slide.notes:+ content = cls._paragraph_content(paragraph)+ if content:+ page.append({"type": BlockType.PAGE_FOOTNOTE, "content": content})+ return page++ @classmethod+ def _presentation_to_pages(cls, presentation: PptPresentation) -> list[list[dict[str, Any]]]:+ """转换整份演示文稿,并把首个有效标题提升为文档标题。"""++ pages = [cls._slide_to_page(slide, presentation) for slide in presentation.slides]+ document_title_promoted = False+ for page in pages:+ candidates = [block for block in page if block.pop("_ppt_title_candidate", False)]+ if not candidates:+ continue+ first = candidates[0]+ if not document_title_promoted:+ first["type"] = BlockType.DOC_TITLE+ first["level"] = 1+ document_title_promoted = True+ for candidate in candidates[1:] if first["type"] == BlockType.DOC_TITLE else candidates:+ candidate["type"] = BlockType.PARAGRAPH_TITLE+ candidate["level"] = 2+ return pagesdiff --git a/mineru/model/flash/ppt/records.py b/mineru/model/flash/ppt/records.pynew file mode 100644index 00000000..e68f12cd--- /dev/null+++ b/mineru/model/flash/ppt/records.py@@ -0,0 +1,171 @@+# Copyright (c) Opendatalab. All rights reserved.++"""有界读取 MS-PPT 与 OfficeArt 记录流。"""++from __future__ import annotations++from dataclasses import dataclass+import struct+from typing import Iterator++from mineru.model.flash.legacy_office.errors import (+ LegacyOfficeMalformedError,+ LegacyOfficeResourceLimitError,+)+from mineru.model.flash.legacy_office.limits import MAX_RECORD_DEPTH, MAX_RECORDS++CONTAINER_VERSION = 0xF+ROUNDTRIP_OPAQUE_MIN = 1053+ROUNDTRIP_OPAQUE_MAX = 1064+++@dataclass(frozen=True, slots=True)+class PptRecord:+ """一条已验证边界的 PPT/OfficeArt 记录。"""++ offset: int+ version: int+ instance: int+ record_type: int+ payload: bytes+++@dataclass(slots=True)+class RecordBudget:+ """跨解析阶段累计记录访问次数。"""++ count: int = 0++ def charge(self) -> None:+ """计入一条记录,超过固定上限时硬失败。"""++ self.count += 1+ if self.count > MAX_RECORDS:+ raise LegacyOfficeResourceLimitError(+ f"record stream exceeds max_records={MAX_RECORDS}"+ )+++def get_u16(data: bytes, offset: int) -> int | None:+ """安全读取小端无符号 16 位整数。"""++ if offset < 0 or offset + 2 > len(data):+ return None+ return struct.unpack_from("<H", data, offset)[0]+++def get_i16(data: bytes, offset: int) -> int | None:+ """安全读取小端有符号 16 位整数。"""++ if offset < 0 or offset + 2 > len(data):+ return None+ return struct.unpack_from("<h", data, offset)[0]+++def get_u32(data: bytes, offset: int) -> int | None:+ """安全读取小端无符号 32 位整数。"""++ if offset < 0 or offset + 4 > len(data):+ return None+ return struct.unpack_from("<I", data, offset)[0]+++def record_at(+ data: bytes,+ offset: int,+ *,+ end: int | None = None,+ strict: bool = False,+ budget: RecordBudget | None = None,+) -> PptRecord | None:+ """读取指定偏移的单条记录;严格模式下把坏边界转换为稳定错误。"""++ limit = len(data) if end is None else min(end, len(data))+ if offset < 0 or offset + 8 > limit:+ if strict:+ raise LegacyOfficeMalformedError("PowerPoint record header is truncated")+ return None+ version_instance, record_type, length = struct.unpack_from("<HHI", data, offset)+ payload_start = offset + 8+ payload_end = payload_start + length+ if payload_end < payload_start or payload_end > limit:+ if strict:+ raise LegacyOfficeMalformedError("PowerPoint record extends beyond its container")+ return None+ if budget is not None:+ budget.charge()+ return PptRecord(+ offset=offset,+ version=version_instance & 0xF,+ instance=version_instance >> 4,+ record_type=record_type,+ payload=data[payload_start:payload_end],+ )+++def iter_records(+ data: bytes,+ *,+ start: int = 0,+ end: int | None = None,+ budget: RecordBudget | None = None,+ strict_first: bool = False,+) -> Iterator[PptRecord]:+ """按顺序遍历同一容器内的记录,允许尾部生产器填充字节。"""++ limit = len(data) if end is None else min(end, len(data))+ cursor = start+ first = True+ while cursor < limit:+ record = record_at(+ data,+ cursor,+ end=limit,+ strict=strict_first and first,+ budget=budget,+ )+ if record is None:+ return+ yield record+ cursor += 8 + len(record.payload)+ first = False+++def iter_descendants(+ record: PptRecord,+ *,+ budget: RecordBudget | None = None,+) -> Iterator[PptRecord]:+ """用显式栈深度优先遍历容器,跳过不可递归的 round-trip blob。"""++ if record.version != CONTAINER_VERSION:+ return+ stack: list[tuple[bytes, Iterator[PptRecord]]] = [+ (record.payload, iter_records(record.payload, budget=budget))+ ]+ while stack:+ if len(stack) > MAX_RECORD_DEPTH:+ raise LegacyOfficeResourceLimitError(+ f"record nesting exceeds max_record_depth={MAX_RECORD_DEPTH}"+ )+ _, iterator = stack[-1]+ try:+ child = next(iterator)+ except StopIteration:+ stack.pop()+ continue+ yield child+ if (+ child.version == CONTAINER_VERSION+ and not ROUNDTRIP_OPAQUE_MIN <= child.record_type <= ROUNDTRIP_OPAQUE_MAX+ ):+ stack.append(+ (child.payload, iter_records(child.payload, budget=budget))+ )+++def utf16_text(payload: bytes) -> str:+ """容错解码 UTF-16LE 文本并移除末尾 NUL。"""++ usable = payload[: len(payload) - (len(payload) % 2)]+ return usable.decode("utf-16le", "replace").rstrip("\x00")diff --git a/mineru/model/flash/ppt/style_text.py b/mineru/model/flash/ppt/style_text.pynew file mode 100644index 00000000..c3c9a28b--- /dev/null+++ b/mineru/model/flash/ppt/style_text.py@@ -0,0 +1,251 @@+# Copyright (c) Opendatalab. All rights reserved.++"""解析 StyleTextPropAtom 与 TextMasterStyleAtom。"""++from __future__ import annotations++from dataclasses import dataclass, field++from .records import get_i16, get_u16, get_u32+++@dataclass(frozen=True, slots=True)+class ParagraphRun:+ """一段 UTF-16 文本范围对应的段落属性。"""++ count: int+ depth: int+ bullet: bool | None = None+ ordered: bool | None = None+ start: int | None = None+++@dataclass(frozen=True, slots=True)+class CharacterRun:+ """一段 UTF-16 文本范围对应的字符属性。"""++ count: int+ bold: bool | None = None+ italic: bool | None = None+ underline: bool | None = None+ strike: bool | None = None+ baseline: int | None = None+ pp9rt: int = 0+++@dataclass(frozen=True, slots=True)+class MasterLevel:+ """一个母版缩进层级的可继承默认值。"""++ bullet: bool | None = None+ bold: bool | None = None+ italic: bool | None = None+ underline: bool | None = None+ baseline: int | None = None+++@dataclass(slots=True)+class StyleRuns:+ """同一文本形状的段落与字符属性序列。"""++ paragraphs: list[ParagraphRun] = field(default_factory=list)+ characters: list[CharacterRun] = field(default_factory=list)+++@dataclass(frozen=True, slots=True)+class _CharacterStyle:+ """TextCFException 解出的三态字符属性。"""++ bold: bool | None = None+ italic: bool | None = None+ underline: bool | None = None+ strike: bool | None = None+ baseline: int | None = None+ pp9rt: int = 0+++def _parse_paragraph_exception(+ body: bytes,+ position: int,+) -> tuple[bool | None, int] | None:+ """解析 TextPFException 并返回显式 bullet 状态与下一偏移。"""++ mask = get_u32(body, position)+ if mask is None:+ return None+ position += 4+ bullet = None+ if mask & 0x000F:+ flags = get_u16(body, position)+ if flags is None:+ return None+ if mask & 0x0001:+ bullet = bool(flags & 0x0001)+ position += 2+ fixed_sizes = (+ (0x0080, 2),+ (0x0010, 2),+ (0x0040, 2),+ (0x0020, 4),+ (0x0800, 2),+ (0x1000, 2),+ (0x2000, 2),+ (0x4000, 2),+ (0x0100, 2),+ (0x0400, 2),+ (0x8000, 2),+ )+ for property_mask, size in fixed_sizes:+ if mask & property_mask:+ position += size+ if mask & 0x0010_0000:+ tab_count = get_u16(body, position)+ if tab_count is None:+ return None+ position += 2 + tab_count * 4+ if mask & 0x0001_0000:+ position += 2+ if mask & 0x000E_0000:+ position += 2+ if mask & 0x0020_0000:+ position += 2+ if position > len(body):+ return None+ return bullet, position+++def _parse_character_exception(+ body: bytes,+ position: int,+) -> tuple[_CharacterStyle, int] | None:+ """解析 TextCFException,并保留每个可继承属性的三态值。"""++ mask = get_u32(body, position)+ if mask is None:+ return None+ position += 4+ bold = italic = underline = strike = None+ pp9rt = 0+ if mask & 0xFFFF:+ flags = get_u16(body, position)+ if flags is None:+ return None+ if mask & 0x0001:+ bold = bool(flags & 0x0001)+ if mask & 0x0002:+ italic = bool(flags & 0x0002)+ if mask & 0x0004:+ underline = bool(flags & 0x0004)+ # 一些生产器把删除线写入扩展 style 位;未声明时继续继承。+ if mask & 0x0100:+ strike = bool(flags & 0x0100)+ # fontStyle 的 4 位 pp9rt 选择 StyleTextProp9 数组条目。+ pp9rt = (flags >> 10) & 0xF+ position += 2+ for property_mask in (0x0001_0000, 0x0020_0000, 0x0040_0000, 0x0080_0000):+ if mask & property_mask:+ position += 2+ if mask & 0x0002_0000:+ position += 2+ if mask & 0x0004_0000:+ position += 4+ baseline = None+ if mask & 0x0008_0000:+ baseline = get_i16(body, position)+ if baseline is None:+ return None+ position += 2+ if position > len(body):+ return None+ return (+ _CharacterStyle(+ bold=bold,+ italic=italic,+ underline=underline,+ strike=strike,+ baseline=baseline,+ pp9rt=pp9rt,+ ),+ position,+ )+++def parse_style_text(body: bytes, text_utf16_length: int) -> StyleRuns:+ """按 UTF-16 单元长度解析一个 StyleTextPropAtom。"""++ runs = StyleRuns()+ position = 0+ covered = 0+ while covered <= text_utf16_length:+ count = get_u32(body, position)+ depth = get_u16(body, position + 4)+ if count is None or depth is None:+ break+ position += 6+ parsed = _parse_paragraph_exception(body, position)+ if parsed is None:+ return runs+ bullet, position = parsed+ runs.paragraphs.append(+ ParagraphRun(count=int(count), depth=min(int(depth), 8), bullet=bullet)+ )+ covered += int(count)+ if count == 0:+ break++ covered = 0+ while covered <= text_utf16_length:+ count = get_u32(body, position)+ if count is None:+ break+ position += 4+ parsed = _parse_character_exception(body, position)+ if parsed is None:+ break+ style, position = parsed+ runs.characters.append(+ CharacterRun(+ count=int(count),+ bold=style.bold,+ italic=style.italic,+ underline=style.underline,+ strike=style.strike,+ baseline=style.baseline,+ pp9rt=style.pp9rt,+ )+ )+ covered += int(count)+ if count == 0:+ break+ return runs+++def parse_master_style(body: bytes, instance: int) -> list[MasterLevel]:+ """解析 TextMasterStyleAtom 的逐层默认字符与列表属性。"""++ level_count = get_u16(body, 0)+ if level_count is None:+ return []+ position = 2+ result: list[MasterLevel] = []+ for _ in range(min(int(level_count), 10)):+ if instance >= 5:+ position += 2+ parsed_paragraph = _parse_paragraph_exception(body, position)+ if parsed_paragraph is None:+ break+ bullet, position = parsed_paragraph+ parsed_character = _parse_character_exception(body, position)+ if parsed_character is None:+ break+ style, position = parsed_character+ result.append(+ MasterLevel(+ bullet=bullet,+ bold=style.bold,+ italic=style.italic,+ underline=style.underline,+ baseline=style.baseline,+ )+ )+ return resultdiff --git a/mineru/model/flash/xls/__init__.py b/mineru/model/flash/xls/__init__.pynew file mode 100644index 00000000..f8de07d2--- /dev/null+++ b/mineru/model/flash/xls/__init__.py@@ -0,0 +1,3 @@+# Copyright (c) Opendatalab. All rights reserved.++"""Excel 97–2003 二进制解析实现。"""diff --git a/mineru/model/flash/xls/chart.py b/mineru/model/flash/xls/chart.pynew file mode 100644index 00000000..0d74c4e7--- /dev/null+++ b/mineru/model/flash/xls/chart.py@@ -0,0 +1,98 @@+# Copyright (c) Opendatalab. All rights reserved.++"""解析 BIFF chart BRAI 中的简单单元格引用。"""++from __future__ import annotations++import struct++from .records import BiffRecord++BRAI = 0x1051+++def _extern_sheet_index(+ extern_sheets: list[int | None],+ extern_index: int,+) -> int | None:+ """把 ixti 解析为内部工作表索引。"""++ if 0 <= extern_index < len(extern_sheets):+ return extern_sheets[extern_index]+ return None+++def _reference_from_tokens(+ tokens: bytes,+ *,+ current_sheet_index: int,+ extern_sheets: list[int | None],+) -> tuple[list[int], list[int]] | None:+ """解析单一 PtgRef/PtgArea 及其 3D 变体。"""++ if not tokens:+ return None+ token = tokens[0] & 0x1F+ if token == 0x04 and len(tokens) >= 5:+ row, column_flags = struct.unpack_from("<HH", tokens, 1)+ return [int(row)], [int(column_flags & 0x00FF)]+ if token == 0x05 and len(tokens) >= 9:+ row_first, row_last, col_first, col_last = struct.unpack_from("<4H", tokens, 1)+ return (+ list(range(min(row_first, row_last), max(row_first, row_last) + 1)),+ list(range((col_first & 0x00FF), (col_last & 0x00FF) + 1)),+ )+ if token == 0x1A and len(tokens) >= 7:+ extern_index, row, column_flags = struct.unpack_from("<3H", tokens, 1)+ if _extern_sheet_index(extern_sheets, int(extern_index)) != current_sheet_index:+ return None+ return [int(row)], [int(column_flags & 0x00FF)]+ if token == 0x1B and len(tokens) >= 11:+ extern_index, row_first, row_last, col_first, col_last = struct.unpack_from(+ "<5H", tokens, 1+ )+ if _extern_sheet_index(extern_sheets, int(extern_index)) != current_sheet_index:+ return None+ first_col = col_first & 0x00FF+ last_col = col_last & 0x00FF+ return (+ list(range(min(row_first, row_last), max(row_first, row_last) + 1)),+ list(range(min(first_col, last_col), max(first_col, last_col) + 1)),+ )+ return None+++def chart_source_axes(+ records: list[BiffRecord],+ *,+ current_sheet_index: int,+ extern_sheets: list[int | None],+) -> tuple[list[int], list[int]] | None:+ """合并 chart 名称、分类、数值与气泡引用的行列集合。"""++ rows: set[int] = set()+ cols: set[int] = set()+ formulas_found = False+ for record in records:+ if record.record_type != BRAI or len(record.payload) < 8:+ continue+ formula_length = int(struct.unpack_from("<H", record.payload, 6)[0])+ if formula_length <= 0:+ continue+ formulas_found = True+ tokens = record.payload[8 : 8 + formula_length]+ if len(tokens) != formula_length:+ return None+ reference = _reference_from_tokens(+ tokens,+ current_sheet_index=current_sheet_index,+ extern_sheets=extern_sheets,+ )+ if reference is None:+ return None+ reference_rows, reference_cols = reference+ rows.update(reference_rows)+ cols.update(reference_cols)+ if not formulas_found or not rows or not cols:+ return None+ return sorted(rows), sorted(cols)diff --git a/mineru/model/flash/xls/models.py b/mineru/model/flash/xls/models.pynew file mode 100644index 00000000..e6b80643--- /dev/null+++ b/mineru/model/flash/xls/models.py@@ -0,0 +1,86 @@+# Copyright (c) Opendatalab. All rights reserved.++"""旧版 Excel 解析阶段使用的内部语义模型。"""++from __future__ import annotations++from dataclasses import dataclass, field+++@dataclass(frozen=True, slots=True)+class XlsFontStyle:+ """一个 BIFF FONT 记录中可表达的行内文字样式。"""++ bold: bool = False+ italic: bool = False+ underline: bool = False+ strike: bool = False+ superscript: bool = False+ subscript: bool = False+++@dataclass(frozen=True, slots=True)+class XlsRichRun:+ """以 Python 字符索引表示的富文本区间。"""++ start: int+ end: int+ style: XlsFontStyle+++@dataclass(frozen=True, slots=True)+class XlsRichText:+ """单元格或 drawing 文本及其富文本区间。"""++ text: str+ runs: tuple[XlsRichRun, ...] = ()+++@dataclass(slots=True)+class XlsCell:+ """工作表中的一个可见语义单元格。"""++ row: int+ col: int+ value: XlsRichText+ hyperlink: str | None = None+++@dataclass(frozen=True, slots=True)+class XlsImage:+ """绑定到工作表 cell anchor 的已序列化图片。"""++ row: int+ col: int+ image_base64: str+++@dataclass(frozen=True, slots=True)+class XlsChart:+ """由嵌入 chart 引用恢复出的源数据坐标。"""++ row: int+ col: int+ source_rows: tuple[int, ...]+ source_cols: tuple[int, ...]+ image_base64: str | None = None+++@dataclass(slots=True)+class XlsSheet:+ """一个 worksheet 的单元格、合并区域与 drawing 资源。"""++ name: str+ visible: bool+ cells: dict[tuple[int, int], XlsCell] = field(default_factory=dict)+ merges: list[tuple[int, int, int, int]] = field(default_factory=list)+ images: list[XlsImage] = field(default_factory=list)+ charts: list[XlsChart] = field(default_factory=list)+ recovered: bool = False+++@dataclass(slots=True)+class XlsWorkbook:+ """Excel 97–2003 工作簿的内部分页表示。"""++ sheets: list[XlsSheet]diff --git a/mineru/model/flash/xls/number_format.py b/mineru/model/flash/xls/number_format.pynew file mode 100644index 00000000..6997d82e--- /dev/null+++ b/mineru/model/flash/xls/number_format.py@@ -0,0 +1,523 @@+# Copyright (c) Opendatalab. All rights reserved.++"""Excel 数值格式解析与稳定显示文本生成。"""++from __future__ import annotations++from dataclasses import dataclass+from datetime import datetime, timedelta+from decimal import Decimal, InvalidOperation, ROUND_HALF_UP+from fractions import Fraction+import math+import re+++BUILTIN_NUMBER_FORMATS: dict[int, str] = {+ 1: "0",+ 2: "0.00",+ 3: "#,##0",+ 4: "#,##0.00",+ 9: "0%",+ 10: "0.00%",+ 11: "0.00E+00",+ 12: "# ?/?",+ 13: "# ??/??",+ 14: "mm-dd-yy",+ 15: "d-mmm-yy",+ 16: "d-mmm",+ 17: "mmm-yy",+ 18: "h:mm AM/PM",+ 19: "h:mm:ss AM/PM",+ 20: "h:mm",+ 21: "h:mm:ss",+ 22: "m/d/yy h:mm",+ 37: "#,##0 ;(#,##0)",+ 38: "#,##0 ;[Red](#,##0)",+ 39: "#,##0.00;(#,##0.00)",+ 40: "#,##0.00;[Red](#,##0.00)",+ 45: "mm:ss",+ 46: "[h]:mm:ss",+ 47: "mmss.0",+ 48: "##0.0E+0",+ 49: "@",+}++_COLOR_NAMES = {+ "black",+ "blue",+ "cyan",+ "green",+ "magenta",+ "red",+ "white",+ "yellow",+}+_CONDITION_RE = re.compile(r"^(<=|>=|<>|=|<|>)([-+]?(?:\d+(?:\.\d*)?|\.\d+))$")+++@dataclass(frozen=True, slots=True)+class _Condition:+ """一个数值格式 section 的比较条件。"""++ operator: str+ operand: float++ def matches(self, value: float) -> bool:+ """判断数值是否满足当前比较条件。"""++ return {+ "<": value < self.operand,+ "<=": value <= self.operand,+ ">": value > self.operand,+ ">=": value >= self.operand,+ "=": value == self.operand,+ "<>": value != self.operand,+ }[self.operator]+++@dataclass(frozen=True, slots=True)+class _Section:+ """一个已拆分但仍保留 Excel 格式语法的 section。"""++ pattern: str+ condition: _Condition | None+++def builtin_number_format(format_id: int) -> str | None:+ """返回确定的内建格式代码,地区相关格式不做猜测。"""++ return BUILTIN_NUMBER_FORMATS.get(int(format_id))+++def format_general(value: float) -> str:+ """按 Excel 15 位有效数字输出无格式浮点数。"""++ if not math.isfinite(value):+ return str(value)+ if value == 0:+ return "0"+ rounded = float(f"{value:.15g}")+ if rounded.is_integer() and abs(rounded) < 1e15:+ return str(int(rounded))+ return format(rounded, ".15g")+++def _split_sections(code: str) -> list[str] | None:+ """在不切开引号、转义和方括号的前提下拆分分号 sections。"""++ sections: list[str] = []+ current: list[str] = []+ quote = False+ bracket_depth = 0+ escaped = False+ for char in code:+ if escaped:+ current.append(char)+ escaped = False+ continue+ if char == "\\" and not quote:+ current.append(char)+ escaped = True+ continue+ if char == '"':+ current.append(char)+ quote = not quote+ continue+ if not quote and char == "[":+ bracket_depth += 1+ elif not quote and char == "]":+ bracket_depth -= 1+ if bracket_depth < 0:+ return None+ if char == ";" and not quote and bracket_depth == 0:+ sections.append("".join(current))+ current = []+ else:+ current.append(char)+ if quote or bracket_depth != 0 or escaped:+ return None+ sections.append("".join(current))+ return sections if len(sections) <= 4 else None+++def _strip_brackets(pattern: str) -> tuple[str, _Condition | None, bool]:+ """移除颜色/条件/地区标记,同时识别 elapsed 时间格式。"""++ output: list[str] = []+ condition: _Condition | None = None+ elapsed = False+ cursor = 0+ while cursor < len(pattern):+ if pattern[cursor] != "[":+ output.append(pattern[cursor])+ cursor += 1+ continue+ end = pattern.find("]", cursor + 1)+ if end < 0:+ return pattern, condition, elapsed+ inner = pattern[cursor + 1 : end]+ match = _CONDITION_RE.fullmatch(inner)+ if match and condition is None:+ condition = _Condition(match.group(1), float(match.group(2)))+ elif inner.casefold() in _COLOR_NAMES or re.fullmatch(r"Color\d+", inner, re.I):+ pass+ elif inner.casefold() in {"h", "hh", "m", "mm", "s", "ss"}:+ elapsed = True+ output.append(f"[{inner}]")+ elif inner.startswith("$"):+ currency = inner[1:].split("-", 1)[0]+ output.append(currency)+ else:+ output.append(f"[{inner}]")+ cursor = end + 1+ return "".join(output), condition, elapsed+++def _parse_sections(code: str) -> list[_Section] | None:+ """拆分格式并提取每个 section 的可选条件。"""++ raw_sections = _split_sections(code)+ if raw_sections is None or not raw_sections:+ return None+ sections: list[_Section] = []+ for raw in raw_sections:+ pattern, condition, _ = _strip_brackets(raw)+ sections.append(_Section(pattern=pattern, condition=condition))+ if sum(section.condition is not None for section in sections) > 2:+ return None+ return sections+++def _choose_numeric_section(+ sections: list[_Section],+ value: float,+) -> tuple[_Section, float, bool] | None:+ """按条件或正负零位置选择用于渲染的数值 section。"""++ numeric = sections[:-1] if len(sections) == 4 else sections+ if not numeric:+ return None+ if any(section.condition is not None for section in numeric):+ for section in numeric:+ if section.condition is None or section.condition.matches(value):+ return section, value, True+ return None+ if len(numeric) == 1:+ return numeric[0], value, True+ if len(numeric) == 2:+ return (numeric[1], abs(value), False) if value < 0 else (numeric[0], value, False)+ if value > 0:+ return numeric[0], value, False+ if value < 0:+ return numeric[1], abs(value), False+ return numeric[2], value, False+++def _literalize(pattern: str) -> str:+ """把引号、转义、下划线和填充语法还原为显示字面量。"""++ output: list[str] = []+ cursor = 0+ quote = False+ while cursor < len(pattern):+ char = pattern[cursor]+ if char == '"':+ quote = not quote+ cursor += 1+ continue+ if not quote and char == "\\" and cursor + 1 < len(pattern):+ output.append(pattern[cursor + 1])+ cursor += 2+ continue+ if not quote and char == "_" and cursor + 1 < len(pattern):+ output.append(" ")+ cursor += 2+ continue+ if not quote and char == "*" and cursor + 1 < len(pattern):+ cursor += 2+ continue+ output.append(char)+ cursor += 1+ return "".join(output)+++def _syntax_view(pattern: str) -> str:+ """移除字面量后返回仅供格式类型判定的语法视图。"""++ output: list[str] = []+ cursor = 0+ quote = False+ while cursor < len(pattern):+ char = pattern[cursor]+ if char == '"':+ quote = not quote+ cursor += 1+ continue+ if not quote and char in {"\\", "_", "*"} and cursor + 1 < len(pattern):+ cursor += 2+ continue+ if not quote:+ output.append(char)+ cursor += 1+ return "".join(output)+++def _date_parts(pattern: str) -> tuple[bool, bool, bool] | None:+ """判断格式是否表示日期、时间或 elapsed 时长。"""++ syntax = _syntax_view(pattern).casefold()+ elapsed = bool(re.search(r"\[(?:h+|m+|s+)\]", syntax))+ syntax_without_elapsed = re.sub(r"\[(?:h+|m+|s+)\]", "", syntax)+ has_year_or_day = bool(re.search(r"y|d", syntax_without_elapsed))+ has_hour_or_second = bool(re.search(r"h|s|am/pm|a/p", syntax_without_elapsed))+ has_month_or_minute = "m" in syntax_without_elapsed+ if not (elapsed or has_year_or_day or has_hour_or_second or has_month_or_minute):+ return None+ if not re.search(r"[ydhms]", syntax_without_elapsed) and not elapsed:+ return None+ if has_month_or_minute:+ minute_context = has_hour_or_second or bool(re.search(r"m+\s*:\s*s+|h+\s*:\s*m+", syntax))+ has_date = has_year_or_day or not minute_context+ has_time = has_hour_or_second or minute_context+ else:+ has_date = has_year_or_day+ has_time = has_hour_or_second+ if elapsed:+ has_time = True+ if not has_year_or_day:+ has_date = False+ return has_date, has_time, elapsed+++def _render_serial(value: float, *, date1904: bool, parts: tuple[bool, bool, bool]) -> str:+ """把 Excel serial 按确定的 ISO 日期/时间策略输出。"""++ has_date, has_time, elapsed = parts+ if elapsed:+ total_seconds = int(round(abs(value) * 86_400))+ sign = "-" if value < 0 else ""+ hours, remainder = divmod(total_seconds, 3600)+ minutes, seconds = divmod(remainder, 60)+ return f"{sign}{hours}:{minutes:02}:{seconds:02}"+ if not has_date:+ total_seconds = int(round(abs(value % 1) * 86_400)) % 86_400+ hours, remainder = divmod(total_seconds, 3600)+ minutes, seconds = divmod(remainder, 60)+ return f"{hours:02}:{minutes:02}:{seconds:02}"+ days = math.floor(value)+ if not date1904 and days == 60:+ return format_general(value)+ try:+ if date1904:+ resolved = datetime(1904, 1, 1) + timedelta(days=value)+ else:+ corrected = value - 1 if value >= 60 else value+ resolved = datetime(1899, 12, 31) + timedelta(days=corrected)+ except (OverflowError, ValueError):+ return format_general(value)+ output = resolved.strftime("%Y-%m-%d")+ if has_time:+ output += resolved.strftime(" %H:%M:%S")+ return output+++def _decimal_quantize(value: float, places: int) -> Decimal:+ """以 Excel 接近的 half-up 规则按指定位数舍入。"""++ decimal_value = Decimal(format(value, ".15g"))+ quantum = Decimal(1).scaleb(-places)+ return decimal_value.quantize(quantum, rounding=ROUND_HALF_UP)+++def _extract_number_span(pattern: str) -> tuple[str, str, str]:+ """拆出数字占位主体及其前后字面量。"""++ literalized = _literalize(pattern)+ general_match = re.search("general", literalized, re.I)+ if general_match is not None:+ return (+ literalized[: general_match.start()],+ literalized[general_match.start() : general_match.end()],+ literalized[general_match.end() :],+ )+ positions = [index for index, char in enumerate(literalized) if char in "0#?@"]+ if not positions:+ return literalized, "", ""+ start, end = min(positions), max(positions) + 1+ numeric_syntax = set("0123456789#?.,%Ee+-/")+ while start > 0 and literalized[start - 1] in numeric_syntax:+ start -= 1+ while end < len(literalized) and literalized[end] in numeric_syntax:+ end += 1+ return literalized[:start], literalized[start:end], literalized[end:]+++def _render_scientific(value: float, pattern: str) -> str | None:+ """按 Excel 科学计数占位符输出 mantissa 与 exponent。"""++ match = re.search(r"([0#?]+)(?:\.([0#?]+))?[Ee]([+-])([0#?]+)", pattern)+ if match is None:+ return None+ int_places = len(match.group(1))+ frac_places = len(match.group(2) or "")+ exponent_places = len(match.group(4))+ if value == 0:+ exponent = 0+ mantissa = 0.0+ else:+ raw_exponent = math.floor(math.log10(abs(value)))+ exponent = math.floor(raw_exponent / max(int_places, 1)) * max(int_places, 1)+ mantissa = value / (10**exponent)+ rounded = _decimal_quantize(mantissa, frac_places)+ if abs(rounded) >= 10**int_places:+ exponent += max(int_places, 1)+ rounded /= Decimal(10**max(int_places, 1))+ mantissa_text = f"{rounded:.{frac_places}f}"+ exponent_sign = "+" if exponent >= 0 else "-"+ if match.group(3) == "-" and exponent >= 0:+ exponent_sign = ""+ exponent_text = str(abs(exponent)).rjust(exponent_places, "0")+ return f"{mantissa_text}E{exponent_sign}{exponent_text}"+++def _render_fraction(value: float, pattern: str) -> str | None:+ """按固定或占位 denominator 输出最接近的分数。"""++ match = re.search(r"([#0?]*)\s*([0#?]+)\/([0-9#?]+)", pattern)+ if match is None:+ return None+ integer_pattern, numerator_pattern, denominator_pattern = match.groups()+ whole = math.floor(abs(value)) if integer_pattern else 0+ fraction_value = abs(value) - whole+ fixed_denominator = int(denominator_pattern) if denominator_pattern.isdigit() else None+ if fixed_denominator:+ denominator = fixed_denominator+ numerator = int(Decimal(format(fraction_value * denominator, ".15g")).quantize(Decimal(1), rounding=ROUND_HALF_UP))+ else:+ max_denominator = max(1, 10 ** len(denominator_pattern) - 1)+ fraction = Fraction(fraction_value).limit_denominator(max_denominator)+ numerator, denominator = fraction.numerator, fraction.denominator+ if numerator == 0:+ return str(whole) if whole else ""+ if numerator >= denominator and integer_pattern:+ whole += numerator // denominator+ numerator %= denominator+ numerator_text = str(numerator).rjust(len(numerator_pattern), " " if "?" in numerator_pattern else "0")+ denominator_text = str(denominator).rjust(+ len(denominator_pattern),+ " " if "?" in denominator_pattern else "0",+ )+ fraction_text = f"{numerator_text}/{denominator_text}"+ return f"{whole} {fraction_text}" if whole else fraction_text+++def _render_decimal(value: float, pattern: str) -> str:+ """按整数、小数、分组、缩放与百分号占位符输出数值。"""++ percent_count = pattern.count("%")+ core = pattern.replace("%", "")+ placeholder_positions = [index for index, char in enumerate(core) if char in "0#?"]+ trailing_commas = 0+ if placeholder_positions:+ suffix = core[max(placeholder_positions) + 1 :]+ trailing_commas = suffix.count(",") if not suffix.strip(", ") else 0+ if trailing_commas:+ remove_from = max(placeholder_positions) + 1+ core = core[:remove_from] + core[remove_from:].replace(",", "")+ decimal_pos = core.find(".")+ integer_pattern = core if decimal_pos < 0 else core[:decimal_pos]+ fractional_pattern = "" if decimal_pos < 0 else core[decimal_pos + 1 :]+ scaled = value * (100**percent_count) / (1000**trailing_commas)+ integer_placeholders = "".join(char for char in integer_pattern if char in "0#?")+ fractional_placeholders = "".join(char for char in fractional_pattern if char in "0#?")+ decimal_places = len(fractional_placeholders)+ rounded = _decimal_quantize(abs(scaled), decimal_places)+ absolute_text = f"{rounded:.{decimal_places}f}"+ integer_text, _, fraction_text = absolute_text.partition(".")+ required_integer = integer_placeholders.count("0")+ if len(integer_text) < required_integer:+ integer_text = integer_text.rjust(required_integer, "0")+ if rounded == 0 and not required_integer and integer_placeholders:+ integer_text = ""+ if "," in integer_pattern and integer_text:+ integer_text = f"{int(integer_text):,}"+ if integer_placeholders.startswith("?") and integer_text:+ integer_text = integer_text.rjust(len(integer_placeholders), " ")+ visible_fraction = list(fraction_text)+ for index in range(len(fractional_placeholders) - 1, -1, -1):+ placeholder = fractional_placeholders[index]+ if placeholder == "0":+ break+ if index >= len(visible_fraction) or visible_fraction[index] != "0":+ break+ visible_fraction[index] = " " if placeholder == "?" else ""+ rendered_fraction = "".join(visible_fraction)+ show_decimal = decimal_pos >= 0 and (rendered_fraction != "" or not fractional_placeholders)+ result = integer_text+ if show_decimal:+ result += "." + rendered_fraction+ if scaled < 0:+ result = "-" + result+ return result + ("%" * percent_count)+++def _render_pattern(pattern: str, value: float, auto_minus: bool) -> str:+ """渲染一个已经选定的数值 section。"""++ if not pattern:+ return ""+ prefix, core, suffix = _extract_number_span(pattern)+ if core.casefold() == "general":+ body = format_general(abs(value) if not auto_minus else value)+ if value < 0 and not auto_minus:+ body = format_general(abs(value))+ return prefix + body + suffix+ if not any(char in core for char in "0#?"):+ return prefix + suffix+ if re.search(r"[Ee][+-][0#?]", core):+ body = _render_scientific(abs(value), core) or format_general(abs(value))+ elif "/" in core:+ body = _render_fraction(abs(value), core) or format_general(abs(value))+ else:+ body = _render_decimal(abs(value), core)+ if auto_minus and value < 0:+ body = "-" + body+ return prefix + body + suffix+++def format_number(value: float, format_code: str | None, *, date1904: bool) -> str:+ """使用 Excel format code 渲染数值,无法解析时退回 General。"""++ if format_code is None or not math.isfinite(value):+ return format_general(value)+ sections = _parse_sections(format_code)+ if sections is None:+ return format_general(value)+ chosen = _choose_numeric_section(sections, value)+ if chosen is None:+ return format_general(value)+ section, selected_value, auto_minus = chosen+ pattern, _, _ = _strip_brackets(section.pattern)+ parts = _date_parts(pattern)+ if parts is not None:+ return _render_serial(selected_value, date1904=date1904, parts=parts)+ try:+ return _render_pattern(pattern, selected_value, auto_minus)+ except (InvalidOperation, OverflowError, ValueError, ZeroDivisionError):+ return format_general(value)+++def format_text(text: str, format_code: str | None) -> str:+ """应用第四个文本 section;没有文本 section 时保持原文。"""++ if format_code is None:+ return text+ sections = _parse_sections(format_code)+ if sections is None:+ return text+ if len(sections) == 4:+ pattern = _literalize(sections[3].pattern)+ return pattern.replace("@", text)+ if len(sections) == 1 and "@" in sections[0].pattern:+ return _literalize(sections[0].pattern).replace("@", text)+ return textdiff --git a/mineru/model/flash/xls/parser.py b/mineru/model/flash/xls/parser.pynew file mode 100644index 00000000..fc8e3f6f--- /dev/null+++ b/mineru/model/flash/xls/parser.py@@ -0,0 +1,1070 @@+# Copyright (c) Opendatalab. All rights reserved.++"""纯 Python 解析 Excel 97–2003 Workbook BIFF stream。"""++from __future__ import annotations++from dataclasses import dataclass, field+import struct+from urllib.parse import urlparse+import uuid++from loguru import logger++from mineru.model.flash.legacy_office.errors import (+ LegacyOfficeEncryptedError,+ LegacyOfficeMalformedError,+)+from mineru.model.flash.legacy_office.officeart import (+ OfficeArtShape,+ OfficeImagePayload,+ decode_bstore,+ extract_excel_shapes,+)+from mineru.model.flash.office.image import serialize_office_image++from .chart import chart_source_axes+from .models import (+ XlsCell,+ XlsChart,+ XlsFontStyle,+ XlsImage,+ XlsRichRun,+ XlsRichText,+ XlsSheet,+ XlsWorkbook,+)+from .number_format import builtin_number_format, format_number, format_text+from .records import (+ BOF,+ CONTINUE,+ EOF,+ BiffRecord,+ RecordBudget,+ SegmentReader,+ collect_continues,+ get_f64,+ get_u16,+ get_u32,+ iter_records,+ record_at,+)+from .strings import (+ DecodedString,+ clean_text,+ codepage_name,+ read_biff8_string,+ read_byte_string,+ read_txo_text,+ to_rich_text,+)++FILEPASS = 0x002F+CODEPAGE = 0x0042+DATEMODE = 0x0022+BOUNDSHEET = 0x0085+SST = 0x00FC+FORMAT = 0x041E+XF = 0x00E0+FONT = 0x0031+ROW = 0x0208+COLINFO = 0x007D+MERGEDCELLS = 0x00E5+LABELSST = 0x00FD+LABEL = 0x0204+RSTRING = 0x00D6+NUMBER = 0x0203+RK = 0x027E+MULRK = 0x00BD+BOOLERR = 0x0205+FORMULA = 0x0006+STRING = 0x0207+MSODRAWINGGROUP = 0x00EB+MSODRAWING = 0x00EC+OBJ = 0x005D+TXO = 0x01B6+HLINK = 0x01B8+SUPBOOK = 0x01AE+EXTERNSHEET = 0x0017++WORKBOOK_GLOBALS_SUBSTREAM = 0x0005+WORKSHEET_SUBSTREAM = 0x0010+CHART_SUBSTREAM = 0x0020+MAX_ROWS = 65_536+MAX_COLS = 256++OBJ_CHART = 0x0005+OBJ_TEXTBOX = 0x0006+OBJ_PICTURE = 0x0008+OBJ_CHECKBOX = 0x000B+++@dataclass(frozen=True, slots=True)+class _BoundSheet:+ """BoundSheet8 目录项。"""++ name: str+ offset: int+ visible: bool+ sheet_type: int+++@dataclass(frozen=True, slots=True)+class _CellFormat:+ """XF 解析后的字体索引和数值格式代码。"""++ font_index: int+ format_code: str | None+++@dataclass(slots=True)+class _Globals:+ """Workbook Globals Substream 中供所有工作表共享的状态。"""++ biff8: bool+ date1904: bool = False+ encoding: str = "cp1252"+ sheets: list[_BoundSheet] = field(default_factory=list)+ strings: list[DecodedString] = field(default_factory=list)+ fonts: list[XlsFontStyle] = field(default_factory=list)+ formats: list[_CellFormat] = field(default_factory=list)+ images: dict[int, OfficeImagePayload] = field(default_factory=dict)+ extern_sheets: list[int | None] = field(default_factory=list)++ def read_string(+ self,+ reader: SegmentReader,+ *,+ short: bool,+ rich: bool = False,+ ) -> DecodedString | None:+ """按当前 BIFF 版本和 codepage 读取字符串。"""++ if self.biff8:+ return read_biff8_string(reader, short=short, rich=rich)+ return read_byte_string(reader, short=short, encoding=self.encoding)++ def cell_format(self, index: int) -> _CellFormat:+ """解析越界 XF 时返回 General 与无字体的稳定默认值。"""++ if 0 <= index < len(self.formats):+ return self.formats[index]+ return _CellFormat(font_index=0, format_code=None)+++@dataclass(slots=True)+class _SheetObject:+ """一个 OBJ 记录及其后续 TXO 可见文本。"""++ object_type: int+ object_id: int+ checked: bool | None = None+ text: XlsRichText | None = None+ shape: OfficeArtShape | None = None+++def _error_literal(code: int) -> str | None:+ """把 BIFF error code 转成 Excel 可见错误文本。"""++ return {+ 0x00: "#NULL!",+ 0x07: "#DIV/0!",+ 0x0F: "#VALUE!",+ 0x17: "#REF!",+ 0x1D: "#NAME?",+ 0x24: "#NUM!",+ 0x2A: "#N/A",+ 0x2B: "#GETTING_DATA",+ }.get(int(code))+++def _rk_number(value: int) -> float:+ """解码 RK 压缩整数或截断双精度数。"""++ if value & 0x02:+ signed = struct.unpack("<i", struct.pack("<I", value))[0]+ number = float(signed >> 2)+ else:+ number = struct.unpack("<d", struct.pack("<Q", (value & 0xFFFF_FFFC) << 32))[0]+ return number / 100.0 if value & 0x01 else number+++def _read_font(payload: bytes, *, biff8: bool) -> XlsFontStyle:+ """提取 FONT 中可映射为 MinerU 行内标签的字符属性。"""++ if len(payload) < 11:+ return XlsFontStyle()+ flags = int(get_u16(payload, 2) or 0)+ weight = int(get_u16(payload, 6) or 400)+ escapement = int(get_u16(payload, 8) or 0)+ underline = int(payload[10])+ return XlsFontStyle(+ bold=weight >= 700,+ italic=bool(flags & 0x0002),+ strike=bool(flags & 0x0008),+ underline=underline != 0,+ superscript=escapement == 1,+ subscript=escapement == 2,+ )+++def _read_boundsheet(payload: bytes, globals_: _Globals) -> _BoundSheet | None:+ """解析 sheet 偏移、可见性、类型和名称。"""++ if len(payload) < 8:+ return None+ offset = get_u32(payload, 0)+ if offset is None:+ return None+ reader = SegmentReader([payload[6:]])+ decoded = globals_.read_string(reader, short=True)+ if decoded is None:+ return None+ return _BoundSheet(+ name=clean_text(decoded.text) or "Sheet",+ offset=int(offset),+ visible=(payload[4] & 0x03) == 0,+ sheet_type=int(payload[5]),+ )+++def _read_sst(segments: list[bytes]) -> list[DecodedString]:+ """读取共享字符串表,并允许损坏尾部保留已完成的 strings。"""++ reader = SegmentReader(segments)+ total = reader.u32()+ unique = reader.u32()+ if total is None or unique is None:+ return []+ strings: list[DecodedString] = []+ while len(strings) < unique:+ decoded = read_biff8_string(reader, short=False, rich=True)+ if decoded is None:+ logger.warning(+ "XLS_SST_TRUNCATED: shared string table stopped at entry {}",+ len(strings),+ )+ break+ strings.append(decoded)+ return strings+++def _read_supbook(payload: bytes) -> bool:+ """判断 SUPBOOK 是否表示当前工作簿内部 sheet 集合。"""++ return len(payload) >= 4 and get_u16(payload, 2) == 0x0401+++def _read_extern_sheets(+ payload: bytes,+ internal_supbooks: list[bool],+) -> list[int | None]:+ """把 XTI entries 解析为内部工作表索引。"""++ count = min(int(get_u16(payload, 0) or 0), max(0, (len(payload) - 2) // 6))+ result: list[int | None] = []+ for index in range(count):+ offset = 2 + index * 6+ supbook, first_sheet, last_sheet = struct.unpack_from("<3H", payload, offset)+ if (+ supbook < len(internal_supbooks)+ and internal_supbooks[supbook]+ and first_sheet == last_sheet+ and first_sheet < 0xFFFE+ ):+ result.append(int(first_sheet))+ else:+ result.append(None)+ return result+++def _read_globals(data: bytes, budget: RecordBudget) -> _Globals:+ """解析 Workbook Globals Substream 及共享图片资源。"""++ first = record_at(data, 0, budget=budget)+ if first is None or first.record_type != BOF:+ raise LegacyOfficeMalformedError("workbook stream does not start with a BOF record")+ if get_u16(first.payload, 2) not in {WORKBOOK_GLOBALS_SUBSTREAM, None}:+ raise LegacyOfficeMalformedError("first BIFF substream is not workbook globals")+ version = get_u16(first.payload, 0)+ if version not in {0x0500, 0x0600}:+ raise LegacyOfficeMalformedError(f"unsupported BIFF version: {version!r}")+ globals_ = _Globals(biff8=version == 0x0600)+ raw_formats: dict[int, str] = {}+ raw_xfs: list[tuple[int, int]] = []+ drawing_chunks: list[bytes] = []+ internal_supbooks: list[bool] = []+ extern_payloads: list[bytes] = []+ cursor = first.next_offset+ depth = 1+ while cursor < len(data):+ record = record_at(data, cursor, budget=budget)+ if record is None:+ logger.warning("XLS_GLOBALS_TRUNCATED: globals end at byte {}", cursor)+ break+ cursor = record.next_offset+ if record.record_type == BOF:+ depth += 1+ continue+ if record.record_type == EOF:+ depth -= 1+ if depth == 0:+ break+ continue+ if depth != 1:+ continue+ if record.record_type == FILEPASS:+ raise LegacyOfficeEncryptedError("password-protected XLS is not supported")+ if record.record_type == CODEPAGE:+ globals_.encoding = codepage_name(int(get_u16(record.payload, 0) or 1252))+ elif record.record_type == DATEMODE:+ globals_.date1904 = get_u16(record.payload, 0) == 1+ elif record.record_type == FONT:+ globals_.fonts.append(_read_font(record.payload, biff8=globals_.biff8))+ elif record.record_type == BOUNDSHEET:+ sheet = _read_boundsheet(record.payload, globals_)+ if sheet is not None and sheet.sheet_type != 0x06:+ globals_.sheets.append(sheet)+ elif record.record_type == FORMAT:+ format_id = get_u16(record.payload, 0)+ if format_id is not None:+ reader = SegmentReader([record.payload[2:]])+ decoded = globals_.read_string(reader, short=not globals_.biff8)+ if decoded is not None:+ raw_formats[int(format_id)] = decoded.text+ elif record.record_type == XF:+ font_index = int(get_u16(record.payload, 0) or 0)+ format_id = int(get_u16(record.payload, 2) or 0)+ raw_xfs.append((font_index, format_id))+ elif record.record_type == SST and globals_.biff8:+ segments, cursor = collect_continues(data, record, budget=budget)+ globals_.strings = _read_sst(segments)+ elif record.record_type == MSODRAWINGGROUP:+ segments, cursor = collect_continues(data, record, budget=budget)+ drawing_chunks.extend(segments)+ elif record.record_type == SUPBOOK:+ internal_supbooks.append(_read_supbook(record.payload))+ elif record.record_type == EXTERNSHEET:+ extern_payloads.append(record.payload)++ globals_.formats = [+ _CellFormat(+ font_index=font_index,+ format_code=raw_formats.get(format_id) or builtin_number_format(format_id),+ )+ for font_index, format_id in raw_xfs+ ]+ for payload in extern_payloads:+ globals_.extern_sheets.extend(_read_extern_sheets(payload, internal_supbooks))+ if drawing_chunks:+ globals_.images = decode_bstore(b"".join(drawing_chunks), charge=budget.charge)+ return globals_+++def _cell_ref(payload: bytes) -> tuple[int, int, int] | None:+ """读取 cell header,并拒绝超出 BIFF8 网格的列。"""++ if len(payload) < 6:+ return None+ row, col, xf_index = struct.unpack_from("<3H", payload, 0)+ if row >= MAX_ROWS or col >= MAX_COLS:+ return None+ return int(row), int(col), int(xf_index)+++def _resolved_rich_text(+ decoded: DecodedString,+ globals_: _Globals,+ xf_index: int,+) -> XlsRichText:+ """应用 text number format,并在原文未变时保留 rich runs。"""++ cell_format = globals_.cell_format(xf_index)+ formatted = format_text(decoded.text, cell_format.format_code)+ if formatted != decoded.text:+ return XlsRichText(formatted)+ return to_rich_text(decoded, globals_.fonts)+++def _put_cell(+ sheet: XlsSheet,+ row: int,+ col: int,+ value: XlsRichText,+) -> None:+ """仅保存非空文本,并覆盖同坐标较早的缓存记录。"""++ if not value.text:+ return+ sheet.cells[(row, col)] = XlsCell(row=row, col=col, value=value)+++def _append_cell_text(+ sheet: XlsSheet,+ row: int,+ col: int,+ value: XlsRichText,+) -> None:+ """把 drawing/control 文本追加到 anchor 单元格且平移 rich runs。"""++ if not value.text:+ return+ existing = sheet.cells.get((row, col))+ if existing is None:+ _put_cell(sheet, row, col, value)+ return+ separator = "\n" if existing.value.text else ""+ shift = len(existing.value.text) + len(separator)+ shifted = tuple(+ XlsRichRun(+ start=run.start + shift,+ end=run.end + shift,+ style=run.style,+ )+ for run in value.runs+ )+ existing.value = XlsRichText(+ text=existing.value.text + separator + value.text,+ runs=existing.value.runs + shifted,+ )+++def _read_label_string(+ segments: list[bytes],+ globals_: _Globals,+ *,+ rich_record: bool,+) -> DecodedString | None:+ """读取 LABEL/RSTRING 的字符串并恢复 RSTRING formatting runs。"""++ if not segments or len(segments[0]) < 6:+ return None+ adjusted = [segments[0][6:], *segments[1:]]+ reader = SegmentReader(adjusted)+ decoded = globals_.read_string(reader, short=False)+ if decoded is None or not rich_record:+ return decoded+ run_count = reader.u16()+ if run_count is None:+ return decoded+ starts: list[tuple[int, int]] = []+ for _ in range(run_count):+ raw = reader.read_across(4)+ if raw is None:+ break+ character_index, font_index = struct.unpack("<HH", raw)+ starts.append((int(character_index), int(font_index)))+ return DecodedString(decoded.text, tuple(starts))+++def _read_obj(payload: bytes) -> _SheetObject | None:+ """解析 OBJ subrecords 中的对象类型、id 与 checkbox 状态。"""++ cursor = 0+ object_type: int | None = None+ object_id = 0+ checked: bool | None = None+ while cursor + 4 <= len(payload):+ sub_type, length = struct.unpack_from("<HH", payload, cursor)+ data_start = cursor + 4+ data_end = data_start + int(length)+ if data_end > len(payload):+ break+ body = payload[data_start:data_end]+ if sub_type == 0x0015 and len(body) >= 4:+ object_type, object_id = struct.unpack_from("<HH", body, 0)+ elif sub_type == 0x0012 and len(body) >= 2:+ state = int(get_u16(body, 0) or 0)+ checked = state == 1 if state in {0, 1} else None+ if sub_type == 0:+ break+ cursor = data_end+ if object_type is None:+ return None+ return _SheetObject(int(object_type), int(object_id), checked=checked)+++def _sanitize_hyperlink_target(target: str) -> str | None:+ """保留 XlsxModel 允许的网络、邮件、内部与相对链接。"""++ candidate = target.strip().replace("\x00", "")+ if not candidate:+ return None+ lowered = candidate.casefold()+ if lowered.startswith(("javascript:", "data:", "vbscript:", "file:")):+ return None+ parsed = urlparse(candidate)+ if parsed.scheme and parsed.scheme.casefold() not in {"http", "https", "mailto", "ftp"}:+ return None+ if parsed.scheme.casefold() == "mailto" and not parsed.path:+ return None+ return candidate+++def _read_hyperlink_unicode(payload: bytes, cursor: int) -> tuple[str | None, int]:+ """读取 Hyperlink Object 中含末尾 NUL 的 UTF-16 字符串。"""++ if cursor + 4 > len(payload):+ return None, len(payload)+ character_count = int(struct.unpack_from("<I", payload, cursor)[0])+ cursor += 4+ byte_count = character_count * 2+ if byte_count < 0 or cursor + byte_count > len(payload):+ return None, len(payload)+ text = payload[cursor : cursor + byte_count].decode("utf-16le", "replace").rstrip("\x00")+ return clean_text(text), cursor + byte_count+++def _read_url_moniker(payload: bytes, cursor: int) -> tuple[str | None, int]:+ """读取 URL Moniker 的 UTF-16 URL,忽略可选尾部元数据。"""++ if cursor + 4 > len(payload):+ return None, len(payload)+ byte_count = int(struct.unpack_from("<I", payload, cursor)[0])+ cursor += 4+ if byte_count < 0 or cursor + byte_count > len(payload):+ return None, len(payload)+ raw = payload[cursor : cursor + byte_count]+ usable = raw[: len(raw) - (len(raw) % 2)]+ text = usable.decode("utf-16le", "replace").split("\x00", 1)[0]+ return clean_text(text), cursor + byte_count+++def _read_file_moniker(payload: bytes, cursor: int) -> tuple[str | None, int]:+ """尽力读取 File Moniker 的 ANSI 或 Unicode 路径。"""++ if cursor + 6 > len(payload):+ return None, len(payload)+ anti_count = int(struct.unpack_from("<H", payload, cursor)[0])+ ansi_length = int(struct.unpack_from("<I", payload, cursor + 2)[0])+ cursor += 6+ if cursor + ansi_length > len(payload):+ return None, len(payload)+ ansi = payload[cursor : cursor + ansi_length].split(b"\x00", 1)[0]+ cursor += ansi_length+ path = ("../" * anti_count) + ansi.decode("cp1252", "replace")+ return clean_text(path), cursor+++def _read_hyperlink_target(payload: bytes) -> str | None:+ """解析 HLink 中的 Hyperlink Object 并返回经过白名单过滤的目标。"""++ if len(payload) < 32:+ return None+ cursor = 24+ version, flags = struct.unpack_from("<II", payload, cursor)+ cursor += 8+ if version != 2:+ return None+ if flags & 0x10:+ _, cursor = _read_hyperlink_unicode(payload, cursor)+ if flags & 0x80:+ _, cursor = _read_hyperlink_unicode(payload, cursor)+ target: str | None = None+ blocked_local_file = False+ if flags & 0x01:+ if flags & 0x0100:+ target, cursor = _read_hyperlink_unicode(payload, cursor)+ elif cursor + 16 <= len(payload):+ moniker = uuid.UUID(bytes_le=payload[cursor : cursor + 16])+ cursor += 16+ if moniker == uuid.UUID("79eac9e0-baf9-11ce-8c82-00aa004ba90b"):+ target, cursor = _read_url_moniker(payload, cursor)+ elif moniker == uuid.UUID("00000303-0000-0000-c000-000000000046"):+ _, cursor = _read_file_moniker(payload, cursor)+ blocked_local_file = True+ location: str | None = None+ if flags & 0x08:+ location, cursor = _read_hyperlink_unicode(payload, cursor)+ if location:+ target = f"{target}#{location}" if target else f"#{location}"+ if blocked_local_file:+ logger.warning("XLS_HYPERLINK_BLOCKED: local File Moniker")+ return None+ sanitized = _sanitize_hyperlink_target(target or "")+ if target and sanitized is None:+ logger.warning("XLS_HYPERLINK_BLOCKED: target={!r}", target)+ return sanitized+++def _apply_hlink(+ sheet: XlsSheet,+ payload: bytes,+ pending: dict[tuple[int, int], str],+) -> None:+ """把 HLink 范围目标暂存到所有覆盖单元格。"""++ if len(payload) < 8:+ return+ row_first, row_last, col_first, col_last = struct.unpack_from("<4H", payload, 0)+ target = _read_hyperlink_target(payload)+ if target is None:+ return+ for row in range(min(row_first, row_last), min(max(row_first, row_last), MAX_ROWS - 1) + 1):+ for col in range(min(col_first, col_last), min(max(col_first, col_last), MAX_COLS - 1) + 1):+ pending[(int(row), int(col))] = target+++def _shape_anchor(shape: OfficeArtShape | None) -> tuple[int, int] | None:+ """返回 shape 左上角 cell anchor。"""++ if shape is None or shape.anchor is None:+ return None+ return shape.anchor[0], shape.anchor[1]+++def _serialize_payload(payload: OfficeImagePayload) -> str | None:+ """使用共享 Office 图片策略序列化 BLIP。"""++ return serialize_office_image(+ payload.data,+ part_name=f"picture.{payload.extension}",+ content_type=payload.content_type,+ )+++def _bind_objects(+ sheet: XlsSheet,+ objects: list[_SheetObject],+ drawing_data: bytes,+ chart_streams: list[list[BiffRecord]],+ *,+ globals_: _Globals,+ sheet_index: int,+ budget: RecordBudget,+) -> None:+ """按 drawing/OBJ 顺序绑定文本框、复选框、图片与嵌入图表。"""++ shapes = extract_excel_shapes(drawing_data, charge=budget.charge) if drawing_data else []+ if len(shapes) != len(objects):+ logger.warning(+ "XLS_DRAWING_OBJECT_MISMATCH: sheet={!r}, shapes={}, objects={}",+ sheet.name,+ len(shapes),+ len(objects),+ )+ for object_, shape in zip(objects, shapes, strict=False):+ object_.shape = shape+ chart_objects = [object_ for object_ in objects if object_.object_type == OBJ_CHART]+ for object_ in objects:+ shape = object_.shape+ if shape is None or shape.hidden:+ continue+ anchor = _shape_anchor(shape)+ if anchor is None:+ continue+ row, col = anchor+ if object_.object_type == OBJ_TEXTBOX and object_.text is not None:+ _append_cell_text(sheet, row, col, object_.text)+ elif object_.object_type == OBJ_CHECKBOX and object_.checked is not None:+ marker = "[x]" if object_.checked else "[ ]"+ caption = object_.text.text.strip() if object_.text is not None else ""+ _append_cell_text(sheet, row, col, XlsRichText(f"{marker} {caption}".rstrip()))+ if object_.object_type in {OBJ_PICTURE, OBJ_CHART} or shape.pib is not None:+ payload = globals_.images.get(int(shape.pib or 0))+ if payload is not None:+ image_base64 = _serialize_payload(payload)+ if image_base64 and object_.object_type != OBJ_CHART:+ sheet.images.append(XlsImage(row=row, col=col, image_base64=image_base64))++ for index, object_ in enumerate(chart_objects):+ if object_.shape is None or object_.shape.hidden:+ continue+ anchor = _shape_anchor(object_.shape)+ if anchor is None:+ continue+ axes = (+ chart_source_axes(+ chart_streams[index],+ current_sheet_index=sheet_index,+ extern_sheets=globals_.extern_sheets,+ )+ if index < len(chart_streams)+ else None+ )+ preview: str | None = None+ if object_.shape.pib is not None:+ payload = globals_.images.get(object_.shape.pib)+ preview = _serialize_payload(payload) if payload is not None else None+ if axes is None:+ if preview:+ sheet.charts.append(+ XlsChart(+ row=anchor[0],+ col=anchor[1],+ source_rows=(),+ source_cols=(),+ image_base64=preview,+ )+ )+ else:+ logger.warning(+ "XLS_CHART_SOURCE_UNSUPPORTED: sheet={!r}, object_id={}",+ sheet.name,+ object_.object_id,+ )+ continue+ rows, cols = axes+ sheet.charts.append(+ XlsChart(+ row=anchor[0],+ col=anchor[1],+ source_rows=tuple(rows),+ source_cols=tuple(cols),+ image_base64=preview,+ )+ )+++def _read_sheet(+ data: bytes,+ globals_: _Globals,+ descriptor: _BoundSheet,+ offset: int,+ *,+ sheet_index: int,+ recovered: bool,+ budget: RecordBudget,+) -> XlsSheet | None:+ """解析一个 worksheet substream 并绑定其 drawing/chart 对象。"""++ first = record_at(data, offset, budget=budget)+ if (+ first is None+ or first.record_type != BOF+ or get_u16(first.payload, 2) != WORKSHEET_SUBSTREAM+ ):+ return None+ sheet = XlsSheet(+ name=descriptor.name,+ visible=descriptor.visible,+ recovered=recovered,+ )+ cursor = first.next_offset+ depth = 1+ active_chart: list[BiffRecord] | None = None+ chart_streams: list[list[BiffRecord]] = []+ drawing_chunks: list[bytes] = []+ objects: list[_SheetObject] = []+ pending_formula: tuple[int, int, int] | None = None+ pending_links: dict[tuple[int, int], str] = {}++ while cursor < len(data):+ record = record_at(data, cursor, budget=budget)+ if record is None:+ logger.warning(+ "XLS_SHEET_TRUNCATED: sheet={!r}, byte={}",+ sheet.name,+ cursor,+ )+ break+ cursor = record.next_offset+ if active_chart is not None:+ active_chart.append(record)+ if record.record_type == BOF:+ depth += 1+ elif record.record_type == EOF:+ depth -= 1+ if depth == 1:+ chart_streams.append(active_chart)+ active_chart = None+ continue+ if record.record_type == BOF:+ depth += 1+ if depth == 2 and get_u16(record.payload, 2) == CHART_SUBSTREAM:+ active_chart = [record]+ continue+ if record.record_type == EOF:+ depth -= 1+ if depth == 0:+ break+ continue+ if depth != 1:+ continue++ if record.record_type == MERGEDCELLS:+ count = min(int(get_u16(record.payload, 0) or 0), max(0, (len(record.payload) - 2) // 8))+ for index in range(count):+ row_first, row_last, col_first, col_last = struct.unpack_from(+ "<4H", record.payload, 2 + index * 8+ )+ row_start, row_end = sorted((int(row_first), int(row_last)))+ col_start, col_end = sorted((int(col_first), int(col_last)))+ if col_start >= MAX_COLS or (row_start == row_end and col_start == col_end):+ continue+ sheet.merges.append(+ (+ row_start,+ col_start,+ min(row_end, MAX_ROWS - 1),+ min(col_end, MAX_COLS - 1),+ )+ )+ elif record.record_type == LABELSST:+ reference = _cell_ref(record.payload)+ string_index = get_u32(record.payload, 6)+ if reference is not None and string_index is not None and string_index < len(globals_.strings):+ row, col, xf_index = reference+ _put_cell(+ sheet,+ row,+ col,+ _resolved_rich_text(globals_.strings[int(string_index)], globals_, xf_index),+ )+ elif record.record_type in {LABEL, RSTRING}:+ segments, cursor = collect_continues(data, record, budget=budget)+ reference = _cell_ref(record.payload)+ decoded = _read_label_string(+ segments,+ globals_,+ rich_record=record.record_type == RSTRING,+ )+ if reference is not None and decoded is not None:+ row, col, xf_index = reference+ _put_cell(sheet, row, col, _resolved_rich_text(decoded, globals_, xf_index))+ elif record.record_type == NUMBER:+ reference = _cell_ref(record.payload)+ value = get_f64(record.payload, 6)+ if reference is not None and value is not None:+ row, col, xf_index = reference+ cell_format = globals_.cell_format(xf_index)+ _put_cell(+ sheet,+ row,+ col,+ XlsRichText(+ format_number(+ value,+ cell_format.format_code,+ date1904=globals_.date1904,+ )+ ),+ )+ elif record.record_type == RK:+ reference = _cell_ref(record.payload)+ raw_value = get_u32(record.payload, 6)+ if reference is not None and raw_value is not None:+ row, col, xf_index = reference+ cell_format = globals_.cell_format(xf_index)+ _put_cell(+ sheet,+ row,+ col,+ XlsRichText(+ format_number(+ _rk_number(raw_value),+ cell_format.format_code,+ date1904=globals_.date1904,+ )+ ),+ )+ elif record.record_type == MULRK and len(record.payload) >= 6:+ row = int(get_u16(record.payload, 0) or 0)+ first_col = int(get_u16(record.payload, 2) or 0)+ pair_count = max(0, (len(record.payload) - 6) // 6)+ for index in range(pair_count):+ xf_index = int(get_u16(record.payload, 4 + index * 6) or 0)+ raw_value = get_u32(record.payload, 6 + index * 6)+ col = first_col + index+ if raw_value is None or col >= MAX_COLS:+ break+ cell_format = globals_.cell_format(xf_index)+ _put_cell(+ sheet,+ row,+ col,+ XlsRichText(+ format_number(+ _rk_number(raw_value),+ cell_format.format_code,+ date1904=globals_.date1904,+ )+ ),+ )+ elif record.record_type == BOOLERR:+ reference = _cell_ref(record.payload)+ if reference is not None and len(record.payload) >= 8:+ row, col, _ = reference+ value, is_error = record.payload[6], record.payload[7]+ text = _error_literal(value) if is_error == 1 else ("TRUE" if value else "FALSE")+ if text:+ _put_cell(sheet, row, col, XlsRichText(text))+ elif record.record_type == FORMULA:+ reference = _cell_ref(record.payload)+ if reference is not None and len(record.payload) >= 14:+ row, col, xf_index = reference+ cached = record.payload[6:14]+ if cached[6:8] == b"\xff\xff":+ kind = cached[0]+ if kind == 0x00:+ pending_formula = (row, col, xf_index)+ elif kind == 0x01:+ _put_cell(sheet, row, col, XlsRichText("TRUE" if cached[2] else "FALSE"))+ elif kind == 0x02:+ error = _error_literal(cached[2])+ if error:+ _put_cell(sheet, row, col, XlsRichText(error))+ else:+ value = get_f64(record.payload, 6)+ if value is not None:+ cell_format = globals_.cell_format(xf_index)+ _put_cell(+ sheet,+ row,+ col,+ XlsRichText(+ format_number(+ value,+ cell_format.format_code,+ date1904=globals_.date1904,+ )+ ),+ )+ elif record.record_type == STRING:+ segments, cursor = collect_continues(data, record, budget=budget)+ if pending_formula is not None:+ reader = SegmentReader(segments)+ decoded = globals_.read_string(reader, short=False)+ if decoded is not None:+ if decoded.text.lstrip().upper().startswith(("=DISPIMG(", "=_XLFN.DISPIMG(")):+ # 旧版文件无法携带现代 DISPIMG 计算语义,按 Office 回存结果稳定降级。+ decoded = DecodedString("#NAME?")+ row, col, xf_index = pending_formula+ _put_cell(sheet, row, col, _resolved_rich_text(decoded, globals_, xf_index))+ pending_formula = None+ elif record.record_type == MSODRAWING:+ segments, cursor = collect_continues(data, record, budget=budget)+ drawing_chunks.extend(segments)+ elif record.record_type == OBJ:+ object_ = _read_obj(record.payload)+ if object_ is not None:+ objects.append(object_)+ elif record.record_type == TXO:+ segments, cursor = collect_continues(data, record, budget=budget)+ if objects:+ objects[-1].text = read_txo_text(+ record.payload,+ segments[1:],+ globals_.fonts,+ )+ elif record.record_type == HLINK:+ _apply_hlink(sheet, record.payload, pending_links)+ elif record.record_type in {ROW, COLINFO, CONTINUE}:+ # 用户明确要求隐藏行列中的内容仍参与表格重建。+ pass++ for coordinate, target in pending_links.items():+ cell = sheet.cells.get(coordinate)+ if cell is not None:+ cell.hyperlink = target+ _bind_objects(+ sheet,+ objects,+ b"".join(drawing_chunks),+ chart_streams,+ globals_=globals_,+ sheet_index=sheet_index,+ budget=budget,+ )+ return sheet+++def _worksheet_bof_offsets(data: bytes) -> list[int]:+ """扫描所有可识别 worksheet BOF 偏移,供坏目录恢复使用。"""++ return [+ record.offset+ for record in iter_records(data)+ if record.record_type == BOF and get_u16(record.payload, 2) == WORKSHEET_SUBSTREAM+ ]+++def _is_worksheet_offset(data: bytes, offset: int) -> bool:+ """判断 BoundSheet offset 是否精确指向 worksheet BOF。"""++ record = record_at(data, offset)+ return bool(+ record is not None+ and record.record_type == BOF+ and get_u16(record.payload, 2) == WORKSHEET_SUBSTREAM+ )+++def parse_xls_workbook(data: bytes) -> XlsWorkbook:+ """解析一个 Workbook/Book stream,并按目录顺序恢复 worksheets。"""++ if not data:+ raise LegacyOfficeMalformedError("empty Workbook stream")+ budget = RecordBudget()+ globals_ = _read_globals(data, budget)+ candidates = _worksheet_bof_offsets(data)+ used_offsets: set[int] = set()+ sheets: list[XlsSheet] = []++ descriptor_entries = [+ (index, sheet)+ for index, sheet in enumerate(globals_.sheets)+ if sheet.sheet_type == 0x00+ ]+ if not descriptor_entries and candidates:+ descriptor_entries = [+ (+ index - 1,+ _BoundSheet(+ name=f"Recovered Sheet {index}",+ offset=offset,+ visible=True,+ sheet_type=0,+ ),+ )+ for index, offset in enumerate(candidates, start=1)+ ]+ if not descriptor_entries and not candidates:+ raise LegacyOfficeMalformedError("workbook contains no worksheet substream")++ for sheet_index, descriptor in descriptor_entries:+ resolved_offset: int | None = None+ recovered = False+ if _is_worksheet_offset(data, descriptor.offset) and descriptor.offset not in used_offsets:+ resolved_offset = descriptor.offset+ else:+ resolved_offset = next((offset for offset in candidates if offset not in used_offsets), None)+ recovered = resolved_offset is not None+ if recovered:+ logger.warning(+ "XLS_BOUNDSHEET_RECOVERED: sheet={!r}, old_offset={}, new_offset={}",+ descriptor.name,+ descriptor.offset,+ resolved_offset,+ )+ if resolved_offset is None:+ logger.warning("XLS_SHEET_UNREADABLE: keeping empty sheet {!r}", descriptor.name)+ sheets.append(+ XlsSheet(+ name=descriptor.name,+ visible=descriptor.visible,+ recovered=True,+ )+ )+ continue+ used_offsets.add(resolved_offset)+ parsed = _read_sheet(+ data,+ globals_,+ descriptor,+ resolved_offset,+ sheet_index=sheet_index,+ recovered=recovered,+ budget=budget,+ )+ if parsed is None:+ sheets.append(+ XlsSheet(+ name=descriptor.name,+ visible=descriptor.visible,+ recovered=True,+ )+ )+ else:+ sheets.append(parsed)+ return XlsWorkbook(sheets=sheets)diff --git a/mineru/model/flash/xls/records.py b/mineru/model/flash/xls/records.pynew file mode 100644index 00000000..a1161b83--- /dev/null+++ b/mineru/model/flash/xls/records.py@@ -0,0 +1,240 @@+# Copyright (c) Opendatalab. All rights reserved.++"""有界读取 Excel 97–2003 BIFF 记录流。"""++from __future__ import annotations++from dataclasses import dataclass+import struct+from typing import Iterator++from loguru import logger++from mineru.model.flash.legacy_office.errors import LegacyOfficeResourceLimitError+from mineru.model.flash.legacy_office.limits import MAX_RECORDS++BOF = 0x0809+EOF = 0x000A+CONTINUE = 0x003C+++@dataclass(frozen=True, slots=True)+class BiffRecord:+ """一条已完成边界校验的 BIFF 记录。"""++ offset: int+ record_type: int+ payload: bytes+ next_offset: int+++@dataclass(slots=True)+class RecordBudget:+ """跨 globals、worksheet 与 OfficeArt 共享记录访问预算。"""++ count: int = 0++ def charge(self) -> None:+ """计入一条记录并在超过固定上限时硬失败。"""++ self.count += 1+ if self.count > MAX_RECORDS:+ raise LegacyOfficeResourceLimitError(+ f"workbook stream exceeds max_records={MAX_RECORDS}"+ )+++def get_u16(data: bytes, offset: int) -> int | None:+ """安全读取小端无符号 16 位整数。"""++ if offset < 0 or offset + 2 > len(data):+ return None+ return int(struct.unpack_from("<H", data, offset)[0])+++def get_i16(data: bytes, offset: int) -> int | None:+ """安全读取小端有符号 16 位整数。"""++ if offset < 0 or offset + 2 > len(data):+ return None+ return int(struct.unpack_from("<h", data, offset)[0])+++def get_u32(data: bytes, offset: int) -> int | None:+ """安全读取小端无符号 32 位整数。"""++ if offset < 0 or offset + 4 > len(data):+ return None+ return int(struct.unpack_from("<I", data, offset)[0])+++def get_f64(data: bytes, offset: int) -> float | None:+ """安全读取小端 IEEE-754 双精度数。"""++ if offset < 0 or offset + 8 > len(data):+ return None+ return float(struct.unpack_from("<d", data, offset)[0])+++def record_at(+ data: bytes,+ offset: int,+ *,+ budget: RecordBudget | None = None,+) -> BiffRecord | None:+ """读取指定偏移的 BIFF 记录,截断 header 或 body 返回空值。"""++ if offset < 0 or offset + 4 > len(data):+ return None+ record_type, length = struct.unpack_from("<HH", data, offset)+ body_start = offset + 4+ body_end = body_start + int(length)+ if body_end < body_start or body_end > len(data):+ return None+ if budget is not None:+ budget.charge()+ return BiffRecord(+ offset=offset,+ record_type=int(record_type),+ payload=data[body_start:body_end],+ next_offset=body_end,+ )+++def iter_records(+ data: bytes,+ *,+ start: int = 0,+ stop_at_eof: bool = False,+ budget: RecordBudget | None = None,+) -> Iterator[BiffRecord]:+ """顺序遍历 BIFF 记录,并在截断尾部保留已经完成的记录。"""++ cursor = start+ while cursor < len(data):+ if data[cursor:] and not any(data[cursor:]):+ return+ record = record_at(data, cursor, budget=budget)+ if record is None:+ logger.warning(+ "XLS_TRUNCATED_RECORD: workbook stream ends mid-record at byte {}",+ cursor,+ )+ return+ yield record+ cursor = record.next_offset+ if stop_at_eof and record.record_type == EOF:+ return+++def collect_continues(+ data: bytes,+ base: BiffRecord,+ *,+ budget: RecordBudget,+) -> tuple[list[bytes], int]:+ """收集紧随 base 的 CONTINUE bodies,并返回下一条非延续记录偏移。"""++ segments = [base.payload]+ cursor = base.next_offset+ while True:+ record = record_at(data, cursor)+ if record is None or record.record_type != CONTINUE:+ return segments, cursor+ budget.charge()+ segments.append(record.payload)+ cursor = record.next_offset+++class SegmentReader:+ """在基础记录及其 CONTINUE segments 上执行有界顺序读取。"""++ def __init__(self, segments: list[bytes]) -> None:+ """保存 segment 列表并把游标置于首段开头。"""++ self.segments = segments+ self.segment_index = 0+ self.offset = 0++ def remaining_in_segment(self) -> int:+ """返回当前 segment 尚未消费的字节数。"""++ if self.segment_index >= len(self.segments):+ return 0+ return len(self.segments[self.segment_index]) - self.offset++ def normalize(self) -> None:+ """跳过已经耗尽的 segments。"""++ while (+ self.segment_index < len(self.segments)+ and self.offset >= len(self.segments[self.segment_index])+ ):+ self.segment_index += 1+ self.offset = 0++ def next_segment(self) -> bool:+ """显式移动到下一 segment,若不存在则返回 False。"""++ if self.segment_index + 1 >= len(self.segments):+ return False+ self.segment_index += 1+ self.offset = 0+ return True++ def read(self, size: int) -> bytes | None:+ """只在当前 segment 内读取固定长度字段。"""++ self.normalize()+ if size < 0 or self.segment_index >= len(self.segments):+ return None+ segment = self.segments[self.segment_index]+ end = self.offset + size+ if end > len(segment):+ return None+ output = segment[self.offset:end]+ self.offset = end+ return output++ def read_across(self, size: int) -> bytes | None:+ """跨 segment 读取普通非字符数据。"""++ if size < 0:+ return None+ output = bytearray()+ remaining = size+ while remaining:+ self.normalize()+ available = self.remaining_in_segment()+ if available <= 0:+ return None+ take = min(available, remaining)+ chunk = self.read(take)+ if chunk is None:+ return None+ output.extend(chunk)+ remaining -= take+ return bytes(output)++ def skip(self, size: int) -> bool:+ """跨 segments 跳过指定字节数。"""++ return self.read_across(size) is not None++ def u8(self) -> int | None:+ """读取一个无符号 8 位整数。"""++ value = self.read(1)+ return int(value[0]) if value is not None else None++ def u16(self) -> int | None:+ """读取一个小端无符号 16 位整数。"""++ value = self.read(2)+ return int(struct.unpack("<H", value)[0]) if value is not None else None++ def u32(self) -> int | None:+ """读取一个小端无符号 32 位整数。"""++ value = self.read(4)+ return int(struct.unpack("<I", value)[0]) if value is not None else Nonediff --git a/mineru/model/flash/xls/strings.py b/mineru/model/flash/xls/strings.pynew file mode 100644index 00000000..c169f30e--- /dev/null+++ b/mineru/model/flash/xls/strings.py@@ -0,0 +1,211 @@+# Copyright (c) Opendatalab. All rights reserved.++"""BIFF5–BIFF8 字符串、富文本区间与 codepage 解码。"""++from __future__ import annotations++from dataclasses import dataclass+import re+import struct++from .models import XlsFontStyle, XlsRichRun, XlsRichText+from .records import SegmentReader+++@dataclass(frozen=True, slots=True)+class DecodedString:+ """已解码文本及以 UTF-16 code unit 表示的字体切换点。"""++ text: str+ font_starts: tuple[tuple[int, int], ...] = ()+++def clean_text(text: str) -> str:+ """规范换行、NUL 与不可见控制字符,同时保留制表符。"""++ normalized = text.replace("\r\n", "\n").replace("\r", "\n").rstrip("\x00")+ return re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", normalized)+++def codepage_name(codepage: int) -> str:+ """把 BIFF CODEPAGE 值映射为 Python codec 名称。"""++ return {+ 874: "cp874",+ 932: "shift_jis",+ 936: "gbk",+ 949: "euc_kr",+ 950: "big5",+ 1200: "utf-16le",+ 1250: "cp1250",+ 1251: "cp1251",+ 1252: "cp1252",+ 1253: "cp1253",+ 1254: "cp1254",+ 1255: "cp1255",+ 1256: "cp1256",+ 1257: "cp1257",+ 1258: "cp1258",+ }.get(int(codepage), "cp1252")+++def _decode_utf16_units(units: list[int]) -> str:+ """容错解码 UTF-16 code units。"""++ payload = struct.pack(f"<{len(units)}H", *units) if units else b""+ return payload.decode("utf-16le", "replace")+++def read_biff8_string(+ reader: SegmentReader,+ *,+ short: bool,+ rich: bool,+) -> DecodedString | None:+ """读取可跨 CONTINUE 且可切换压缩模式的 BIFF8 Unicode 字符串。"""++ character_count = reader.u8() if short else reader.u16()+ flags = reader.u8()+ if character_count is None or flags is None:+ return None+ wide = bool(flags & 0x01)+ run_count = reader.u16() if rich and flags & 0x08 else 0+ extension_size = reader.u32() if rich and flags & 0x04 else 0+ if run_count is None or extension_size is None:+ return None++ units: list[int] = []+ remaining = int(character_count)+ while remaining > 0:+ if reader.remaining_in_segment() == 0:+ if not reader.next_segment():+ return None+ repeated_flags = reader.u8()+ if repeated_flags is None:+ return None+ wide = bool(repeated_flags & 0x01)+ unit_size = 2 if wide else 1+ take = min(reader.remaining_in_segment() // unit_size, remaining)+ if take <= 0:+ return None+ payload = reader.read(take * unit_size)+ if payload is None:+ return None+ if wide:+ units.extend(struct.unpack(f"<{take}H", payload))+ else:+ units.extend(int(value) for value in payload)+ remaining -= take++ font_starts: list[tuple[int, int]] = []+ for _ in range(int(run_count)):+ run = reader.read_across(4)+ if run is None:+ break+ character_index, font_index = struct.unpack("<HH", run)+ if character_index <= character_count:+ font_starts.append((int(character_index), int(font_index)))+ if extension_size:+ reader.skip(int(extension_size))+ return DecodedString(+ text=clean_text(_decode_utf16_units(units)),+ font_starts=tuple(font_starts),+ )+++def read_byte_string(+ reader: SegmentReader,+ *,+ short: bool,+ encoding: str,+) -> DecodedString | None:+ """按 workbook CODEPAGE 读取 BIFF5/BIFF7 单字节字符串。"""++ character_count = reader.u8() if short else reader.u16()+ if character_count is None:+ return None+ payload = reader.read_across(int(character_count))+ if payload is None:+ return None+ try:+ text = payload.decode(encoding, "replace")+ except LookupError:+ text = payload.decode("cp1252", "replace")+ return DecodedString(clean_text(text))+++def utf16_unit_to_index(text: str, unit_offset: int) -> int:+ """把 UTF-16 code unit 偏移转换为 Python 字符索引。"""++ units = 0+ for index, char in enumerate(text):+ if units >= unit_offset:+ return index+ units += 2 if ord(char) > 0xFFFF else 1+ return len(text)+++def to_rich_text(+ decoded: DecodedString,+ fonts: list[XlsFontStyle],+) -> XlsRichText:+ """把字体切换点解析成稳定的字符区间。"""++ if not decoded.font_starts or not decoded.text:+ return XlsRichText(decoded.text)+ starts = sorted(decoded.font_starts, key=lambda item: item[0])+ runs: list[XlsRichRun] = []+ for index, (unit_start, font_index) in enumerate(starts):+ unit_end = starts[index + 1][0] if index + 1 < len(starts) else 0x7FFF_FFFF+ start = utf16_unit_to_index(decoded.text, unit_start)+ end = utf16_unit_to_index(decoded.text, unit_end)+ resolved_font_index = font_index if font_index < 4 else font_index - 1+ style = (+ fonts[resolved_font_index]+ if 0 <= resolved_font_index < len(fonts)+ else XlsFontStyle()+ )+ if start < end and style != XlsFontStyle():+ runs.append(XlsRichRun(start=start, end=end, style=style))+ return XlsRichText(decoded.text, tuple(runs))+++def read_txo_text(+ base_payload: bytes,+ continuation_segments: list[bytes],+ fonts: list[XlsFontStyle],+) -> XlsRichText | None:+ """读取 TXO 文本和 8 字节 formatting runs。"""++ if len(base_payload) < 14:+ return None+ character_count = int(struct.unpack_from("<H", base_payload, 10)[0])+ formatting_size = int(struct.unpack_from("<H", base_payload, 12)[0])+ if character_count <= 0:+ return XlsRichText("")+ units: list[int] = []+ consumed_segments = 0+ remaining = character_count+ for segment in continuation_segments:+ if remaining <= 0:+ break+ consumed_segments += 1+ if not segment:+ continue+ wide = bool(segment[0] & 0x01)+ payload = segment[1:]+ if wide:+ take = min(remaining, len(payload) // 2)+ units.extend(struct.unpack(f"<{take}H", payload[: take * 2]))+ else:+ take = min(remaining, len(payload))+ units.extend(int(value) for value in payload[:take])+ remaining -= take+ text = clean_text(_decode_utf16_units(units))+ formatting = b"".join(continuation_segments[consumed_segments:])[:formatting_size]+ starts: list[tuple[int, int]] = []+ for offset in range(0, len(formatting) - 7, 8):+ character_index, font_index = struct.unpack_from("<HH", formatting, offset)+ if character_index <= character_count:+ starts.append((int(character_index), int(font_index)))+ return to_rich_text(DecodedString(text, tuple(starts)), fonts)diff --git a/mineru/model/flash/xls/xls_converter.py b/mineru/model/flash/xls/xls_converter.pynew file mode 100644index 00000000..d7617355--- /dev/null+++ b/mineru/model/flash/xls/xls_converter.py@@ -0,0 +1,217 @@+# Copyright (c) Opendatalab. All rights reserved.++"""把 Excel 97–2003 BIFF 工作簿转换为 MinerU 分页 model-list。"""++from __future__ import annotations++from typing import Any, BinaryIO++from loguru import logger+from openpyxl import Workbook # type: ignore[reportMissingModuleSource]+from openpyxl.cell.rich_text import CellRichText, TextBlock # type: ignore[reportMissingModuleSource]+from openpyxl.cell.text import InlineFont # type: ignore[reportMissingModuleSource]+from openpyxl.worksheet.worksheet import Worksheet # type: ignore[reportMissingModuleSource]++from mineru.model.flash.legacy_office import BoundedOleReader, LegacyOfficeEncryptedError+from mineru.model.flash.legacy_office.errors import LegacyOfficeResourceLimitError+from mineru.model.flash.legacy_office.limits import MAX_GRID_SLOTS+from mineru.model.flash.xlsx.xlsx_converter import ExcelTable, XlsxConverter+from mineru.model.office_stream import read_stream_bytes_from_start+from mineru.types import BlockType++from .models import XlsChart, XlsRichText, XlsSheet, XlsWorkbook+from .parser import parse_xls_workbook+++def _inline_font(rich_text: XlsRichText, start: int) -> InlineFont | None:+ """返回覆盖指定字符位置的 openpyxl 行内字体。"""++ for run in rich_text.runs:+ if run.start <= start < run.end:+ style = run.style+ return InlineFont(+ b=style.bold,+ i=style.italic,+ u="single" if style.underline else None,+ strike=style.strike,+ vertAlign=(+ "superscript"+ if style.superscript+ else "subscript"+ if style.subscript+ else None+ ),+ )+ return None+++def _rich_text_boundaries(value: XlsRichText) -> list[int]:+ """收集富文本的起止边界并裁剪到有效字符范围。"""++ boundaries = {0, len(value.text)}+ for run in value.runs:+ boundaries.add(max(0, min(run.start, len(value.text))))+ boundaries.add(max(0, min(run.end, len(value.text))))+ return sorted(boundaries)+++def _to_openpyxl_rich_text(value: XlsRichText) -> str | CellRichText:+ """把内部富文本转换为 XlsxConverter 已支持的 CellRichText。"""++ if not value.runs:+ return value.text+ parts: list[str | TextBlock] = []+ boundaries = _rich_text_boundaries(value)+ for start, end in zip(boundaries, boundaries[1:]):+ if start >= end:+ continue+ text = value.text[start:end]+ font = _inline_font(value, start)+ parts.append(TextBlock(font, text) if font is not None else text)+ return CellRichText(parts)+++class _XlsPageBuilder(XlsxConverter):+ """用轻量 openpyxl worksheet 适配器复用现有网格与 HTML 投影。"""++ def __init__(self, workbook_model: XlsWorkbook) -> None:+ """初始化解析结果映射和全工作簿网格预算。"""++ super().__init__(include_hidden_sheets=False)+ self.workbook_model = workbook_model+ self._sheet_by_title: dict[str, XlsSheet] = {}+ self._active_xls_sheet: XlsSheet | None = None+ self._grid_slots = 0++ def _build_openpyxl_workbook(self) -> Workbook:+ """把 BIFF 语义模型投影成不落盘的 worksheet 对象。"""++ workbook = Workbook()+ default_sheet = workbook.active+ if default_sheet is not None:+ workbook.remove(default_sheet)+ for sheet_model in self.workbook_model.sheets:+ worksheet = workbook.create_sheet(sheet_model.name)+ self._sheet_by_title[worksheet.title] = sheet_model+ if not sheet_model.visible:+ worksheet.sheet_state = Worksheet.SHEETSTATE_HIDDEN+ for cell_model in sheet_model.cells.values():+ cell = worksheet.cell(row=cell_model.row + 1, column=cell_model.col + 1)+ cell.value = _to_openpyxl_rich_text(cell_model.value)+ if cell_model.hyperlink:+ cell.hyperlink = cell_model.hyperlink+ for row_first, col_first, row_last, col_last in sheet_model.merges:+ worksheet.merge_cells(+ start_row=row_first + 1,+ start_column=col_first + 1,+ end_row=row_last + 1,+ end_column=col_last + 1,+ )+ return workbook++ def build_pages(self) -> list[list[dict[str, Any]]]:+ """逐可见 worksheet 生成 page,并复用 XlsxModel 的标题规则。"""++ self.workbook = self._build_openpyxl_workbook()+ sheet_pages: list[tuple[str, list[dict[str, Any]]]] = []+ for worksheet in self._iter_sheets_to_convert():+ self._active_xls_sheet = self._sheet_by_title.get(worksheet.title)+ self.cur_page = []+ self._convert_sheet(worksheet)+ sheet_pages.append((worksheet.title, self.cur_page))+ if self._should_emit_sheet_titles([page for _, page in sheet_pages]):+ self._prepend_sheet_titles(sheet_pages)+ return [page for _, page in sheet_pages]++ def _collect_sheet_images(self, sheet: Worksheet) -> list[dict]:+ """返回解析器已经绑定到当前 sheet 的图片。"""++ sheet_model = self._sheet_by_title.get(sheet.title)+ if sheet_model is None:+ return []+ return [+ {+ "anchor": (image.row, image.col),+ "base64": image.image_base64,+ }+ for image in sheet_model.images+ ]++ def _find_data_tables(self, sheet: Worksheet) -> list[ExcelTable]:+ """复用 XLSX 区域发现并累计限制实际物化网格。"""++ tables = super()._find_data_tables(sheet)+ self._grid_slots += sum(table.num_rows * table.num_cols for table in tables)+ if self._grid_slots > MAX_GRID_SLOTS:+ raise LegacyOfficeResourceLimitError(+ f"workbook extent exceeds max_grid_slots={MAX_GRID_SLOTS}"+ )+ return tables++ def _chart_block(self, sheet: Worksheet, chart: XlsChart) -> dict[str, Any] | None:+ """把简单 chart 引用转换成数据表,预览图片仅用于无数据 fallback。"""++ if chart.source_rows and chart.source_cols:+ self._grid_slots += len(chart.source_rows) * len(chart.source_cols)+ if self._grid_slots > MAX_GRID_SLOTS:+ raise LegacyOfficeResourceLimitError(+ f"workbook extent exceeds max_grid_slots={MAX_GRID_SLOTS}"+ )+ table = self._build_synthetic_table_from_sheet_selection(+ sheet,+ list(chart.source_rows),+ list(chart.source_cols),+ )+ return {+ "type": BlockType.CHART,+ "content": self.excel_table_to_html(table),+ }+ if chart.image_base64:+ return {+ "type": BlockType.CHART,+ "content": "",+ "image_base64": chart.image_base64,+ }+ return None++ def _find_charts_in_sheet(+ self,+ sheet: Worksheet,+ ) -> list[tuple[tuple[int, int], int, dict[str, Any]]]:+ """按 cell anchor 输出当前工作表的 legacy chart blocks。"""++ sheet_model = self._sheet_by_title.get(sheet.title)+ if sheet_model is None:+ return []+ artifacts = []+ for order, chart in enumerate(sheet_model.charts):+ block = self._chart_block(sheet, chart)+ if block is None:+ continue+ artifacts.append(((chart.row, chart.col), 10_000 + order, block))+ return artifacts+++class XlsConverter:+ """将 Excel 97–2003 OLE/BIFF 二进制流转换为 model-list。"""++ def __init__(self) -> None:+ """初始化空分页输出。"""++ self.pages: list[list[dict[str, Any]]] = []++ def convert(self, file_binary: BinaryIO) -> None:+ """读取 Workbook/Book stream,解析 BIFF 并生成可见工作表页面。"""++ file_bytes = read_stream_bytes_from_start(file_binary)+ with BoundedOleReader(file_bytes) as ole:+ if ole.has_stream("EncryptionInfo") or ole.has_stream("EncryptedPackage"):+ raise LegacyOfficeEncryptedError("password-protected XLS is not supported")+ if ole.has_stream("Workbook"):+ workbook_stream = ole.read_stream("Workbook")+ else:+ workbook_stream = ole.read_stream("Book")+ workbook = parse_xls_workbook(workbook_stream)+ builder = _XlsPageBuilder(workbook)+ self.pages = builder.build_pages()+ logger.debug("XLS parsing produced {} visible worksheet pages", len(self.pages))diff --git a/mineru/types.py b/mineru/types.pyindex 902e198b..c77e28eb 100644--- a/mineru/types.py+++ b/mineru/types.py@@ -664,7 +664,7 @@ class ModelJson(_StrictMiddleModel):pages: list[list[dict[str, Any]]]page_index_map: list[int]- file_suffix: Literal["pdf", "docx", "pptx", "xlsx"]+ file_suffix: Literal["pdf", "docx", "ppt", "pptx", "xls", "xlsx"]effort: Literal["flash", "low", "medium", "high", "xhigh"]parse_mode: Literal["txt", "ocr"]mineru_version: str = Field(min_length=1)@@ -730,7 +730,7 @@ class MiddleJson(_StrictMiddleModel):pages: list[PageInfo]is_full_document: bool- file_suffix: Literal["pdf", "docx", "pptx", "xlsx"]+ file_suffix: Literal["pdf", "docx", "ppt", "pptx", "xls", "xlsx"]effort: Literal["flash", "low", "medium", "high", "xhigh"]parse_mode: Literal["txt", "ocr"]mineru_version: str = Field(min_length=1)diff --git a/pyproject.toml b/pyproject.tomlindex 605366b8..2ace9cad 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -62,6 +62,7 @@ dependencies = ["pylatexenc>=2.10,<3","lxml>=4.0.0,<7.0.0","openpyxl>=3.1.5,<4",+ "olefile>=0.47,<1","aiosqlite>=0.20.0,<1","watchfiles>=1.0.0,<2","fastapi",diff --git a/tests/unittest/_legacy_ppt_test_utils.py b/tests/unittest/_legacy_ppt_test_utils.pynew file mode 100644index 00000000..0f9c431c--- /dev/null+++ b/tests/unittest/_legacy_ppt_test_utils.py@@ -0,0 +1,238 @@+"""构造不依赖 Office 的最小 PowerPoint 97–2003 测试文件。"""++from __future__ import annotations++import struct+++def _ppt_record(version_instance: int, record_type: int, payload: bytes) -> bytes:+ """构造一条 PPT record。"""++ return struct.pack("<HHI", version_instance, record_type, len(payload)) + payload+++def _ppt_container(instance: int, record_type: int, payload: bytes) -> bytes:+ """构造 recVer=0xF 的 PPT container。"""++ return _ppt_record((instance << 4) | 0xF, record_type, payload)+++def _build_cfb(streams: list[tuple[str, bytes]]) -> bytes:+ """生成所有 stream 均使用常规 FAT sector 的最小 CFB v3。"""++ sector_size = 512+ end_of_chain = 0xFFFF_FFFE+ fat_sector = 0xFFFF_FFFD+ free_sector = 0xFFFF_FFFF+ fat: list[int] = []+ sectors: list[bytes] = []++ def add_chain(data: bytes) -> int:+ """把字节追加为 FAT chain 并返回首 sector。"""++ if not data:+ return end_of_chain+ padded = data + b"\x00" * (-len(data) % sector_size)+ first = len(sectors)+ count = len(padded) // sector_size+ for index in range(count):+ sectors.append(padded[index * sector_size : (index + 1) * sector_size])+ fat.append(first + index + 1 if index + 1 < count else end_of_chain)+ return first++ def directory_entry(+ name: str,+ kind: int,+ right: int,+ child: int,+ start: int,+ size: int,+ ) -> bytes:+ """构造一个 128 字节 CFB directory entry。"""++ none = 0xFFFF_FFFF+ raw_name = name.encode("utf-16-le") + b"\x00\x00"+ return (+ raw_name+ + b"\x00" * (64 - len(raw_name))+ + struct.pack("<HBBIII", len(raw_name), kind, 1, none, right, child)+ + b"\x00" * 16+ + b"\x00" * 4+ + b"\x00" * 16+ + struct.pack("<IQ", start, size)+ )++ starts: list[tuple[int, int]] = []+ for _, data in streams:+ padded = data + b"\x00" * (4096 - len(data)) if 0 < len(data) < 4096 else data+ starts.append((add_chain(padded), len(padded)))++ none = 0xFFFF_FFFF+ entries = [+ directory_entry(+ "Root Entry",+ 5,+ none,+ 1 if streams else none,+ end_of_chain,+ 0,+ )+ ]+ for index, ((name, _), (start, size)) in enumerate(zip(streams, starts, strict=True), start=1):+ right = index + 1 if index < len(streams) else none+ entries.append(directory_entry(name, 2, right, none, start, size))+ directory = b"".join(entries)+ directory += b"\x00" * (-len(directory) % sector_size)+ directory_start = add_chain(directory)++ fat_count = 1+ while (len(fat) + fat_count + 127) // 128 > fat_count:+ fat_count += 1+ fat_start = len(sectors)+ fat_ids = list(range(fat_start, fat_start + fat_count))+ full_fat = fat + [fat_sector] * fat_count+ full_fat += [free_sector] * (fat_count * 128 - len(full_fat))+ for index in range(fat_count):+ sectors.append(struct.pack("<128I", *full_fat[index * 128 : (index + 1) * 128]))++ difat = fat_ids + [free_sector] * (109 - len(fat_ids))+ header = (+ b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"+ + b"\x00" * 16+ + struct.pack(+ "<HHHHHHIIIIIIIII",+ 0x003E,+ 0x0003,+ 0xFFFE,+ 9,+ 6,+ 0,+ 0,+ 0,+ fat_count,+ directory_start,+ 0,+ 4096,+ end_of_chain,+ 0,+ end_of_chain,+ )+ + struct.pack("<I", 0)+ + struct.pack("<109I", *difat)+ )+ return header + b"".join(sectors)+++def build_sparse_notes_ppt() -> bytes:+ """构造仅第二页含 speaker notes 的两页 PPT。"""++ def slide(text: str) -> bytes:+ """构造含一段直接文本的 slide container。"""++ slide_atom = _ppt_record(2, 0x03EF, struct.pack("<I", 0) + b"\x00" * 8 + struct.pack("<IIHH", 0, 0, 0, 0))+ text_header = _ppt_record(0, 0x0F9F, struct.pack("<I", 1))+ text_bytes = _ppt_record(0, 0x0FA8, text.encode("ascii"))+ return _ppt_container(0, 0x03EE, slide_atom + text_header + text_bytes)++ def notes(slide_ref: int, text: str) -> bytes:+ """构造绑定到指定 slide id 的 notes container。"""++ notes_atom = _ppt_record(1, 0x03F1, struct.pack("<IHH", slide_ref, 0, 0))+ text_header = _ppt_record(0, 0x0F9F, struct.pack("<I", 2))+ text_bytes = _ppt_record(0, 0x0FA8, text.encode("ascii"))+ return _ppt_container(0, 0x03F0, notes_atom + text_header + text_bytes)++ def persist_atom(persist_ref: int, slide_id: int) -> bytes:+ """构造 SlidePersistAtom。"""++ return _ppt_record(0, 0x03F3, struct.pack("<IIIII", persist_ref, 0, 0, slide_id, 0))++ slide_list = _ppt_container(0, 0x0FF0, persist_atom(2, 256) + persist_atom(3, 257))+ notes_list = _ppt_container(2, 0x0FF0, persist_atom(4, 1301))+ document = _ppt_container(0, 0x03E8, slide_list + notes_list)+ records = [+ (1, document),+ (2, slide("First slide text\r")),+ (3, slide("Second slide text\r")),+ (4, notes(257, "Notes for the second slide\r")),+ ]+ stream = b""+ offsets: dict[int, int] = {}+ for persist_id, record in records:+ offsets[persist_id] = len(stream)+ stream += record+ directory = struct.pack("<I", 1 | (4 << 20)) + struct.pack("<4I", *(offsets[index] for index in range(1, 5)))+ directory_offset = len(stream)+ stream += _ppt_record(0, 0x1772, directory)+ edit_offset = len(stream)+ stream += _ppt_record(0, 0x0FF5, struct.pack("<IIIIIIHH", 0, 0, 0, directory_offset, 1, 5, 0, 0))+ current_user = _ppt_record(0, 0x0FF6, struct.pack("<III", 20, 0xE391C05F, edit_offset))+ return _build_cfb([("Current User", current_user), ("PowerPoint Document", stream)])+++def build_multimaster_ppt() -> bytes:+ """构造两页分别继承不同母版 bullet/粗斜体默认值的 PPT。"""++ def master_style(bullet_on: bool, character_mask: int, character_style: int) -> bytes:+ """构造一个层级的 TextMasterStyleAtom。"""++ paragraph = struct.pack("<IH", 0x0001, 0x0001 if bullet_on else 0x0000)+ character = struct.pack("<IH", character_mask, character_style)+ return _ppt_record(1 << 4, 0x0FA3, struct.pack("<H", 1) + paragraph + character)++ def slide(master_id: int, text: str) -> bytes:+ """构造引用指定 master id 的 slide。"""++ slide_atom = _ppt_record(+ 2,+ 0x03EF,+ struct.pack("<I", 0) + b"\x00" * 8 + struct.pack("<IIHH", master_id, 0, 0, 0),+ )+ text_header = _ppt_record(0, 0x0F9F, struct.pack("<I", 1))+ text_bytes = _ppt_record(0, 0x0FA8, text.encode("ascii"))+ return _ppt_container(0, 0x03EE, slide_atom + text_header + text_bytes)++ def persist_atom(persist_ref: int, stable_id: int) -> bytes:+ """构造 slide/master 共用的 persist atom。"""++ return _ppt_record(0, 0x03F3, struct.pack("<IIIII", persist_ref, 0, 0, stable_id, 0))++ slide_list = _ppt_container(0, 0x0FF0, persist_atom(4, 256) + persist_atom(5, 257))+ master_list = _ppt_container(1, 0x0FF0, persist_atom(2, 1001) + persist_atom(3, 1002))+ document = _ppt_container(0, 0x03E8, slide_list + master_list)+ master_a = _ppt_container(0, 0x03F8, master_style(True, 0x0001, 0x0001))+ master_b = _ppt_container(0, 0x03F8, master_style(False, 0x0002, 0x0002))+ records = [+ (1, document),+ (2, master_a),+ (3, master_b),+ (4, slide(1001, "Alpha master body text\r")),+ (5, slide(1002, "Beta master body text\r")),+ ]+ stream = b""+ offsets: dict[int, int] = {}+ for persist_id, record in records:+ offsets[persist_id] = len(stream)+ stream += record+ directory = struct.pack("<I", 1 | (5 << 20)) + struct.pack(+ "<5I", *(offsets[index] for index in range(1, 6))+ )+ directory_offset = len(stream)+ stream += _ppt_record(0, 0x1772, directory)+ edit_offset = len(stream)+ stream += _ppt_record(+ 0,+ 0x0FF5,+ struct.pack("<IIIIIIHH", 0, 0, 0, directory_offset, 1, 6, 0, 0),+ )+ current_user = _ppt_record(0, 0x0FF6, struct.pack("<III", 20, 0xE391C05F, edit_offset))+ return _build_cfb([("Current User", current_user), ("PowerPoint Document", stream)])+++def build_deep_nested_ppt() -> bytes:+ """构造超过固定 record depth 的攻击形状。"""++ nested = _ppt_record(0, 0x0FA8, b"deep")+ for _ in range(200):+ nested = _ppt_container(0, 0x03EE, nested)+ return _build_cfb([("Current User", b""), ("PowerPoint Document", nested)])diff --git a/tests/unittest/_legacy_xls_test_utils.py b/tests/unittest/_legacy_xls_test_utils.pynew file mode 100644index 00000000..8a7565b3--- /dev/null+++ b/tests/unittest/_legacy_xls_test_utils.py@@ -0,0 +1,220 @@+"""构造不依赖 Excel/LibreOffice 的最小 BIFF8 测试文件。"""++from __future__ import annotations++from dataclasses import dataclass+import struct+import uuid++from _legacy_ppt_test_utils import _build_cfb+++@dataclass(frozen=True, slots=True)+class SheetFixture:+ """一个测试 worksheet 的名称、记录和可见状态。"""++ name: str+ records: bytes = b""+ visible: bool = True+++def biff_record(record_type: int, payload: bytes = b"") -> bytes:+ """构造一条 BIFF record。"""++ return struct.pack("<HH", record_type, len(payload)) + payload+++def biff_bof(substream_type: int, *, version: int = 0x0600) -> bytes:+ """构造 BIFF8 BOF 记录。"""++ return biff_record(+ 0x0809,+ struct.pack("<HHHHII", version, substream_type, 0x4F5A, 0x07CD, 0x000200C1, 0x00000608),+ )+++def label_cell(row: int, col: int, text: str, *, xf_index: int = 0) -> bytes:+ """构造 BIFF8 LABEL 单元格。"""++ encoded = text.encode("utf-16le")+ string = struct.pack("<HB", len(encoded) // 2, 1) + encoded+ return biff_record(0x0204, struct.pack("<HHH", row, col, xf_index) + string)+++def number_cell(row: int, col: int, value: float, *, xf_index: int = 0) -> bytes:+ """构造 NUMBER 单元格。"""++ return biff_record(0x0203, struct.pack("<HHHd", row, col, xf_index, value))+++def formula_number_cell(row: int, col: int, value: float, *, xf_index: int = 0) -> bytes:+ """构造仅依赖缓存数值的 FORMULA 单元格。"""++ body = struct.pack("<HHH", row, col, xf_index) + struct.pack("<d", value) + b"\x00" * 6+ return biff_record(0x0006, body)+++def formula_string_cell(row: int, col: int, value: str, *, xf_index: int = 0) -> bytes:+ """构造缓存结果由紧随 STRING 记录提供的 FORMULA。"""++ cached = bytes([0, 0, 0, 0, 0, 0, 0xFF, 0xFF])+ formula = biff_record(+ 0x0006,+ struct.pack("<HHH", row, col, xf_index) + cached + b"\x00" * 6,+ )+ encoded = value.encode("utf-16le")+ string = biff_record(0x0207, struct.pack("<HB", len(encoded) // 2, 1) + encoded)+ return formula + string+++def merged_cells(*ranges: tuple[int, int, int, int]) -> bytes:+ """构造 MERGEDCELLS 记录。"""++ payload = struct.pack("<H", len(ranges))+ for row_first, col_first, row_last, col_last in ranges:+ payload += struct.pack("<4H", row_first, row_last, col_first, col_last)+ return biff_record(0x00E5, payload)+++def url_hyperlink(+ row: int,+ col: int,+ label: str,+ target: str,+) -> bytes:+ """构造带 display name 和 URL Moniker 的 HLink。"""++ ref = struct.pack("<4H", row, row, col, col)+ hyperlink_clsid = uuid.UUID("79eac9d0-baf9-11ce-8c82-00aa004ba90b").bytes_le+ url_clsid = uuid.UUID("79eac9e0-baf9-11ce-8c82-00aa004ba90b").bytes_le+ display = (label + "\x00").encode("utf-16le")+ url = (target + "\x00").encode("utf-16le")+ body = (+ ref+ + hyperlink_clsid+ + struct.pack("<II", 2, 0x17)+ + struct.pack("<I", len(display) // 2)+ + display+ + url_clsid+ + struct.pack("<I", len(url))+ + url+ )+ return biff_record(0x01B8, body)+++def font_record(*, bold: bool = False, italic: bool = False) -> bytes:+ """构造只携带粗体/斜体属性的 FONT 记录。"""++ flags = 0x0002 if italic else 0+ weight = 700 if bold else 400+ body = struct.pack("<HHHHHBBBB", 220, flags, 0, weight, 0, 0, 0, 0, 0)+ body += bytes([5, 1]) + "Arial".encode("utf-16le")+ return biff_record(0x0031, body)+++def rich_sst(strings: list[tuple[str, list[tuple[int, int]]]]) -> bytes:+ """构造含字体切换点的 SST。"""++ payload = struct.pack("<II", len(strings), len(strings))+ for text, starts in strings:+ encoded = text.encode("utf-16le")+ flags = 0x01 | (0x08 if starts else 0)+ payload += struct.pack("<HB", len(encoded) // 2, flags)+ if starts:+ payload += struct.pack("<H", len(starts))+ payload += encoded+ for character_index, font_index in starts:+ payload += struct.pack("<HH", character_index, font_index)+ return biff_record(0x00FC, payload)+++def continued_rich_sst(text: str, starts: list[tuple[int, int]]) -> bytes:+ """在字符数据中间用 CONTINUE 切分一个富文本 SST entry。"""++ encoded = text.encode("utf-16le")+ unit_count = len(encoded) // 2+ first_character = encoded[:2]+ remaining_characters = encoded[2:]+ base = struct.pack("<IIHBH", 1, 1, unit_count, 0x09, len(starts))+ base += first_character+ continuation = bytes([0x01]) + remaining_characters+ continuation += b"".join(+ struct.pack("<HH", character_index, font_index)+ for character_index, font_index in starts+ )+ return biff_record(0x00FC, base) + biff_record(0x003C, continuation)+++def labelsst_cell(row: int, col: int, string_index: int, *, xf_index: int = 0) -> bytes:+ """构造引用 SST 的 LABELSST 单元格。"""++ return biff_record(0x00FD, struct.pack("<HHHI", row, col, xf_index, string_index))+++def build_xls(+ sheets: list[SheetFixture],+ *,+ globals_records: bytes = b"",+ corrupt_first_offset: bool = False,+ encrypted: bool = False,+) -> bytes:+ """构造含 Workbook Globals 与多个 worksheet substreams 的 OLE 文件。"""++ prefix = biff_bof(0x0005)+ prefix += biff_record(0x0042, struct.pack("<H", 1200))+ prefix += font_record()+ prefix += biff_record(0x00E0, struct.pack("<HH", 0, 0) + b"\x00" * 16)+ if encrypted:+ prefix += biff_record(0x002F, b"\x00\x00")+ prefix += globals_records++ def boundsheet(offset: int, sheet: SheetFixture) -> bytes:+ """构造 BoundSheet8 目录项。"""++ name = sheet.name.encode("utf-16le")+ body = struct.pack("<IBB", offset, 0 if sheet.visible else 1, 0)+ body += struct.pack("<BB", len(name) // 2, 1) + name+ return biff_record(0x0085, body)++ placeholders = b"".join(boundsheet(0, sheet) for sheet in sheets)+ globals_length = len(prefix) + len(placeholders) + len(biff_record(0x000A))+ sheet_streams = [biff_bof(0x0010) + sheet.records + biff_record(0x000A) for sheet in sheets]+ offsets: list[int] = []+ cursor = globals_length+ for stream in sheet_streams:+ offsets.append(cursor)+ cursor += len(stream)+ if corrupt_first_offset and offsets:+ offsets[0] = 0x7FFF_FFF0+ directory = b"".join(+ boundsheet(offset, sheet)+ for offset, sheet in zip(offsets, sheets, strict=True)+ )+ workbook = prefix + directory + biff_record(0x000A) + b"".join(sheet_streams)+ return _build_cfb([("Workbook", workbook)])+++def build_biff5_xls(text: str) -> bytes:+ """构造使用 Book stream 和 cp1252 LABEL 的 BIFF5 文件。"""++ encoded = text.encode("cp1252")+ label = biff_record(+ 0x0204,+ struct.pack("<HHHH", 0, 0, 0, len(encoded)) + encoded,+ )+ sheet_stream = biff_bof(0x0010, version=0x0500) + label + biff_record(0x000A)+ prefix = biff_bof(0x0005, version=0x0500)+ prefix += biff_record(0x0042, struct.pack("<H", 1252))+ prefix += biff_record(0x00E0, struct.pack("<HH", 0, 0) + b"\x00" * 12)+ name = b"Legacy"+ placeholder = biff_record(+ 0x0085,+ struct.pack("<IBBB", 0, 0, 0, len(name)) + name,+ )+ offset = len(prefix) + len(placeholder) + len(biff_record(0x000A))+ boundsheet = biff_record(+ 0x0085,+ struct.pack("<IBBB", offset, 0, 0, len(name)) + name,+ )+ workbook = prefix + boundsheet + biff_record(0x000A) + sheet_stream+ return _build_cfb([("Book", workbook)])diff --git a/tests/unittest/test_flash_legacy_ppt.py b/tests/unittest/test_flash_legacy_ppt.pynew file mode 100644index 00000000..410bd7b8--- /dev/null+++ b/tests/unittest/test_flash_legacy_ppt.py@@ -0,0 +1,263 @@+from __future__ import annotations++import asyncio+from io import BytesIO+from pathlib import Path+import struct++from bs4 import BeautifulSoup+import pytest+from pydantic import ValidationError++from mineru.backend.analyze import aio_doc_analyze, doc_analyze+from mineru.model.flash import PptModel+from mineru.model.flash.legacy_office import LegacyOfficeEncryptedError, LegacyOfficeResourceLimitError+from mineru.model.flash.ppt import parser as ppt_parser+from mineru.model.flash.ppt.models import PptPresentation, PptSlide+from mineru.model.flash.ppt.ppt_converter import PptConverter+from mineru.model.flash.ppt.records import PptRecord, RecordBudget+from mineru.model.flash.ppt.style_text import CharacterRun, StyleRuns+from mineru.types import BlockType, ImageBlock, MiddleJson, ModelJson, TableBlock++from _legacy_ppt_test_utils import build_deep_nested_ppt, build_multimaster_ppt, build_sparse_notes_ppt+++_PROJECT_ROOT = Path(__file__).resolve().parents[2]+_REAL_PPT = _PROJECT_ROOT / "output" / "office_roundtrip_research_20260824" / "legacy" / "pptx_01.ppt"+++def test_ppt_model_preserves_slide_pages_and_sparse_notes() -> None:+ """验证旧版 PPT 始终逐 slide 分页,并按 slide id 绑定稀疏备注。"""++ pages = PptModel().predict(BytesIO(build_sparse_notes_ppt()))++ assert len(pages) == 2+ assert pages[0] == [{"type": BlockType.TEXT, "content": "First slide text"}]+ assert pages[1] == [+ {"type": BlockType.TEXT, "content": "Second slide text"},+ {"type": BlockType.PAGE_FOOTNOTE, "content": "Notes for the second slide"},+ ]+++def test_ppt_converter_preserves_empty_slide_positions() -> None:+ """验证空白或隐藏 slide 仍在 model-list 中保留对应空页。"""++ presentation = PptPresentation(+ slides=[PptSlide(slide_id=1), PptSlide(slide_id=2, hidden=True)]+ )++ assert PptConverter._presentation_to_pages(presentation) == [[], []]+++def test_backend_analyze_accepts_ppt_and_async_contract() -> None:+ """验证同步与异步 Backend Analyze 均返回严格 PPT 文档契约。"""++ file_bytes = build_sparse_notes_ppt()+ middle_json, model_json = doc_analyze(file_bytes, file_suffix="ppt")+ async_middle_json, async_model_json = asyncio.run(+ aio_doc_analyze(file_bytes, file_suffix="ppt")+ )++ assert isinstance(model_json, ModelJson)+ assert isinstance(middle_json, MiddleJson)+ assert model_json.file_suffix == "ppt"+ assert middle_json.file_suffix == "ppt"+ assert model_json.effort == middle_json.effort == "flash"+ assert model_json.parse_mode == middle_json.parse_mode == "txt"+ assert model_json.is_full_document is middle_json.is_full_document is True+ assert [page.page_idx for page in middle_json.pages] == [0, 1]+ assert async_middle_json == middle_json+ assert async_model_json == model_json+++def test_ppt_model_applies_per_slide_master_styles() -> None:+ """验证每页按自身 master id 继承 bullet、粗体和斜体,而不是固定首个母版。"""++ pages = PptModel().predict(BytesIO(build_multimaster_ppt()))++ assert pages == [+ [+ {+ "type": BlockType.LIST,+ "attribute": "unordered",+ "ilevel": 0,+ "content": [+ {+ "type": BlockType.TEXT,+ "content": '<text style="bold">Alpha master body text</text>',+ }+ ],+ }+ ],+ [+ {+ "type": BlockType.TEXT,+ "content": '<text style="italic">Beta master body text</text>',+ }+ ],+ ]+++def test_ppt_record_depth_is_a_hard_resource_limit() -> None:+ """验证恶意深层 PPT records 在递归前触发固定资源限制。"""++ with pytest.raises(LegacyOfficeResourceLimitError, match="max_record_depth"):+ PptModel().predict(BytesIO(build_deep_nested_ppt()))+++def test_ppt_encryption_marker_is_rejected_before_record_parsing() -> None:+ """验证 Current User 加密标志在读取文档记录前返回稳定错误。"""++ current_user = bytearray(20)+ struct.pack_into("<H", current_user, 2, 0x0FF6)+ struct.pack_into("<I", current_user, 12, 0xF3D1_C4DF)++ with pytest.raises(LegacyOfficeEncryptedError, match="password-protected"):+ ppt_parser.parse_ppt_document(b"not parsed", current_user=bytes(current_user))++[email protected]("file_suffix", ["doc"])+def test_unimplemented_legacy_suffixes_remain_rejected(file_suffix: str) -> None:+ """验证本阶段没有提前开放 DOC 严格类型或运行时入口。"""++ with pytest.raises(ValueError, match="Unsupported file suffix"):+ doc_analyze(b"legacy", file_suffix=file_suffix) # type: ignore[arg-type]+ with pytest.raises(ValidationError):+ ModelJson(+ pages=[],+ page_index_map=[],+ file_suffix=file_suffix, # type: ignore[arg-type]+ effort="flash",+ parse_mode="txt",+ mineru_version="test",+ )+++def test_ppt_is_not_routed_through_public_parser() -> None:+ """验证实现范围没有新增 PptParser 或 mineru.parser.parse 路由。"""++ office_source = (_PROJECT_ROOT / "mineru" / "parser" / "office.py").read_text(encoding="utf-8")+ parser_source = (_PROJECT_ROOT / "mineru" / "parser" / "__init__.py").read_text(encoding="utf-8")++ assert "class PptParser" not in office_source+ assert '"ppt": PptParser' not in parser_source+++def test_safe_ppt_hyperlink_schemes_are_explicit() -> None:+ """验证外链白名单保留 Web/邮件链接并拒绝本地或脚本目标。"""++ assert ppt_parser._safe_hyperlink_target("https://example.com/a") == "https://example.com/a"+ assert ppt_parser._safe_hyperlink_target("mailto:[email protected]") == "mailto:[email protected]"+ assert ppt_parser._safe_hyperlink_target("file:///tmp/a") is None+ assert ppt_parser._safe_hyperlink_target("javascript:alert(1)") is None+++def test_ppt_hyperlink_range_splits_utf16_and_style_boundaries() -> None:+ """验证非 BMP 字符的 UTF-16 链接范围可跨字符样式边界准确拆分。"""++ interactive_atom = struct.pack("<II8x", 0, 7)+ container_payload = struct.pack(+ "<HHI", 0, ppt_parser.RT_INTERACTIVE_INFO_ATOM, len(interactive_atom)+ ) + interactive_atom+ records = [+ PptRecord(+ offset=0,+ version=0xF,+ instance=0,+ record_type=ppt_parser.RT_INTERACTIVE_INFO,+ payload=container_payload,+ ),+ PptRecord(+ offset=0,+ version=0,+ instance=0,+ record_type=ppt_parser.RT_TEXT_INTERACTIVE_INFO_ATOM,+ payload=struct.pack("<II", 1, 4),+ ),+ ]+ spans = ppt_parser._interactive_spans(+ records,+ {7: "https://example.com"},+ RecordBudget(),+ )+ paragraphs = ppt_parser._build_paragraphs(+ "A😀BC",+ StyleRuns(+ characters=[+ CharacterRun(count=3, bold=True),+ CharacterRun(count=2, italic=True),+ ]+ ),+ [],+ spans,+ )++ assert [+ (run.text, run.bold, run.italic, run.hyperlink)+ for run in paragraphs[0].runs+ ] == [+ ("A", True, False, None),+ ("😀", True, False, "https://example.com"),+ ("B", False, True, "https://example.com"),+ ("C", False, True, None),+ ]++[email protected](not _REAL_PPT.exists(), reason="real Office roundtrip fixture is local-only")+def test_real_ppt_recovers_table_notes_images_and_exports(tmp_path: Path) -> None:+ """验证真实六页 PPT 的合并表格、备注、图片及 sidecar 完整闭包。"""++ middle_json, model_json = doc_analyze(_REAL_PPT.read_bytes(), file_suffix="ppt")++ assert len(model_json.pages) == len(middle_json.pages) == 6+ assert model_json.file_suffix == middle_json.file_suffix == "ppt"+ table = next(block for block in middle_json.pages[0].blocks if isinstance(block, TableBlock))+ table_html = table.content[0].content+ soup = BeautifulSoup(table_html, "html.parser")+ rows = soup.find_all("tr")+ assert len(rows) == 9+ assert max(sum(int(cell.get("colspan", 1)) for cell in row.find_all("td")) for row in rows) == 7+ merged = sorted(+ (int(cell.get("rowspan", 1)), int(cell.get("colspan", 1)), cell.get_text(strip=True))+ for cell in soup.find_all("td")+ if cell.has_attr("rowspan") or cell.has_attr("colspan")+ )+ assert merged == sorted(+ [+ (1, 3, "Class1"),+ (1, 3, "Class2"),+ (1, 2, "A merged with B"),+ (2, 1, "R3"),+ (3, 1, "R4"),+ ]+ )+ assert [+ block.content+ for block in middle_json.pages[1].blocks+ if block.type == BlockType.PAGE_FOOTNOTE+ ] == ["Some notes on the second slide."]+ assert [+ block.content+ for block in middle_json.pages[2].blocks+ if block.type == BlockType.PAGE_FOOTNOTE+ ] == ["Final notes on the third slide.", "Second line of notes."]+ assert [sum(isinstance(block, ImageBlock) for block in page.blocks) for page in middle_json.pages] == [+ 0,+ 0,+ 0,+ 2,+ 1,+ 0,+ ]++ page_six_lists = [block for block in model_json.pages[5] if block.get("type") == BlockType.LIST]+ assert page_six_lists[0]["attribute"] == "ordered"+ assert page_six_lists[-1]["attribute"] == "ordered"+ assert page_six_lists[-1]["start"] == 3++ export_result = middle_json.export(tmp_path / "export")+ exported_payload = export_result.middle_json.model_dump(mode="json", exclude_none=True)+ assert export_result.json_path.exists()+ assert export_result.image_paths+ assert all(path.exists() and path.stat().st_size > 0 for path in export_result.image_paths)+ assert "image_base64" not in str(exported_payload)diff --git a/tests/unittest/test_flash_legacy_xls.py b/tests/unittest/test_flash_legacy_xls.pynew file mode 100644index 00000000..4c07f133--- /dev/null+++ b/tests/unittest/test_flash_legacy_xls.py@@ -0,0 +1,368 @@+from __future__ import annotations++import asyncio+from io import BytesIO+from pathlib import Path+import struct++from bs4 import BeautifulSoup+import pytest++from mineru.backend.analyze import aio_doc_analyze, doc_analyze+from mineru.model.flash import XlsModel+from mineru.model.flash.legacy_office import (+ LegacyOfficeEncryptedError,+ LegacyOfficeMissingPartError,+ LegacyOfficeResourceLimitError,+)+from mineru.model.flash.legacy_office.limits import MAX_RECORDS+from mineru.model.flash.xls import xls_converter as xls_converter_module+from mineru.model.flash.xls import parser as xls_parser+from mineru.model.flash.xls.number_format import format_number, format_text+from mineru.model.flash.xls.records import RecordBudget+from mineru.types import BlockType, ImageBlock, MiddleJson, ModelJson, TableBlock++from _legacy_xls_test_utils import (+ SheetFixture,+ biff_record,+ build_biff5_xls,+ build_xls,+ continued_rich_sst,+ font_record,+ formula_number_cell,+ formula_string_cell,+ label_cell,+ labelsst_cell,+ merged_cells,+ rich_sst,+ url_hyperlink,+)+from _legacy_ppt_test_utils import _build_cfb+++_PROJECT_ROOT = Path(__file__).resolve().parents[2]+_REAL_XLS = (+ _PROJECT_ROOT+ / "output"+ / "office_roundtrip_research_20260824"+ / "legacy"+ / "xlsx_01.xls"+)+++def test_xls_model_preserves_visible_empty_pages_and_skips_hidden_sheet() -> None:+ """验证可见空表保留页位而隐藏 sheet 不输出。"""++ file_bytes = build_xls(+ [+ SheetFixture("Visible", label_cell(0, 0, "visible")),+ SheetFixture("Empty"),+ SheetFixture("Secret", label_cell(0, 0, "secret"), visible=False),+ ]+ )+ stream = BytesIO(file_bytes)++ pages = XlsModel().predict(stream)++ assert not stream.closed+ assert pages == [[{"type": BlockType.TEXT, "content": "visible"}], []]+++def test_backend_analyze_accepts_xls_and_async_contract() -> None:+ """验证同步与异步 Analyze 都返回严格 XLS 文档契约。"""++ file_bytes = build_xls([SheetFixture("Data", label_cell(0, 0, "value"))])+ middle_json, model_json = doc_analyze(file_bytes, file_suffix="xls")+ async_middle, async_model = asyncio.run(aio_doc_analyze(file_bytes, file_suffix="xls"))++ assert isinstance(model_json, ModelJson)+ assert isinstance(middle_json, MiddleJson)+ assert model_json.file_suffix == middle_json.file_suffix == "xls"+ assert model_json.effort == middle_json.effort == "flash"+ assert model_json.parse_mode == middle_json.parse_mode == "txt"+ assert model_json.is_full_document is middle_json.is_full_document is True+ assert async_model == model_json+ assert async_middle == middle_json+++def test_xls_formula_cache_merge_and_hyperlink_flow_into_table() -> None:+ """验证缓存公式、合并结构和安全链接进入同一 HTML 表格。"""++ records = (+ label_cell(0, 0, "header")+ + label_cell(0, 1, "link")+ + formula_number_cell(1, 0, 21.0)+ + formula_string_cell(1, 1, "#NAME?")+ + url_hyperlink(0, 1, "link", "https://example.test/path")+ + merged_cells((2, 0, 2, 1))+ + label_cell(2, 0, "merged")+ )++ pages = XlsModel().predict(BytesIO(build_xls([SheetFixture("Data", records)])))+ table = next(block for block in pages[0] if block["type"] == BlockType.TABLE)+ soup = BeautifulSoup(table["content"], "html.parser")++ assert soup.get_text(" ", strip=True).split() == [+ "header",+ "link",+ "21",+ "#NAME?",+ "merged",+ ]+ assert soup.find("a")["href"] == "https://example.test/path"+ assert soup.find(string="merged").find_parent(["th", "td"])["colspan"] == "2"+++def test_xls_rich_sst_uses_utf16_ranges_across_non_bmp_text() -> None:+ """验证非 BMP 字符的 UTF-16 rich run 边界不会偏移。"""++ globals_records = (+ font_record(bold=True)+ + font_record(italic=True)+ + rich_sst([("A😀B", [(0, 1), (3, 2)])])+ )+ pages = XlsModel().predict(+ BytesIO(+ build_xls(+ [SheetFixture("Rich", labelsst_cell(0, 0, 0))],+ globals_records=globals_records,+ )+ )+ )++ table = next(block for block in pages[0] if block["type"] == BlockType.TABLE)+ assert "<strong>A😀</strong>" in table["content"]+ assert "<em>B</em>" in table["content"]+++def test_xls_sst_character_data_can_cross_continue_records() -> None:+ """验证 SST 在字符中间切入 CONTINUE 后重读压缩标志并继续 rich runs。"""++ globals_records = (+ font_record(bold=True)+ + font_record(italic=True)+ + continued_rich_sst("A😀BC", [(0, 1), (3, 2)])+ )+ pages = XlsModel().predict(+ BytesIO(+ build_xls(+ [SheetFixture("Rich", labelsst_cell(0, 0, 0))],+ globals_records=globals_records,+ )+ )+ )++ table = next(block for block in pages[0] if block["type"] == BlockType.TABLE)+ assert "<strong>A😀</strong>" in table["content"]+ assert "<em>BC</em>" in table["content"]+++ ("format_code", "value", "expected"),+ [+ ("0.0%", 0.075, "7.5%"),+ ("#,##0.00", 1234.5, "1,234.50"),+ ('"$"#,##0.00', 1234.5, "$1,234.50"),+ ("0.00;(0.00)", -3.5, "(3.50)"),+ ("0.00E+00", 12345.0, "1.23E+04"),+ ("# ?/?", 5.25, "5 1/4"),+ ("# ?/8", 5.25, "5 2/8"),+ ("0.0,,", 12_345_678.0, "12.3"),+ ("0.00_);(0.00)", 3.5, "3.50 "),+ ('0.0\\ "m/s"', 3.51, "3.5 m/s"),+ ('"~"General" kg"', 1234.5, "~1234.5 kg"),+ ("yyyy-mm-dd", 46096.0, "2026-03-15"),+ ("[h]:mm:ss", 1.5, "36:00:00"),+ ],+)+def test_xls_number_formats_match_expected_visible_semantics(+ format_code: str,+ value: float,+ expected: str,+) -> None:+ """验证关键数值格式符合预期的稳定显示语义。"""++ assert format_number(value, format_code, date1904=False) == expected+++def test_xls_text_format_and_unsafe_hyperlink_fallback() -> None:+ """验证文本 section 生效且危险链接降级为普通文本。"""++ assert format_text("hi", '0;0;0;"* "@" *"') == "* hi *"+ records = label_cell(0, 0, "unsafe") + url_hyperlink(+ 0,+ 0,+ "unsafe",+ "javascript:alert(1)",+ )+ pages = XlsModel().predict(BytesIO(build_xls([SheetFixture("Data", records)])))+ assert pages == [[{"type": BlockType.TEXT, "content": "unsafe"}]]+ assert xls_parser._sanitize_hyperlink_target("mailto:[email protected]") == (+ "mailto:[email protected]"+ )+ assert xls_parser._sanitize_hyperlink_target("#Sheet2!A1") == "#Sheet2!A1"+ assert xls_parser._sanitize_hyperlink_target("../relative/path") == "../relative/path"+ assert xls_parser._sanitize_hyperlink_target("file:///tmp/local.xls") is None+ assert xls_parser._sanitize_hyperlink_target("custom:payload") is None+++def test_xls_filepass_and_broken_boundsheet_behaviors() -> None:+ """验证加密硬失败,而损坏 sheet offset 可按 worksheet BOF 恢复。"""++ with pytest.raises(LegacyOfficeEncryptedError, match="password-protected"):+ XlsModel().predict(BytesIO(build_xls([SheetFixture("Data")], encrypted=True)))++ pages = XlsModel().predict(+ BytesIO(+ build_xls(+ [SheetFixture("Recovered", label_cell(0, 0, "ok"))],+ corrupt_first_offset=True,+ )+ )+ )+ assert pages == [[{"type": BlockType.TEXT, "content": "ok"}]]+++def test_xls_encrypted_ooxml_marker_and_missing_workbook_are_stable_errors() -> None:+ """验证 OLE 加密包不会误判成 BIFF,缺失 Workbook/Book 返回稳定错误。"""++ encrypted = _build_cfb(+ [+ ("EncryptionInfo", b"marker"),+ ("EncryptedPackage", b"payload"),+ ]+ )+ with pytest.raises(LegacyOfficeEncryptedError, match="password-protected"):+ XlsModel().predict(BytesIO(encrypted))++ with pytest.raises(LegacyOfficeMissingPartError, match="Book"):+ XlsModel().predict(BytesIO(_build_cfb([("Other", b"payload")])))+++def test_xls_biff5_codepage_and_hidden_rows_columns_are_preserved() -> None:+ """验证 BIFF5 codepage 降级及用户选择的隐藏行列保留策略。"""++ assert XlsModel().predict(BytesIO(build_biff5_xls("légacy"))) == [+ [{"type": BlockType.TEXT, "content": "légacy"}]+ ]++ row = bytearray(16)+ struct.pack_into("<H", row, 0, 0)+ row[12] = 0x20+ colinfo = bytearray(12)+ struct.pack_into("<HH", colinfo, 0, 0, 0)+ colinfo[8] = 0x01+ records = (+ biff_record(0x0208, bytes(row))+ + biff_record(0x007D, bytes(colinfo))+ + label_cell(0, 0, "still visible")+ )++ assert XlsModel().predict(BytesIO(build_xls([SheetFixture("Data", records)]))) == [+ [{"type": BlockType.TEXT, "content": "still visible"}]+ ]+++def test_xls_record_and_grid_limits_are_hard_failures(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证记录访问与工作簿网格预算均不可静默绕过。"""++ budget = RecordBudget(count=MAX_RECORDS)+ with pytest.raises(LegacyOfficeResourceLimitError, match="max_records"):+ budget.charge()++ monkeypatch.setattr(xls_converter_module, "MAX_GRID_SLOTS", 0)+ with pytest.raises(LegacyOfficeResourceLimitError, match="max_grid_slots"):+ XlsModel().predict(+ BytesIO(build_xls([SheetFixture("Data", label_cell(0, 0, "value"))]))+ )+++def test_xls_is_not_routed_through_public_parser() -> None:+ """验证实现范围没有新增 XlsParser 或 parser/CLI 路由。"""++ office_source = (_PROJECT_ROOT / "mineru" / "parser" / "office.py").read_text(encoding="utf-8")+ parser_source = (_PROJECT_ROOT / "mineru" / "parser" / "__init__.py").read_text(encoding="utf-8")++ assert "class XlsParser" not in office_source+ assert '"xls": XlsParser' not in parser_source++[email protected](not _REAL_XLS.exists(), reason="real Office roundtrip fixture is local-only")+def test_real_xls_recovers_tables_charts_image_link_and_exports(tmp_path: Path) -> None:+ """验证真实 XLS 的三页结构、图表、图片、链接与 sidecar 闭包。"""++ middle_json, model_json = doc_analyze(_REAL_XLS.read_bytes(), file_suffix="xls")++ assert len(model_json.pages) == len(middle_json.pages) == 3+ assert model_json.file_suffix == middle_json.file_suffix == "xls"+ assert [+ [block.get("type") for block in page]+ for page in model_json.pages+ ] == [+ [BlockType.PARAGRAPH_TITLE, BlockType.TABLE],+ [+ BlockType.PARAGRAPH_TITLE,+ BlockType.TABLE,+ BlockType.TABLE,+ BlockType.CHART,+ BlockType.TABLE,+ BlockType.CHART,+ ],+ [BlockType.PARAGRAPH_TITLE, BlockType.TABLE, BlockType.TABLE, BlockType.IMAGE],+ ]++ page_one_table = next(+ block for block in middle_json.pages[0].blocks if isinstance(block, TableBlock)+ )+ page_one_soup = BeautifulSoup(page_one_table.content[0].content, "html.parser")+ page_one_rows = page_one_soup.find_all("tr")+ assert len(page_one_rows) == 9+ assert all(len(row.find_all(["th", "td"], recursive=False)) == 3 for row in page_one_rows)+ assert page_one_soup.find("a")["href"] == "http://www.baidu.com/"+ assert "21" in page_one_soup.get_text(" ", strip=True)+ assert "#NAME?" in page_one_soup.get_text(" ", strip=True)+ assert "(x+a)^n" in page_one_soup.get_text(" ", strip=True)++ chart_tables = [+ block.content[0].content+ for block in middle_json.pages[1].blocks+ if block.type == BlockType.CHART+ ]+ assert [+ (+ len(BeautifulSoup(content, "html.parser").find_all("tr")),+ max(+ len(row.find_all(["th", "td"], recursive=False))+ for row in BeautifulSoup(content, "html.parser").find_all("tr")+ ),+ )+ for content in chart_tables+ ] == [(5, 2), (9, 4)]++ page_three_tables = [+ block for block in middle_json.pages[2].blocks if isinstance(block, TableBlock)+ ]+ assert len(page_three_tables) == 2+ assert all(+ len(+ [+ cell+ for cell in BeautifulSoup(table.content[0].content, "html.parser").find_all(+ ["th", "td"]+ )+ if cell.has_attr("rowspan") or cell.has_attr("colspan")+ ]+ )+ == 4+ for table in page_three_tables+ )+ assert sum(isinstance(block, ImageBlock) for block in middle_json.pages[2].blocks) == 1++ export_result = middle_json.export(tmp_path / "export")+ exported = export_result.middle_json.model_dump(mode="json", exclude_none=True)+ assert export_result.json_path.exists()+ assert len(export_result.image_paths) == 1+ assert export_result.image_paths[0].exists()+ assert "image_base64" not in str(exported)diff --git a/tests/unittest/test_flash_office_models.py b/tests/unittest/test_flash_office_models.pyindex ae1fb461..4a342b09 100644--- a/tests/unittest/test_flash_office_models.py+++ b/tests/unittest/test_flash_office_models.py@@ -12,11 +12,13 @@ import pytestimport mineru.model.flash as flash_modelsimport mineru.model.flash.model as flat_model_module-from mineru.model.flash import DocxModel, PdfModel, PptxModel, XlsxModel+from mineru.model.flash import DocxModel, PdfModel, PptModel, PptxModel, XlsModel, XlsxModelfrom mineru.model.flash.docx import docx_converter as docx_converter_modulefrom mineru.model.flash.docx import main as docx_mainfrom mineru.model.flash.pptx import main as pptx_mainfrom mineru.model.flash.pptx import pptx_converter as pptx_converter_module+from mineru.model.flash.ppt import ppt_converter as ppt_converter_module+from mineru.model.flash.xls import xls_converter as xls_converter_modulefrom mineru.model.flash.xlsx import main as xlsx_mainfrom mineru.model.flash.xlsx import xlsx_converter as xlsx_converter_module@@ -59,6 +61,8 @@ def test_flash_office_model_conversion([(DocxModel, docx_converter_module, "DocxConverter"),(PptxModel, pptx_converter_module, "PptxConverter"),+ (PptModel, ppt_converter_module, "PptConverter"),+ (XlsModel, xls_converter_module, "XlsConverter"),(XlsxModel, xlsx_converter_module, "XlsxConverter"),],)@@ -145,12 +149,21 @@ def test_convert_path_delegates_to_binary_helper(def test_models_are_exported_from_flash_root() -> None:- """验证四个模型统一由 Flash 根包公开。"""-- assert flash_models.__all__ == ["PdfModel", "DocxModel", "PptxModel", "XlsxModel"]+ """验证全部模型统一由 Flash 根包公开。"""++ assert flash_models.__all__ == [+ "PdfModel",+ "DocxModel",+ "PptModel",+ "PptxModel",+ "XlsModel",+ "XlsxModel",+ ]assert PdfModel is flat_model_module.PdfModelassert DocxModel is flat_model_module.DocxModelassert PptxModel is flat_model_module.PptxModel+ assert PptModel is flat_model_module.PptModel+ assert XlsModel is flat_model_module.XlsModelassert XlsxModel is flat_model_module.XlsxModel@@ -159,6 +172,8 @@ def test_models_are_exported_from_flash_root() -> None:[("mineru.model.flash.docx", "DocxModel"),("mineru.model.flash.pptx", "PptxModel"),+ ("mineru.model.flash.ppt", "PptModel"),+ ("mineru.model.flash.xls", "XlsModel"),("mineru.model.flash.xlsx", "XlsxModel"),],)@@ -180,6 +195,9 @@ def test_importing_pdf_model_does_not_load_office_converters() -> None:"assert PdfModel.__name__ == 'PdfModel'","assert 'mineru.model.flash.docx.docx_converter' not in sys.modules","assert 'mineru.model.flash.pptx.pptx_converter' not in sys.modules",+ "assert 'mineru.model.flash.ppt.ppt_converter' not in sys.modules",+ "assert 'mineru.model.flash.xls.xls_converter' not in sys.modules",+ "assert 'olefile' not in sys.modules","assert 'mineru.model.flash.xlsx.xlsx_converter' not in sys.modules",])@@ -196,7 +214,13 @@ def test_importing_pdf_model_does_not_load_office_converters() -> None:@pytest.mark.parametrize("module_name",- ["mineru.model.docx", "mineru.model.pptx", "mineru.model.xlsx"],+ [+ "mineru.model.docx",+ "mineru.model.ppt",+ "mineru.model.pptx",+ "mineru.model.xls",+ "mineru.model.xlsx",+ ],)def test_legacy_office_model_paths_are_removed(module_name: str) -> None:"""验证迁移后不再暴露旧的 Office 模型包路径。"""diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.pyindex fa61a74d..e84923f0 100644--- a/tests/unittest/test_pdf_analyze_visual_blocks.py+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py@@ -1250,12 +1250,12 @@ def test_aio_doc_analyze_propagates_sync_entrypoint_error(asyncio.run(analyze.aio_doc_analyze(b"invalid-document"))[email protected]("file_suffix", ["docx", "pptx", "xlsx"])[email protected]("file_suffix", ["docx", "ppt", "pptx", "xls", "xlsx"])def test_doc_analyze_office_returns_model_json_without_pdf_processing(monkeypatch: pytest.MonkeyPatch,file_suffix: str,) -> None:- """验证三类 Office 文件返回严格 ModelJson,且不进入任何 PDF 处理阶段。"""+ """验证五类 Office 文件返回严格 ModelJson,且不进入任何 PDF 处理阶段。"""source_model_list = [[{"type": BlockType.TEXT, "content": "原始 \\(office\\) 内容"}]]events: list[str] = []model_factories: dict[str, MagicMock] = {}@@ -1267,7 +1267,7 @@ def test_doc_analyze_office_returns_model_json_without_pdf_processing(return source_model_listselected_model.predict.side_effect = fake_office_predict- for suffix in ("docx", "pptx", "xlsx"):+ for suffix in ("docx", "ppt", "pptx", "xls", "xlsx"):model = selected_model if suffix == file_suffix else MagicMock()model_factories[suffix] = MagicMock(return_value=model)@@ -1339,7 +1339,9 @@ def test_doc_analyze_rejects_unsupported_suffix_before_resource_initialization() -> None:"""验证非法后缀会在创建 PDF 文档或 Office 模型前直接报错。"""pdf_document = MagicMock()- model_factories = {suffix: MagicMock() for suffix in ("docx", "pptx", "xlsx")}+ model_factories = {+ suffix: MagicMock() for suffix in ("docx", "ppt", "pptx", "xls", "xlsx")+ }monkeypatch.setattr(pipeline, "PDFDocument", pdf_document)monkeypatch.setattr(office, "_OFFICE_MODEL_MAP", model_factories)