Skip to content

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

feat: implement DOC binary parsing and related structures for Word 97–2003

myhlolidd26bce3faba
diff --git a/docs/next/middle-json/current-medium.md b/docs/next/middle-json/current-medium.md
index 4130df9f..666338c5 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/ppt/pptx/xls/xlsx` | 必填 |
+| `file_suffix` | `pdf/doc/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/ppt/pptx/xls/xlsx` | 必填 |
+| `file_suffix` | `pdf/doc/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.py
index b51f2fbc..e47e5774 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", "ppt", "pptx", "xls", "xlsx"]
+OfficeSuffix: TypeAlias = Literal["doc", "docx", "ppt", "pptx", "xls", "xlsx"]
@dataclass(slots=True)
diff --git a/mineru/backend/analysis/office.py b/mineru/backend/analysis/office.py
index b857e365..b8c490a0 100644
--- a/mineru/backend/analysis/office.py
+++ b/mineru/backend/analysis/office.py
@@ -6,11 +6,12 @@ from __future__ import annotations
import time
from io import BytesIO
-from mineru.model.flash import DocxModel, PptModel, PptxModel, XlsModel, XlsxModel
+from mineru.model.flash import DocModel, DocxModel, PptModel, PptxModel, XlsModel, XlsxModel
from .contracts import AnalysisResult, OfficeSuffix
_OFFICE_MODEL_MAP = {
+ "doc": DocModel,
"docx": DocxModel,
"ppt": PptModel,
"pptx": PptxModel,
diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.py
index e97ba899..b243b479 100644
--- a/mineru/backend/analyze.py
+++ b/mineru/backend/analyze.py
@@ -16,7 +16,7 @@ from mineru.config import config
from mineru.types import MiddleJson, ModelJson
from mineru.version import __version__ as mineru_version
-_SUPPORTED_FILE_SUFFIXES = {"pdf", "docx", "ppt", "pptx", "xls", "xlsx"}
+_SUPPORTED_FILE_SUFFIXES = {"pdf", "doc", "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", "ppt", "pptx", "xls", "xlsx"] = "pdf",
+ file_suffix: Literal["pdf", "doc", "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", "ppt", "pptx", "xls", "xlsx"] = "pdf",
+ file_suffix: Literal["pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx"] = "pdf",
) -> tuple[MiddleJson, ModelJson]:
"""在线程中执行统一文档分析,避免阻塞调用方事件循环。"""
return await asyncio.to_thread(
diff --git a/mineru/backend/postprocess/lists.py b/mineru/backend/postprocess/lists.py
index 85e78ee1..be2ffa21 100644
--- a/mineru/backend/postprocess/lists.py
+++ b/mineru/backend/postprocess/lists.py
@@ -188,8 +188,14 @@ def fix_office_list_blocks(list_blocks: list[dict[str, Any]]) -> list[dict[str,
if child_type == BlockType.TEXT:
child_content = child_block.get("content")
if not isinstance(child_content, str):
+ child_block.pop("list_label", None)
continue
- if is_ordered:
+ exact_label = child_block.pop("list_label", None)
+ if isinstance(exact_label, str) and exact_label.strip():
+ prefix = f"{exact_label.strip()} "
+ if is_ordered:
+ ordered_number += 1
+ elif is_ordered:
prefix = f"{ordered_number}. "
ordered_number += 1
else:
diff --git a/mineru/model/flash/__init__.py b/mineru/model/flash/__init__.py
index 4992afac..404d9f81 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, PptModel, PptxModel, XlsModel, XlsxModel
+from .model import DocModel, DocxModel, PdfModel, PptModel, PptxModel, XlsModel, XlsxModel
-__all__ = ["PdfModel", "DocxModel", "PptModel", "PptxModel", "XlsModel", "XlsxModel"]
+__all__ = ["PdfModel", "DocModel", "DocxModel", "PptModel", "PptxModel", "XlsModel", "XlsxModel"]
diff --git a/mineru/model/flash/doc/__init__.py b/mineru/model/flash/doc/__init__.py
new file mode 100644
index 00000000..f6a747e1
--- /dev/null
+++ b/mineru/model/flash/doc/__init__.py
@@ -0,0 +1,4 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""Word 97–2003 二进制文档解析实现。"""
+
diff --git a/mineru/model/flash/doc/bookmarks.py b/mineru/model/flash/doc/bookmarks.py
new file mode 100644
index 00000000..cfb77fbf
--- /dev/null
+++ b/mineru/model/flash/doc/bookmarks.py
@@ -0,0 +1,83 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""解析 DOC 标准书签名称及其主文档 CP 范围。"""
+
+from __future__ import annotations
+
+from .records import DocBudget, bounded_slice, get_u16, parse_plc
+
+
+def _parse_string_table(data: bytes, budget: DocBudget) -> list[str]:
+ """解析扩展或单字节 STTB 字符串表。"""
+
+ if len(data) < 2:
+ return []
+ extended = get_u16(data, 0) == 0xFFFF
+ if extended:
+ count = get_u16(data, 2)
+ extra = get_u16(data, 4)
+ cursor = 6
+ else:
+ count = get_u16(data, 0)
+ extra = get_u16(data, 2)
+ cursor = 4
+ if count is None or extra is None:
+ return []
+ strings: list[str] = []
+ for _ in range(count):
+ if extended:
+ length = get_u16(data, cursor)
+ cursor += 2
+ width = 2
+ else:
+ length = data[cursor] if cursor < len(data) else None
+ cursor += 1
+ width = 1
+ if length is None or length == 0xFFFF:
+ strings.append("")
+ continue
+ payload = bounded_slice(data, cursor, length * width)
+ if payload is None:
+ break
+ cursor += length * width
+ strings.append(payload.decode("utf-16le" if extended else "cp1252", errors="replace"))
+ cursor += extra
+ budget.charge()
+ return strings
+
+
+def parse_bookmarks(
+ table_stream: bytes,
+ *,
+ names_offset: int,
+ names_size: int,
+ starts_offset: int,
+ starts_size: int,
+ ends_offset: int,
+ ends_size: int,
+ budget: DocBudget,
+) -> dict[int, list[str]]:
+ """返回主文档中书签起始 CP 到名称列表的映射。"""
+
+ names_payload = bounded_slice(table_stream, names_offset, names_size)
+ starts_payload = bounded_slice(table_stream, starts_offset, starts_size)
+ ends_payload = bounded_slice(table_stream, ends_offset, ends_size)
+ if names_payload is None or starts_payload is None or ends_payload is None:
+ return {}
+ names = _parse_string_table(names_payload, budget)
+ start_cps, start_items = parse_plc(starts_payload, item_size=4, budget=budget)
+ end_cps, _ = parse_plc(ends_payload, item_size=0, budget=budget)
+ result: dict[int, list[str]] = {}
+ for index, (name, item) in enumerate(zip(names, start_items, strict=False)):
+ if not name or name.startswith("_GoBack") or index >= len(start_cps):
+ continue
+ end_index = get_u16(item, 0)
+ if end_index is None or end_index >= max(len(end_cps) - 1, 0):
+ continue
+ start = start_cps[index]
+ end = end_cps[end_index]
+ if end < start:
+ continue
+ result.setdefault(start, []).append(name)
+ return result
+
diff --git a/mineru/model/flash/doc/doc_converter.py b/mineru/model/flash/doc/doc_converter.py
new file mode 100644
index 00000000..95e62254
--- /dev/null
+++ b/mineru/model/flash/doc/doc_converter.py
@@ -0,0 +1,431 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""把 Word 97–2003 语义模型转换为 MinerU 分页 model-list。"""
+
+from __future__ import annotations
+
+from html import escape
+import re
+from typing import Any, BinaryIO, Iterable
+
+from mineru.model.flash.legacy_office import BoundedOleReader, LegacyOfficeEncryptedError
+from mineru.model.flash.office.image import serialize_office_image
+from mineru.model.office_stream import read_stream_bytes_from_start
+from mineru.types import RAW_CAPTION, BlockType
+from mineru.utils.office_rich_text import OfficeRichTextSegment, build_rich_text_from_segments
+
+from .fib import parse_fib
+from .models import (
+ DocCharStyle,
+ DocDocument,
+ DocElement,
+ DocImage,
+ DocImagePayload,
+ DocParagraph,
+ DocSection,
+ DocTable,
+ DocTableCell,
+ DocTextRun,
+)
+from .parser import parse_doc_document
+
+
+class DocConverter:
+ """将 Word 97–2003 OLE 二进制流转换为逐 section raw blocks。"""
+
+ def __init__(self) -> None:
+ """初始化空输出。"""
+
+ self.pages: list[list[dict[str, Any]]] = []
+
+ def convert(self, file_binary: BinaryIO) -> None:
+ """读取输入 OLE streams,解析 DOC 并生成 model-list。"""
+
+ file_bytes = read_stream_bytes_from_start(file_binary)
+ with BoundedOleReader(file_bytes) as ole:
+ if ole.has_stream("EncryptedPackage") or ole.has_stream("EncryptionInfo"):
+ raise LegacyOfficeEncryptedError("encrypted OOXML package is not a binary DOC")
+ word_document = ole.read_stream("WordDocument")
+ fib = parse_fib(word_document)
+ if fib.base.encrypted or fib.base.obfuscated:
+ raise LegacyOfficeEncryptedError("password-protected DOC is unsupported")
+ preferred = "1Table" if fib.base.uses_1table else "0Table"
+ alternate = "0Table" if preferred == "1Table" else "1Table"
+ table_stream = ole.read_stream(preferred, required=False)
+ if not table_stream:
+ table_stream = ole.read_stream(alternate, required=bool(fib.base.complex))
+ data_stream = ole.read_stream("Data", required=False)
+ document = parse_doc_document(word_document, table_stream, data_stream, fib)
+ self.pages = self._document_pages(document)
+
+ @staticmethod
+ def _style_names(style: DocCharStyle) -> list[str]:
+ """把 DOC 字符属性转换为 MinerU 富文本样式名。"""
+
+ names: list[str] = []
+ if style.bold:
+ names.append("bold")
+ if style.italic:
+ names.append("italic")
+ if style.underline:
+ names.append("underline")
+ if style.emphasis:
+ names.append("emphasis")
+ if style.strike:
+ names.append("strikethrough")
+ if style.superscript:
+ names.append("superscript")
+ elif style.subscript:
+ names.append("subscript")
+ return names
+
+ @classmethod
+ def _rich_text(cls, runs: Iterable[DocTextRun], *, trim: bool = True) -> str:
+ """把 DOC runs 转换为已转义的 Office 富文本协议。"""
+
+ segments = [
+ OfficeRichTextSegment(
+ text=escape(run.text, quote=False).replace("\n", "<br/>"),
+ style=cls._style_names(run.style),
+ hyperlink=escape(run.hyperlink, quote=True) if run.hyperlink else None,
+ )
+ for run in runs
+ if run.text
+ ]
+ return build_rich_text_from_segments(segments, trim_plain_edges=trim)
+
+ @staticmethod
+ def _plain_text(paragraph: DocParagraph) -> str:
+ """返回段落不含内部标记的可见文本。"""
+
+ return "".join(run.text for run in paragraph.runs)
+
+ @staticmethod
+ def _serialize_image(payload: DocImagePayload) -> str | None:
+ """复用 Office 图片序列化与矢量占位策略。"""
+
+ return serialize_office_image(
+ payload.data,
+ part_name=f"image.{payload.extension}",
+ content_type=payload.content_type,
+ )
+
+ @classmethod
+ def _image_block(cls, payload: DocImagePayload) -> dict[str, Any] | None:
+ """把原始图片载荷转换为 raw image block。"""
+
+ image_base64 = cls._serialize_image(payload)
+ if image_base64 is None:
+ return None
+ return {"type": BlockType.IMAGE, "image_base64": image_base64}
+
+ @classmethod
+ def _toc_runs(cls, paragraph: DocParagraph) -> list[DocTextRun]:
+ """从 TOC 段落末尾移除仅用于排版的 tab/page number。"""
+
+ runs = list(paragraph.runs)
+ while runs and re.fullmatch(r"[\s\t]*\d+[\s\t]*", runs[-1].text):
+ runs.pop()
+ if runs:
+ cleaned = re.sub(r"\t+\s*\d+\s*$", "", runs[-1].text)
+ if cleaned != runs[-1].text:
+ last = runs[-1]
+ runs[-1] = DocTextRun(cleaned, last.style, last.hyperlink)
+ return runs
+
+ @classmethod
+ def _toc_anchor(cls, paragraph: DocParagraph) -> str | None:
+ """读取 TOC 超链接指向的内部书签。"""
+
+ for run in paragraph.runs:
+ if run.hyperlink and run.hyperlink.startswith("#") and len(run.hyperlink) > 1:
+ return run.hyperlink[1:]
+ return paragraph.anchor
+
+ @classmethod
+ def _append_index_item(
+ cls,
+ page: list[dict[str, Any]],
+ stack: list[dict[str, Any]],
+ paragraph: DocParagraph,
+ ) -> None:
+ """把一个 TOC 段落追加到对应层级的 index 树。"""
+
+ content = cls._rich_text(cls._toc_runs(paragraph))
+ if not content:
+ return
+ level = min(max(paragraph.toc_level or 0, 0), 8)
+ while len(stack) > level + 1:
+ stack.pop()
+ while len(stack) < level + 1:
+ index_block: dict[str, Any] = {
+ "type": BlockType.INDEX,
+ "ilevel": len(stack),
+ "content": [],
+ }
+ if stack:
+ stack[-1]["content"].append(index_block)
+ else:
+ page.append(index_block)
+ stack.append(index_block)
+ leaf: dict[str, Any] = {"type": BlockType.TEXT, "content": content}
+ anchor = cls._toc_anchor(paragraph)
+ if anchor:
+ leaf["anchor"] = anchor
+ stack[level]["content"].append(leaf)
+
+ @classmethod
+ def _append_list_item(
+ cls,
+ page: list[dict[str, Any]],
+ stack: list[dict[str, Any]],
+ identity: int | None,
+ paragraph: DocParagraph,
+ ) -> int:
+ """把一个 DOC 列表段落追加到嵌套 raw list 树。"""
+
+ info = paragraph.list_info
+ if info is None:
+ return identity or -1
+ content = cls._rich_text(paragraph.runs)
+ if not content and not paragraph.images:
+ return identity or info.identity
+ if identity != info.identity:
+ stack.clear()
+ identity = info.identity
+ level = min(max(info.level, 0), 8)
+ while len(stack) > level + 1:
+ stack.pop()
+ while len(stack) < level + 1:
+ list_block: dict[str, Any] = {
+ "type": BlockType.LIST,
+ "attribute": "ordered" if info.ordered else "unordered",
+ "ilevel": len(stack),
+ "content": [],
+ }
+ if info.ordered:
+ list_block["start"] = info.start
+ if stack:
+ stack[-1]["content"].append(list_block)
+ else:
+ page.append(list_block)
+ stack.append(list_block)
+ current = stack[level]
+ expected = "ordered" if info.ordered else "unordered"
+ if current.get("attribute") != expected:
+ del stack[level:]
+ return cls._append_list_item(page, stack, None, paragraph)
+ if content:
+ leaf: dict[str, Any] = {"type": BlockType.TEXT, "content": content}
+ if info.label:
+ leaf["list_label"] = info.label
+ current["content"].append(leaf)
+ return info.identity
+
+ @classmethod
+ def _paragraph_blocks(cls, paragraph: DocParagraph) -> list[dict[str, Any]]:
+ """把非目录、非普通列表段落投影为 raw blocks。"""
+
+ content = cls._rich_text(paragraph.runs)
+ blocks: list[dict[str, Any]] = []
+ list_info = paragraph.list_info
+ exact_label = list_info.label if list_info is not None and list_info.ordered else None
+ if exact_label and (paragraph.is_title or paragraph.heading_level is not None):
+ content = f"{escape(exact_label, quote=False)} {content}".strip()
+ if content:
+ if paragraph.is_title:
+ block: dict[str, Any] = {
+ "type": BlockType.DOC_TITLE,
+ "level": 1,
+ "content": content,
+ }
+ elif paragraph.heading_level is not None:
+ block = {
+ "type": BlockType.PARAGRAPH_TITLE,
+ "level": min(max(paragraph.heading_level + 1, 2), 6),
+ "is_numbered_style": False,
+ "content": content,
+ }
+ elif paragraph.is_caption:
+ block = {"type": RAW_CAPTION, "content": content}
+ elif paragraph.is_code:
+ block = {"type": BlockType.CODE, "content": cls._plain_text(paragraph)}
+ else:
+ block = {"type": BlockType.TEXT, "content": content}
+ if paragraph.anchor and block["type"] in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
+ block["anchor"] = paragraph.anchor
+ blocks.append(block)
+ for payload in paragraph.images:
+ image = cls._image_block(payload)
+ if image is not None:
+ blocks.append(image)
+ return blocks
+
+ @classmethod
+ def _cell_list_html(cls, paragraphs: list[DocParagraph]) -> str:
+ """把连续表格单元格列表段落序列化为嵌套 HTML list。"""
+
+ result: list[str] = []
+ stack: list[str] = []
+ for paragraph in paragraphs:
+ info = paragraph.list_info
+ if info is None:
+ while stack:
+ result.append(f"</{stack.pop()}>")
+ result.append(cls._cell_paragraph_html(paragraph))
+ continue
+ level = min(max(info.level, 0), 8)
+ tag = "ol" if info.ordered else "ul"
+ while len(stack) > level + 1:
+ result.append(f"</{stack.pop()}>")
+ while len(stack) < level + 1:
+ result.append(f"<{tag}>")
+ stack.append(tag)
+ if stack[-1] != tag:
+ result.append(f"</{stack.pop()}><{tag}>")
+ stack.append(tag)
+ label = f"{escape(info.label)} " if info.label and info.ordered else ""
+ result.append(f"<li>{label}{cls._rich_text(paragraph.runs)}</li>")
+ while stack:
+ result.append(f"</{stack.pop()}>")
+ return "".join(result)
+
+ @classmethod
+ def _cell_paragraph_html(cls, paragraph: DocParagraph) -> str:
+ """序列化一个表格单元格段落及其内联图片。"""
+
+ parts: list[str] = []
+ content = cls._rich_text(paragraph.runs, trim=False)
+ if content:
+ parts.append(f"<p>{content}</p>")
+ for payload in paragraph.images:
+ image = cls._serialize_image(payload)
+ if image:
+ parts.append(f'<img src="{escape(image, quote=True)}"/>')
+ return "".join(parts)
+
+ @classmethod
+ def _cell_html(cls, cell: DocTableCell) -> str:
+ """递归序列化单元格中的段落和嵌套表格。"""
+
+ parts: list[str] = []
+ paragraph_buffer: list[DocParagraph] = []
+
+ def flush() -> None:
+ """输出当前连续段落缓冲。"""
+
+ nonlocal paragraph_buffer
+ if paragraph_buffer:
+ parts.append(cls._cell_list_html(paragraph_buffer))
+ paragraph_buffer = []
+
+ for block in cell.blocks:
+ if isinstance(block, DocParagraph):
+ paragraph_buffer.append(block)
+ elif isinstance(block, DocTable):
+ flush()
+ parts.append(cls._table_html(block))
+ elif isinstance(block, DocImage):
+ flush()
+ image = cls._serialize_image(block.payload)
+ if image:
+ parts.append(f'<img src="{escape(image, quote=True)}"/>')
+ flush()
+ return "".join(parts)
+
+ @classmethod
+ def _table_html(cls, table: DocTable) -> str:
+ """序列化带 rowspan/colspan 及嵌套内容的 Word 表格。"""
+
+ rows: list[str] = []
+ for row in table.rows:
+ tag = "th" if row.header else "td"
+ cells: list[str] = []
+ for cell in row.cells:
+ 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}"')
+ suffix = f" {' '.join(attributes)}" if attributes else ""
+ cells.append(f"<{tag}{suffix}>{cls._cell_html(cell)}</{tag}>")
+ rows.append(f"<tr>{''.join(cells)}</tr>")
+ return f"<table>{''.join(rows)}</table>"
+
+ @classmethod
+ def _element_blocks(cls, element: DocElement) -> list[dict[str, Any]]:
+ """把正文语义元素转换为 raw block。"""
+
+ if isinstance(element, DocImage):
+ image = cls._image_block(element.payload)
+ return [image] if image is not None else []
+ if isinstance(element, DocTable):
+ return [{"type": BlockType.TABLE, "content": cls._table_html(element)}]
+ return cls._paragraph_blocks(element)
+
+ @classmethod
+ def _auxiliary_contents(cls, paragraphs: list[DocParagraph]) -> list[str]:
+ """去重页眉页脚段落并过滤纯页码。"""
+
+ result: list[str] = []
+ seen: set[str] = set()
+ for paragraph in paragraphs:
+ content = cls._rich_text(paragraph.runs)
+ plain = cls._plain_text(paragraph).strip()
+ if not content or plain.isdigit() or content in seen:
+ continue
+ seen.add(content)
+ result.append(content)
+ return result
+
+ @classmethod
+ def _section_page(cls, section: DocSection) -> list[dict[str, Any]]:
+ """转换一个 section,并将页面辅助文本稳定追加到末尾。"""
+
+ page: list[dict[str, Any]] = []
+ list_stack: list[dict[str, Any]] = []
+ list_identity: int | None = None
+ index_stack: list[dict[str, Any]] = []
+ for element in section.elements:
+ if isinstance(element, DocParagraph) and element.is_toc:
+ list_stack.clear()
+ list_identity = None
+ cls._append_index_item(page, index_stack, element)
+ for payload in element.images:
+ image = cls._image_block(payload)
+ if image is not None:
+ page.append(image)
+ continue
+ index_stack.clear()
+ if isinstance(element, DocParagraph) and element.list_info is not None and not (
+ element.is_title or element.heading_level is not None
+ ):
+ list_identity = cls._append_list_item(page, list_stack, list_identity, element)
+ for payload in element.images:
+ image = cls._image_block(payload)
+ if image is not None:
+ page.append(image)
+ continue
+ list_stack.clear()
+ list_identity = None
+ page.extend(cls._element_blocks(element))
+ page.extend(
+ {"type": BlockType.HEADER, "content": content}
+ for content in cls._auxiliary_contents(section.headers)
+ )
+ page.extend(
+ {"type": BlockType.FOOTER, "content": content}
+ for content in cls._auxiliary_contents(section.footers)
+ )
+ page.extend(
+ {"type": BlockType.PAGE_FOOTNOTE, "content": content}
+ for content in cls._auxiliary_contents(section.footnotes)
+ )
+ return page
+
+ @classmethod
+ def _document_pages(cls, document: DocDocument) -> list[list[dict[str, Any]]]:
+ """转换整份 DOC,并至少保留一个空 section page。"""
+
+ pages = [cls._section_page(section) for section in document.sections]
+ return pages or [[]]
diff --git a/mineru/model/flash/doc/fib.py b/mineru/model/flash/doc/fib.py
new file mode 100644
index 00000000..002a2043
--- /dev/null
+++ b/mineru/model/flash/doc/fib.py
@@ -0,0 +1,269 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""读取 Word 97–2003 WordDocument stream 中的变长 FIB。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import struct
+
+from mineru.model.flash.legacy_office import LegacyOfficeMalformedError
+
+FIB_IDENT = 0xA5EC
+MIN_WORD97_NFIB = 0x00C1
+
+FCLCB_STSHF = 1
+FCLCB_FOOTNOTE_REF = 2
+FCLCB_FOOTNOTE_TEXT = 3
+FCLCB_SECTION = 6
+FCLCB_HEADER = 11
+FCLCB_BTE_CHPX = 12
+FCLCB_BTE_PAPX = 13
+FCLCB_FIELD_MAIN = 16
+FCLCB_FIELD_HEADER = 17
+FCLCB_FIELD_FOOTNOTE = 18
+FCLCB_BOOKMARK_NAMES = 21
+FCLCB_BOOKMARK_START = 22
+FCLCB_BOOKMARK_END = 23
+FCLCB_DOP = 31
+FCLCB_CLX = 33
+FCLCB_SHAPE_MAIN = 40
+FCLCB_SHAPE_HEADER = 41
+FCLCB_ENDNOTE_REF = 46
+FCLCB_ENDNOTE_TEXT = 47
+FCLCB_FIELD_ENDNOTE = 48
+FCLCB_DGG_INFO = 50
+FCLCB_TEXTBOX_TEXT = 56
+FCLCB_FIELD_TEXTBOX = 57
+FCLCB_HEADER_TEXTBOX_TEXT = 58
+FCLCB_FIELD_HEADER_TEXTBOX = 59
+FCLCB_LISTS = 73
+FCLCB_LIST_OVERRIDES = 74
+FCLCB_TEXTBOX_BREAK = 75
+FCLCB_HEADER_TEXTBOX_BREAK = 76
+
+
+@dataclass(frozen=True, slots=True)
+class FcLcb:
+ """FIB 中一对 stream 偏移和字节长度。"""
+
+ fc: int = 0
+ lcb: int = 0
+
+
+@dataclass(frozen=True, slots=True)
+class FibBase:
+ """FIB 固定头中与解析相关的字段。"""
+
+ n_fib: int
+ lid: int
+ flags: int
+ fc_min: int
+ fc_mac: int
+
+ @property
+ def complex(self) -> bool:
+ """返回文档是否使用 complex/fast-save piece table。"""
+
+ return bool(self.flags & 0x0004)
+
+ @property
+ def encrypted(self) -> bool:
+ """返回文档是否设置加密标志。"""
+
+ return bool(self.flags & 0x0100)
+
+ @property
+ def uses_1table(self) -> bool:
+ """返回 FIB 指定的首选 Table stream。"""
+
+ return bool(self.flags & 0x0200)
+
+ @property
+ def far_east(self) -> bool:
+ """返回文档是否优先使用远东语言标识。"""
+
+ return bool(self.flags & 0x4000)
+
+ @property
+ def obfuscated(self) -> bool:
+ """返回文档是否设置 XOR 混淆标志。"""
+
+ return bool(self.flags & 0x8000)
+
+
+@dataclass(frozen=True, slots=True)
+class FileInformationBlock:
+ """完成边界校验的 Word 97+ FIB。"""
+
+ base: FibBase
+ rgw: tuple[int, ...]
+ rglw: tuple[int, ...]
+ pairs: tuple[FcLcb, ...]
+ csw_new: tuple[int, ...]
+ size: int
+
+ @property
+ def n_fib(self) -> int:
+ """返回版本扩展中的有效 nFib。"""
+
+ return self.csw_new[0] if self.csw_new else self.base.n_fib
+
+ def pair(self, index: int) -> FcLcb:
+ """读取可选 fc/lcb 对,不存在时返回零值。"""
+
+ return self.pairs[index] if 0 <= index < len(self.pairs) else FcLcb()
+
+ def story_count(self, index: int) -> int:
+ """读取 FibRgLw97 中一个 story 的 UTF-16 CP 数。"""
+
+ return int(self.rglw[index]) if 0 <= index < len(self.rglw) else 0
+
+ @property
+ def ccp_text(self) -> int:
+ """返回主文档 story 的 CP 数。"""
+
+ return self.story_count(3)
+
+ @property
+ def ccp_footnote(self) -> int:
+ """返回脚注 story 的 CP 数。"""
+
+ return self.story_count(4)
+
+ @property
+ def ccp_header(self) -> int:
+ """返回页眉页脚 story 的 CP 数。"""
+
+ return self.story_count(5)
+
+ @property
+ def ccp_macro(self) -> int:
+ """返回宏 story 的 CP 数。"""
+
+ return self.story_count(6)
+
+ @property
+ def ccp_annotation(self) -> int:
+ """返回批注 story 的 CP 数。"""
+
+ return self.story_count(7)
+
+ @property
+ def ccp_endnote(self) -> int:
+ """返回尾注 story 的 CP 数。"""
+
+ return self.story_count(8)
+
+ @property
+ def ccp_textbox(self) -> int:
+ """返回正文文本框 story 的 CP 数。"""
+
+ return self.story_count(9)
+
+ @property
+ def ccp_header_textbox(self) -> int:
+ """返回页眉文本框 story 的 CP 数。"""
+
+ return self.story_count(10)
+
+ @property
+ def total_story_cp(self) -> int:
+ """返回全部已知 story 的累计 CP 数。"""
+
+ return sum(self.story_count(index) for index in range(3, 11))
+
+ @property
+ def story_bases(self) -> dict[str, int]:
+ """返回各 story 在全局 CP 空间中的起点。"""
+
+ counts = [self.story_count(index) for index in range(3, 11)]
+ names = [
+ "main",
+ "footnote",
+ "header",
+ "macro",
+ "annotation",
+ "endnote",
+ "textbox",
+ "header_textbox",
+ ]
+ bases: dict[str, int] = {}
+ cursor = 0
+ for name, count in zip(names, counts, strict=True):
+ bases[name] = cursor
+ cursor += count
+ return bases
+
+
+def _read_values(data: bytes, offset: int, count: int, width: int, label: str) -> tuple[tuple[int, ...], int]:
+ """按指定宽度读取一组无符号小端整数。"""
+
+ if count < 0 or width not in {2, 4}:
+ raise LegacyOfficeMalformedError(f"invalid {label} count")
+ size = count * width
+ end = offset + size
+ if offset < 0 or end < offset or end > len(data):
+ raise LegacyOfficeMalformedError(f"truncated FIB {label}")
+ if count == 0:
+ return (), end
+ code = "H" if width == 2 else "I"
+ return tuple(int(value) for value in struct.unpack_from(f"<{count}{code}", data, offset)), end
+
+
+def parse_fib(word_document: bytes) -> FileInformationBlock:
+ """按 MS-DOC 变长布局解析 FIB,并拒绝 Word 95 及更早版本。"""
+
+ if len(word_document) < 34:
+ raise LegacyOfficeMalformedError("WordDocument FIB is truncated")
+ ident, n_fib = struct.unpack_from("<HH", word_document, 0)
+ if ident != FIB_IDENT:
+ raise LegacyOfficeMalformedError("WordDocument FIB magic is invalid")
+ if n_fib < MIN_WORD97_NFIB:
+ raise LegacyOfficeMalformedError(f"Word 95 or earlier nFib is unsupported: 0x{n_fib:04X}")
+ lid = int(struct.unpack_from("<H", word_document, 6)[0])
+ flags = int(struct.unpack_from("<H", word_document, 10)[0])
+ fc_min = int(struct.unpack_from("<I", word_document, 24)[0])
+ fc_mac = int(struct.unpack_from("<I", word_document, 28)[0])
+ base = FibBase(n_fib=n_fib, lid=lid, flags=flags, fc_min=fc_min, fc_mac=fc_mac)
+
+ cursor = 32
+ csw = int(struct.unpack_from("<H", word_document, cursor)[0])
+ cursor += 2
+ rgw, cursor = _read_values(word_document, cursor, csw, 2, "FibRgW")
+ if cursor + 2 > len(word_document):
+ raise LegacyOfficeMalformedError("truncated FIB cslw")
+ cslw = int(struct.unpack_from("<H", word_document, cursor)[0])
+ cursor += 2
+ rglw, cursor = _read_values(word_document, cursor, cslw, 4, "FibRgLw")
+ if cursor + 2 > len(word_document):
+ raise LegacyOfficeMalformedError("truncated FIB cbRgFcLcb")
+ pair_count = int(struct.unpack_from("<H", word_document, cursor)[0])
+ cursor += 2
+ raw_pairs, cursor = _read_values(word_document, cursor, pair_count * 2, 4, "FibRgFcLcb")
+ pairs = tuple(FcLcb(raw_pairs[index], raw_pairs[index + 1]) for index in range(0, len(raw_pairs), 2))
+
+ csw_new: tuple[int, ...] = ()
+ if cursor + 2 <= len(word_document):
+ count = int(struct.unpack_from("<H", word_document, cursor)[0])
+ cursor += 2
+ csw_new, cursor = _read_values(word_document, cursor, count, 2, "FibRgCswNew")
+ if len(rglw) <= 3:
+ # 确定性最小 fixture 可能省略变长计数,但仍保留 Word 97 固定槽位;
+ # 仅在标准布局不可用时按这些公开槽位做恢复读取。
+ if len(word_document) < 0x6C:
+ raise LegacyOfficeMalformedError("FIB does not contain ccpText")
+ rglw = tuple(
+ int(struct.unpack_from("<I", word_document, 0x40 + index * 4)[0])
+ for index in range(11)
+ )
+ if not pairs and len(word_document) >= 0x382:
+ pairs = tuple(
+ FcLcb(*struct.unpack_from("<II", word_document, 0x9A + index * 8))
+ for index in range(93)
+ )
+ cursor = max(cursor, 0x382)
+ fib = FileInformationBlock(base=base, rgw=rgw, rglw=rglw, pairs=pairs, csw_new=csw_new, size=cursor)
+ if fib.total_story_cp < fib.ccp_text:
+ raise LegacyOfficeMalformedError("FIB story CP count overflow")
+ return fib
diff --git a/mineru/model/flash/doc/fields.py b/mineru/model/flash/doc/fields.py
new file mode 100644
index 00000000..01183a71
--- /dev/null
+++ b/mineru/model/flash/doc/fields.py
@@ -0,0 +1,109 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""解析 DOC 字段指令并安全恢复超链接、目录和 caption 语义。"""
+
+from __future__ import annotations
+
+import re
+from urllib.parse import urlparse
+
+from loguru import logger
+
+from .models import DocTextRun
+
+_TOKEN_RE = re.compile(r'"(?:\\.|[^"\\])*"|\\\S|\S+')
+_DRIVE_PATH_RE = re.compile(r"^[A-Za-z]:[\\/]")
+
+
+def field_keyword(instruction: str) -> str:
+ """返回字段指令的首个关键字大写形式。"""
+
+ tokens = _TOKEN_RE.findall(instruction.strip())
+ return tokens[0].strip('"').upper() if tokens else ""
+
+
+def is_toc_field(instruction: str) -> bool:
+ """判断字段是否为多段落 TOC。"""
+
+ return field_keyword(instruction) == "TOC"
+
+
+def is_caption_field(instruction: str) -> bool:
+ """判断字段是否为 Word SEQ caption 编号。"""
+
+ return field_keyword(instruction) == "SEQ"
+
+
+def _unquote(token: str) -> str:
+ """解码字段引号内允许的反斜杠转义。"""
+
+ if len(token) >= 2 and token[0] == token[-1] == '"':
+ token = token[1:-1]
+ return token.replace(r'\"', '"').replace(r"\\", "\\")
+
+
+def sanitize_hyperlink_target(target: str) -> str | None:
+ """仅保留网络、内部 fragment 和非本地安全相对链接。"""
+
+ candidate = target.strip()
+ if not candidate:
+ return None
+ lowered = candidate.casefold()
+ if lowered.startswith(("javascript:", "data:", "vbscript:", "file:")):
+ return None
+ if candidate.startswith(("\\\\", "//", "/")) or _DRIVE_PATH_RE.match(candidate):
+ 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 hyperlink_target(instruction: str) -> str | None:
+ """从 HYPERLINK 字段读取 URL 与可选内部书签。"""
+
+ tokens = _TOKEN_RE.findall(instruction.strip())
+ if not tokens or _unquote(tokens[0]).casefold() != "hyperlink":
+ return None
+ url: str | None = None
+ anchor: str | None = None
+ index = 1
+ while index < len(tokens):
+ token = tokens[index]
+ if token.startswith("\\"):
+ switch = token[1:].casefold()
+ argument: str | None = None
+ if switch in {"l", "o", "t"} and index + 1 < len(tokens) and not tokens[index + 1].startswith("\\"):
+ index += 1
+ argument = _unquote(tokens[index]).strip()
+ if switch == "l" and argument:
+ anchor = argument
+ elif url is None:
+ url = _unquote(token).strip()
+ index += 1
+ if url and anchor:
+ candidate = f"{url}#{anchor}"
+ elif url:
+ candidate = url
+ elif anchor:
+ candidate = f"#{anchor}"
+ else:
+ return None
+ safe = sanitize_hyperlink_target(candidate)
+ if safe is None:
+ logger.warning(f"DOC hyperlink target was rejected: {candidate!r}")
+ return safe
+
+
+def apply_field_result(instruction: str, runs: list[DocTextRun]) -> list[DocTextRun]:
+ """把 HYPERLINK 目标绑定到字段结果,其他字段仅保留缓存结果。"""
+
+ if field_keyword(instruction) != "HYPERLINK":
+ return runs
+ target = hyperlink_target(instruction)
+ if target is None:
+ return runs
+ return [DocTextRun(run.text, run.style, target) for run in runs]
+
diff --git a/mineru/model/flash/doc/formatting.py b/mineru/model/flash/doc/formatting.py
new file mode 100644
index 00000000..aff94b7f
--- /dev/null
+++ b/mineru/model/flash/doc/formatting.py
@@ -0,0 +1,173 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""解析 Word CHPX/PAPX FKP 页面并提供按 FC 查询的格式 run。"""
+
+from __future__ import annotations
+
+from bisect import bisect_right
+from dataclasses import dataclass
+
+from loguru import logger
+
+from .records import DocBudget, bounded_slice, get_u32
+from .sprm import PapDelta, apply_paragraph_sprms
+
+
+@dataclass(frozen=True, slots=True)
+class CharacterRun:
+ """一个物理 FC 范围内的原始 CHPX。"""
+
+ fc_start: int
+ fc_end: int
+ grpprl: bytes
+
+
+@dataclass(frozen=True, slots=True)
+class ParagraphRun:
+ """一个物理 FC 范围内的段落样式和 PAPX。"""
+
+ fc_start: int
+ fc_end: int
+ style_id: int
+ delta: PapDelta
+
+
+class FormattingRuns:
+ """按起始 FC 排序的 CHPX/PAPX 查询索引。"""
+
+ def __init__(self, characters: list[CharacterRun], paragraphs: list[ParagraphRun]) -> None:
+ """排序 run 并缓存二分查询键。"""
+
+ self.characters = sorted(characters, key=lambda run: run.fc_start)
+ self.paragraphs = sorted(paragraphs, key=lambda run: run.fc_start)
+ self._character_starts = [run.fc_start for run in self.characters]
+ self._paragraph_starts = [run.fc_start for run in self.paragraphs]
+
+ def character_at(self, fc: int) -> CharacterRun | None:
+ """返回覆盖指定 FC 的最后一个 CHPX run。"""
+
+ index = bisect_right(self._character_starts, fc) - 1
+ if index < 0:
+ return None
+ run = self.characters[index]
+ return run if fc < run.fc_end else None
+
+ def paragraph_at(self, fc: int) -> ParagraphRun | None:
+ """返回覆盖指定 FC 的最后一个 PAPX run。"""
+
+ index = bisect_right(self._paragraph_starts, fc) - 1
+ if index < 0:
+ return None
+ run = self.paragraphs[index]
+ return run if fc < run.fc_end else None
+
+
+def _parse_bte_pages(table_stream: bytes, offset: int, size: int) -> list[int]:
+ """从 PlcBteChpx/PlcBtePapx 读取 FKP page number。"""
+
+ plc = bounded_slice(table_stream, offset, size)
+ if plc is None or len(plc) < 8 or (len(plc) - 4) % 8:
+ return []
+ count = (len(plc) - 4) // 8
+ page_offset = (count + 1) * 4
+ pages: list[int] = []
+ for index in range(count):
+ raw = get_u32(plc, page_offset + index * 4)
+ if raw is not None:
+ pages.append(raw & 0x003F_FFFF)
+ return pages
+
+
+def _parse_chpx_page(page: bytes, budget: DocBudget) -> list[CharacterRun]:
+ """解析一个 512 字节 ChpxFkp。"""
+
+ count = page[511]
+ if count == 0 or (count + 1) * 4 + count > 511:
+ return []
+ result: list[CharacterRun] = []
+ offset_base = (count + 1) * 4
+ for index in range(count):
+ fc_start = get_u32(page, index * 4)
+ fc_end = get_u32(page, (index + 1) * 4)
+ if fc_start is None or fc_end is None or fc_end <= fc_start:
+ continue
+ byte_offset = page[offset_base + index]
+ grpprl = b""
+ if byte_offset:
+ payload_offset = byte_offset * 2
+ if payload_offset < 511:
+ length = page[payload_offset]
+ grpprl = page[payload_offset + 1 : payload_offset + 1 + length]
+ budget.charge()
+ result.append(CharacterRun(fc_start, fc_end, grpprl))
+ return result
+
+
+def _parse_papx_page(page: bytes, data_stream: bytes, budget: DocBudget) -> list[ParagraphRun]:
+ """解析一个 512 字节 PapxFkp。"""
+
+ count = page[511]
+ header_end = (count + 1) * 4 + count * 13
+ if count == 0 or header_end > 511:
+ return []
+ result: list[ParagraphRun] = []
+ bx_base = (count + 1) * 4
+ for index in range(count):
+ fc_start = get_u32(page, index * 4)
+ fc_end = get_u32(page, (index + 1) * 4)
+ if fc_start is None or fc_end is None or fc_end <= fc_start:
+ continue
+ byte_offset = page[bx_base + index * 13]
+ style_id = 0
+ delta = PapDelta()
+ if byte_offset:
+ payload_offset = byte_offset * 2
+ if payload_offset < 511:
+ first_length = page[payload_offset]
+ if first_length:
+ content_offset = payload_offset + 1
+ content_length = first_length * 2 - 1
+ elif payload_offset + 1 < 511:
+ content_offset = payload_offset + 2
+ content_length = page[payload_offset + 1] * 2
+ else:
+ content_offset = 511
+ content_length = 0
+ content = page[content_offset : min(content_offset + content_length, 511)]
+ if len(content) >= 2:
+ style_id = int.from_bytes(content[:2], "little")
+ delta = apply_paragraph_sprms(content[2:], data_stream, budget=budget)
+ budget.charge()
+ result.append(ParagraphRun(fc_start, fc_end, style_id, delta))
+ return result
+
+
+def parse_formatting_runs(
+ word_document: bytes,
+ table_stream: bytes,
+ data_stream: bytes,
+ *,
+ chpx_offset: int,
+ chpx_size: int,
+ papx_offset: int,
+ papx_size: int,
+ budget: DocBudget,
+) -> FormattingRuns:
+ """解析 FIB 指向的全部 CHPX/PAPX FKP;坏可选页仅告警跳过。"""
+
+ characters: list[CharacterRun] = []
+ paragraphs: list[ParagraphRun] = []
+ for page_number in _parse_bte_pages(table_stream, chpx_offset, chpx_size):
+ page = bounded_slice(word_document, page_number * 512, 512)
+ if page is None:
+ logger.warning(f"DOC ChpxFkp page is truncated: {page_number}")
+ continue
+ characters.extend(_parse_chpx_page(page, budget))
+ for page_number in _parse_bte_pages(table_stream, papx_offset, papx_size):
+ page = bounded_slice(word_document, page_number * 512, 512)
+ if page is None:
+ logger.warning(f"DOC PapxFkp page is truncated: {page_number}")
+ continue
+ paragraphs.extend(_parse_papx_page(page, data_stream, budget))
+ return FormattingRuns(characters, paragraphs)
+
diff --git a/mineru/model/flash/doc/images.py b/mineru/model/flash/doc/images.py
new file mode 100644
index 00000000..6cbe3e9b
--- /dev/null
+++ b/mineru/model/flash/doc/images.py
@@ -0,0 +1,145 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""从 DOC Data/PICF 与 Word OfficeArt drawing 中恢复图片。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+import hashlib
+
+from loguru import logger
+
+from mineru.model.flash.legacy_office import LegacyOfficeResourceLimitError
+from mineru.model.flash.legacy_office.limits import MAX_ASSET_TOTAL_BYTES
+from mineru.model.flash.legacy_office.officeart import (
+ OfficeImagePayload,
+ decode_bstore,
+ extract_word_shapes,
+ first_blip,
+ record_at,
+)
+
+from .models import DocImage, DocImagePayload
+from .records import DocBudget, bounded_slice, get_u16, get_u32, parse_plc
+
+
+@dataclass(slots=True)
+class ImageStore:
+ """按内容去重并限制 DOC 图片累计字节数。"""
+
+ total: int = 0
+ cache: dict[bytes, DocImagePayload] = field(default_factory=dict)
+
+ def add(self, payload: OfficeImagePayload) -> DocImagePayload:
+ """计入一张唯一图片并返回内部载荷。"""
+
+ digest = hashlib.sha256(payload.data).digest()
+ cached = self.cache.get(digest)
+ if cached is not None:
+ return cached
+ if self.total + len(payload.data) > MAX_ASSET_TOTAL_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ f"embedded assets exceed max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}"
+ )
+ converted = DocImagePayload(payload.data, payload.extension, payload.content_type)
+ self.total += len(payload.data)
+ self.cache[digest] = converted
+ return converted
+
+
+def inline_picture(
+ data_stream: bytes,
+ *,
+ offset: int,
+ store: ImageStore,
+ budget: DocBudget,
+) -> DocImagePayload | None:
+ """解析 sprmCPicLocation 指向的 PICFAndOfficeArtData。"""
+
+ total_length = get_u32(data_stream, offset)
+ header_length = get_u16(data_stream, offset + 4)
+ if total_length is None or header_length is None or total_length < header_length:
+ return None
+ picf = bounded_slice(data_stream, offset, total_length)
+ if picf is None:
+ logger.warning(f"DOC picture at Data offset {offset} is out of bounds")
+ return None
+ art = picf[min(header_length, len(picf)) :]
+ decoded = first_blip(art, charge=budget.charge)
+ if decoded is None:
+ # 少量旧文件把原始位图直接放在 PICF 尾部,按 magic 尽力保留。
+ signatures = (
+ (b"\x89PNG\r\n\x1a\n", "png", "image/png"),
+ (b"\xff\xd8\xff", "jpg", "image/jpeg"),
+ (b"GIF8", "gif", "image/gif"),
+ (b"BM", "bmp", "image/bmp"),
+ (b"II*\x00", "tiff", "image/tiff"),
+ (b"MM\x00*", "tiff", "image/tiff"),
+ )
+ for signature, extension, content_type in signatures:
+ position = art.find(signature)
+ if position >= 0:
+ decoded = OfficeImagePayload(art[position:], extension, content_type)
+ break
+ return store.add(decoded) if decoded is not None else None
+
+
+def floating_pictures(
+ table_stream: bytes,
+ *,
+ word_document: bytes,
+ shape_plc_offset: int,
+ shape_plc_size: int,
+ drawing_offset: int,
+ drawing_size: int,
+ store: ImageStore,
+ budget: DocBudget,
+) -> list[DocImage]:
+ """按 PlcfSpaMom anchor CP 将 floating shape 的 BStore 图片绑定到正文。"""
+
+ plc_payload = bounded_slice(table_stream, shape_plc_offset, shape_plc_size)
+ drawing = bounded_slice(table_stream, drawing_offset, drawing_size)
+ if plc_payload is None or drawing is None:
+ return []
+ cps, items = parse_plc(plc_payload, item_size=26, budget=budget)
+ if not items:
+ return []
+ assets = decode_bstore(
+ drawing,
+ charge=budget.charge,
+ delay_stream=word_document,
+ )
+ shapes = {}
+ first = record_at(drawing, 0, charge=budget.charge)
+ cursor = (8 + len(first.payload)) if first is not None else len(drawing)
+ while cursor < len(drawing):
+ # OfficeArtWordDrawing 在 DgContainer 前有一个 main/header 标签字节。
+ cursor += 1
+ container = record_at(drawing, cursor, charge=budget.charge)
+ if container is None:
+ break
+ for shape in extract_word_shapes(container.payload, charge=budget.charge):
+ if shape.shape_id is not None:
+ shapes.setdefault(shape.shape_id, shape)
+ cursor += 8 + len(container.payload)
+ anchors = [
+ (shape_id, cps[index])
+ for index, item in enumerate(items)
+ if index < len(cps) and (shape_id := get_u32(item, 0)) is not None
+ ]
+ images: list[DocImage] = []
+ for shape_id, shape in sorted(shapes.items()):
+ if shape.hidden or shape.pib is None:
+ continue
+ payload = assets.get(shape.pib)
+ if payload is None:
+ continue
+ anchor_cp = next((cp for anchor_id, cp in anchors if anchor_id == shape_id), None)
+ if anchor_cp is None:
+ candidates = [(anchor_id, cp) for anchor_id, cp in anchors if anchor_id <= shape_id]
+ if candidates:
+ anchor_cp = max(candidates)[1]
+ if anchor_cp is None:
+ continue
+ images.append(DocImage(cp=anchor_cp, payload=store.add(payload)))
+ return images
diff --git a/mineru/model/flash/doc/lists.py b/mineru/model/flash/doc/lists.py
new file mode 100644
index 00000000..1db1ab97
--- /dev/null
+++ b/mineru/model/flash/doc/lists.py
@@ -0,0 +1,358 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""解析 Word PlfLst/PlfLfo 并维护九级列表编号状态。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from .models import DocListInfo
+from .records import DocBudget, bounded_slice, get_u16, get_u32
+
+LEVELS = 9
+
+
+@dataclass(frozen=True, slots=True)
+class NumberToken:
+ """编号模板中的层级引用或普通文本。"""
+
+ level: int | None = None
+ text: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class LevelDefinition:
+ """一个 Word 列表层级的编号规则。"""
+
+ marker: str = "bullet"
+ start: int = 1
+ restart: int | None = None
+ tokens: tuple[NumberToken, ...] = ()
+
+
+@dataclass(frozen=True, slots=True)
+class ListDefinition:
+ """一个 LFO 解析后的完整列表定义。"""
+
+ lsid: int
+ levels: tuple[LevelDefinition, ...]
+ overrides: tuple[int | None, ...] = (None,) * LEVELS
+
+
+@dataclass(slots=True)
+class _ListCounter:
+ """同一 lsid 的多级编号运行状态。"""
+
+ values: list[int] = field(default_factory=lambda: [0] * LEVELS)
+ started: list[bool] = field(default_factory=lambda: [False] * LEVELS)
+
+
+class ListTables:
+ """按 ilfo 查询列表定义并生成逐段落可见编号。"""
+
+ def __init__(self, definitions: dict[int, ListDefinition] | None = None) -> None:
+ """初始化列表定义及空计数器。"""
+
+ self._definitions = definitions or {}
+ self._counters: dict[int, _ListCounter] = {}
+ self._override_used: set[tuple[int, int]] = set()
+
+ def paragraph_info(self, ilfo: int, level: int) -> DocListInfo | None:
+ """推进指定列表层级并返回当前段落的标签。"""
+
+ if ilfo in {0, 0xF801}:
+ return None
+ definition = self._definitions.get(ilfo)
+ if definition is None:
+ fallback_levels = tuple(LevelDefinition() for _ in range(LEVELS))
+ definition = ListDefinition(lsid=(0xFFFF_FFFF ^ ilfo), levels=fallback_levels)
+ level = min(max(level, 0), LEVELS - 1)
+ level_def = definition.levels[level]
+ if level_def.marker == "none":
+ return None
+ if level_def.marker == "bullet":
+ return DocListInfo(
+ identity=definition.lsid,
+ level=level,
+ ordered=False,
+ )
+ counter = self._counters.setdefault(definition.lsid, _ListCounter())
+ first_for_override = (ilfo, level) not in self._override_used
+ self._override_used.add((ilfo, level))
+ override = definition.overrides[level]
+ if first_for_override and override is not None:
+ value = override
+ elif counter.started[level]:
+ value = counter.values[level] + 1
+ else:
+ value = level_def.start
+ counter.values[level] = value
+ counter.started[level] = True
+ for deeper in range(level + 1, LEVELS):
+ restart = definition.levels[deeper].restart
+ if restart is None or level < restart:
+ counter.started[deeper] = False
+ return DocListInfo(
+ identity=definition.lsid,
+ level=level,
+ ordered=True,
+ start=value,
+ label=_render_label(definition, counter, level),
+ )
+
+
+def _roman(value: int) -> str:
+ """把正整数格式化为常用 Roman 编号。"""
+
+ if value <= 0:
+ return str(value)
+ pairs = (
+ (1000, "M"),
+ (900, "CM"),
+ (500, "D"),
+ (400, "CD"),
+ (100, "C"),
+ (90, "XC"),
+ (50, "L"),
+ (40, "XL"),
+ (10, "X"),
+ (9, "IX"),
+ (5, "V"),
+ (4, "IV"),
+ (1, "I"),
+ )
+ result: list[str] = []
+ remaining = value
+ for number, label in pairs:
+ while remaining >= number:
+ result.append(label)
+ remaining -= number
+ return "".join(result)
+
+
+def _alpha(value: int) -> str:
+ """把正整数格式化为 Excel 风格字母序号。"""
+
+ if value <= 0:
+ return str(value)
+ result: list[str] = []
+ remaining = value
+ while remaining:
+ remaining, digit = divmod(remaining - 1, 26)
+ result.append(chr(ord("A") + digit))
+ return "".join(reversed(result))
+
+
+def _format_marker(marker: str, value: int) -> str:
+ """按 Word nfc 对应的 marker 类型格式化整数。"""
+
+ if marker == "upper_roman":
+ return _roman(value)
+ if marker == "lower_roman":
+ return _roman(value).lower()
+ if marker == "upper_alpha":
+ return _alpha(value)
+ if marker == "lower_alpha":
+ return _alpha(value).lower()
+ return str(value)
+
+
+def _render_label(definition: ListDefinition, counter: _ListCounter, level: int) -> str:
+ """用当前各层编号替换 LVL 模板中的占位符。"""
+
+ level_def = definition.levels[level]
+ if not level_def.tokens:
+ return f"{_format_marker(level_def.marker, counter.values[level])}."
+ parts: list[str] = []
+ for token in level_def.tokens:
+ if token.level is None:
+ parts.append(token.text)
+ continue
+ source_level = min(max(token.level, 0), LEVELS - 1)
+ source = definition.levels[source_level]
+ value = counter.values[source_level] if counter.started[source_level] else source.start
+ parts.append(_format_marker(source.marker, value))
+ return "".join(parts).strip()
+
+
+def _marker_for_nfc(nfc: int) -> str:
+ """把常见 MS-OSHARED 编号格式映射为内部 marker。"""
+
+ return {
+ 0: "decimal",
+ 1: "upper_roman",
+ 2: "lower_roman",
+ 3: "upper_alpha",
+ 4: "lower_alpha",
+ 23: "bullet",
+ 0xFF: "none",
+ }.get(nfc, "decimal")
+
+
+def _parse_level(data: bytes, offset: int) -> tuple[LevelDefinition, int] | None:
+ """解析一个 LVL 及其 PAPX/CHPX 后的编号文本。"""
+
+ header = bounded_slice(data, offset, 28)
+ if header is None:
+ return None
+ start = get_u32(header, 0)
+ if start is None:
+ return None
+ nfc = header[4]
+ flags = header[5]
+ placeholder_offsets = [value for value in header[6:15] if value]
+ chpx_size = header[24]
+ papx_size = header[25]
+ restart_limit = header[26]
+ cursor = offset + 28 + papx_size + chpx_size
+ char_count = get_u16(data, cursor)
+ if char_count is None:
+ return None
+ cursor += 2
+ text_bytes = bounded_slice(data, cursor, char_count * 2)
+ if text_bytes is None:
+ return None
+ units = [get_u16(text_bytes, index * 2) or 0 for index in range(char_count)]
+ tokens: list[NumberToken] = []
+ marker = _marker_for_nfc(nfc)
+ if marker not in {"bullet", "none"}:
+ for index, unit in enumerate(units):
+ if unit <= 8 and index + 1 in placeholder_offsets:
+ tokens.append(NumberToken(level=unit))
+ elif unit >= 0x20:
+ char = chr(unit)
+ if tokens and tokens[-1].level is None:
+ tokens[-1] = NumberToken(text=tokens[-1].text + char)
+ else:
+ tokens.append(NumberToken(text=char))
+ restart = restart_limit if flags & 0x08 else None
+ return (
+ LevelDefinition(
+ marker=marker,
+ start=max(int(start), 0),
+ restart=restart,
+ tokens=tuple(tokens),
+ ),
+ cursor + char_count * 2,
+ )
+
+
+def _parse_list_definitions(
+ table_stream: bytes,
+ *,
+ offset: int,
+ size: int,
+ budget: DocBudget,
+) -> dict[int, tuple[LevelDefinition, ...]]:
+ """解析 PlfLst 的 LSTF 数组及后续 LVL。"""
+
+ data = table_stream[offset:] if 0 <= offset < len(table_stream) else b""
+ count = get_u16(data, 0)
+ if count is None or size < 2 + count * 28:
+ return {}
+ cursor = 2
+ descriptors: list[tuple[int, bool]] = []
+ for _ in range(count):
+ record = bounded_slice(data, cursor, 28)
+ if record is None:
+ return {}
+ lsid = get_u32(record, 0)
+ if lsid is None:
+ return {}
+ descriptors.append((lsid, bool(record[26] & 1)))
+ cursor += 28
+ budget.charge()
+ cursor = size
+ result: dict[int, tuple[LevelDefinition, ...]] = {}
+ for lsid, simple in descriptors:
+ count_levels = 1 if simple else LEVELS
+ levels: list[LevelDefinition] = []
+ for _ in range(count_levels):
+ parsed = _parse_level(data, cursor)
+ if parsed is None:
+ return result
+ level, cursor = parsed
+ levels.append(level)
+ budget.charge()
+ if simple:
+ levels = [levels[0]] * LEVELS
+ while len(levels) < LEVELS:
+ levels.append(LevelDefinition())
+ result[lsid] = tuple(levels)
+ return result
+
+
+def parse_list_tables(
+ table_stream: bytes,
+ *,
+ list_offset: int,
+ list_size: int,
+ override_offset: int,
+ override_size: int,
+ budget: DocBudget,
+) -> ListTables:
+ """解析 PlfLst/PlfLfo 并建立一基 ilfo 查找表。"""
+
+ by_lsid = _parse_list_definitions(
+ table_stream,
+ offset=list_offset,
+ size=list_size,
+ budget=budget,
+ )
+ data = bounded_slice(table_stream, override_offset, override_size)
+ if data is None or len(data) < 4:
+ return ListTables()
+ count = get_u32(data, 0)
+ if count is None or 4 + count * 16 > len(data):
+ return ListTables()
+ cursor = 4
+ descriptors: list[tuple[int, int]] = []
+ for _ in range(count):
+ record = bounded_slice(data, cursor, 16)
+ if record is None:
+ return ListTables()
+ lsid = get_u32(record, 0)
+ if lsid is None:
+ return ListTables()
+ descriptors.append((lsid, record[12]))
+ cursor += 16
+ budget.charge()
+ definitions: dict[int, ListDefinition] = {}
+ for index, (lsid, override_count) in enumerate(descriptors, start=1):
+ levels = list(by_lsid.get(lsid, tuple(LevelDefinition() for _ in range(LEVELS))))
+ overrides: list[int | None] = [None] * LEVELS
+ for _ in range(override_count):
+ record = bounded_slice(data, cursor, 8)
+ if record is None:
+ break
+ start = get_u32(record, 0) or 0
+ bits = record[4]
+ level_index = bits & 0x0F
+ has_start = bool(bits & 0x10)
+ has_format = bool(bits & 0x20)
+ cursor += 8
+ budget.charge()
+ if has_format:
+ parsed = _parse_level(data, cursor)
+ if parsed is None:
+ break
+ level_def, cursor = parsed
+ if level_index < LEVELS:
+ levels[level_index] = level_def
+ if has_start:
+ overrides[level_index] = level_def.start
+ elif has_start and level_index < LEVELS:
+ levels[level_index] = LevelDefinition(
+ marker=levels[level_index].marker,
+ start=int(start),
+ restart=levels[level_index].restart,
+ tokens=levels[level_index].tokens,
+ )
+ overrides[level_index] = int(start)
+ definitions[index] = ListDefinition(
+ lsid=lsid,
+ levels=tuple(levels),
+ overrides=tuple(overrides),
+ )
+ return ListTables(definitions)
+
diff --git a/mineru/model/flash/doc/models.py b/mineru/model/flash/doc/models.py
new file mode 100644
index 00000000..c0da6018
--- /dev/null
+++ b/mineru/model/flash/doc/models.py
@@ -0,0 +1,152 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""Word 二进制解析器与 Converter 之间的内部语义模型。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import TypeAlias
+
+
+@dataclass(frozen=True, slots=True)
+class DocCharStyle:
+ """一个连续 DOC 文字 run 的可见字符样式。"""
+
+ bold: bool = False
+ italic: bool = False
+ underline: bool = False
+ emphasis: bool = False
+ strike: bool = False
+ superscript: bool = False
+ subscript: bool = False
+ hidden: bool = False
+ deleted: bool = False
+
+
+@dataclass(frozen=True, slots=True)
+class DocTextRun:
+ """一段样式及超链接目标相同的可见文字。"""
+
+ text: str
+ style: DocCharStyle = DocCharStyle()
+ hyperlink: str | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class DocListInfo:
+ """段落从 PlfLst/PlfLfo 解析出的列表信息。"""
+
+ identity: int
+ level: int
+ ordered: bool
+ start: int = 1
+ label: str | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class DocTableCellFormat:
+ """一格 Word 表格在行定义中的合并属性。"""
+
+ right: int
+ horizontal_first: bool = False
+ horizontal_continue: bool = False
+ vertical_first: bool = False
+ vertical_continue: bool = False
+
+
+@dataclass(frozen=True, slots=True)
+class DocTableFormat:
+ """一个 TTP 段落解析出的表格行定义。"""
+
+ boundaries: tuple[int, ...] = ()
+ cells: tuple[DocTableCellFormat, ...] = ()
+ header: bool = False
+
+
+@dataclass(slots=True)
+class DocParagraph:
+ """完成样式、字段和段落属性解析的段落。"""
+
+ cp_start: int
+ cp_end: int
+ runs: list[DocTextRun] = field(default_factory=list)
+ images: list[DocImagePayload] = field(default_factory=list)
+ style_name: str = ""
+ heading_level: int | None = None
+ is_title: bool = False
+ is_toc: bool = False
+ toc_level: int | None = None
+ is_caption: bool = False
+ is_code: bool = False
+ anchor: str | None = None
+ list_info: DocListInfo | None = None
+ in_table: bool = False
+ table_depth: int = 0
+ cell_mark: bool = False
+ row_mark: bool = False
+ table_format: DocTableFormat | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class DocImagePayload:
+ """一张从 PICF/OfficeArt 恢复的图片原始载荷。"""
+
+ data: bytes
+ extension: str
+ content_type: str
+
+
+@dataclass(slots=True)
+class DocImage:
+ """按主 story CP 定位的内联或浮动图片。"""
+
+ cp: int
+ payload: DocImagePayload
+
+
+@dataclass(slots=True)
+class DocTableCell:
+ """Word 表格单元格及其嵌套内容。"""
+
+ blocks: list[DocElement] = field(default_factory=list)
+ row_span: int = 1
+ col_span: int = 1
+
+
+@dataclass(slots=True)
+class DocTableRow:
+ """Word 表格的一行。"""
+
+ cells: list[DocTableCell] = field(default_factory=list)
+ header: bool = False
+
+
+@dataclass(slots=True)
+class DocTable:
+ """按 CP 顺序组装出的普通或嵌套表格。"""
+
+ cp_start: int
+ cp_end: int
+ rows: list[DocTableRow] = field(default_factory=list)
+
+
+DocElement: TypeAlias = DocParagraph | DocImage | DocTable
+
+
+@dataclass(slots=True)
+class DocSection:
+ """一个 Word section 及其页面辅助文本。"""
+
+ cp_start: int
+ cp_end: int
+ elements: list[DocElement] = field(default_factory=list)
+ headers: list[DocParagraph] = field(default_factory=list)
+ footers: list[DocParagraph] = field(default_factory=list)
+ footnotes: list[DocParagraph] = field(default_factory=list)
+
+
+@dataclass(slots=True)
+class DocDocument:
+ """一份可投影为 model-list 的 DOC 文档。"""
+
+ sections: list[DocSection] = field(default_factory=list)
diff --git a/mineru/model/flash/doc/parser.py b/mineru/model/flash/doc/parser.py
new file mode 100644
index 00000000..2976fc78
--- /dev/null
+++ b/mineru/model/flash/doc/parser.py
@@ -0,0 +1,806 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""把 WordDocument/Table/Data streams 解析为逐 section DOC 语义模型。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from loguru import logger
+
+from mineru.model.flash.legacy_office import LegacyOfficeMalformedError
+
+from .bookmarks import parse_bookmarks
+from .fib import (
+ FCLCB_BOOKMARK_END,
+ FCLCB_BOOKMARK_NAMES,
+ FCLCB_BOOKMARK_START,
+ FCLCB_BTE_CHPX,
+ FCLCB_BTE_PAPX,
+ FCLCB_CLX,
+ FCLCB_DGG_INFO,
+ FCLCB_ENDNOTE_REF,
+ FCLCB_ENDNOTE_TEXT,
+ FCLCB_FOOTNOTE_REF,
+ FCLCB_FOOTNOTE_TEXT,
+ FCLCB_HEADER,
+ FCLCB_LIST_OVERRIDES,
+ FCLCB_LISTS,
+ FCLCB_SECTION,
+ FCLCB_SHAPE_MAIN,
+ FCLCB_STSHF,
+ FileInformationBlock,
+)
+from .fields import apply_field_result, field_keyword, is_toc_field
+from .formatting import FormattingRuns, parse_formatting_runs
+from .images import ImageStore, floating_pictures, inline_picture
+from .lists import ListTables, parse_list_tables
+from .models import (
+ DocCharStyle,
+ DocDocument,
+ DocElement,
+ DocImage,
+ DocParagraph,
+ DocSection,
+ DocTable,
+ DocTableCell,
+ DocTableCellFormat,
+ DocTableFormat,
+ DocTableRow,
+ DocTextRun,
+)
+from .pieces import Piece, TextStream, codec_for_lid, extract_text, legacy_single_piece, parse_clx
+from .records import DocBudget, bounded_slice, parse_plc
+from .sprm import (
+ PapDelta,
+ apply_character_sprms,
+ apply_paragraph_sprms,
+ chpx_picture_location,
+ chpx_style_id,
+)
+from .styles import Stylesheet, parse_stylesheet
+
+
+@dataclass(slots=True)
+class _FieldFrame:
+ """一个尚未闭合的 Word 字段。"""
+
+ instruction: str = ""
+ in_result: bool = False
+ transparent: bool = False
+ runs: list[DocTextRun] = field(default_factory=list)
+
+
+@dataclass(slots=True)
+class _RawTableRow:
+ """应用全表网格前的一行单元格。"""
+
+ cells: list[DocTableCell]
+ table_format: DocTableFormat | None
+
+
+class _Assembler:
+ """把全局文字流、格式 run 和辅助 PLC 组装为段落及表格。"""
+
+ def __init__(
+ self,
+ *,
+ text: TextStream,
+ pieces: list[Piece],
+ formatting: FormattingRuns,
+ stylesheet: Stylesheet,
+ lists: ListTables,
+ bookmarks: dict[int, list[str]],
+ data_stream: bytes,
+ image_store: ImageStore,
+ budget: DocBudget,
+ ) -> None:
+ """保存解析上下文;每个 story 开始时会重置字段栈。"""
+
+ self.text = text
+ self.pieces = pieces
+ self.formatting = formatting
+ self.stylesheet = stylesheet
+ self.lists = lists
+ self.bookmarks = bookmarks
+ self.data_stream = data_stream
+ self.image_store = image_store
+ self.budget = budget
+ self._fields: list[_FieldFrame] = []
+
+ def _piece_prm(self, char_index: int) -> bytes:
+ """返回字符所在 piece 的 Prm grpprl。"""
+
+ if char_index >= len(self.text.piece_indexes):
+ return b""
+ piece_index = self.text.piece_indexes[char_index]
+ return self.pieces[piece_index].prm if piece_index < len(self.pieces) else b""
+
+ def _character_style(self, fc: int, char_index: int) -> DocCharStyle:
+ """按样式链、CHPX、piece Prm 顺序解析字符样式。"""
+
+ paragraph_run = self.formatting.paragraph_at(fc)
+ paragraph_style_id = paragraph_run.style_id if paragraph_run is not None else 0
+ character_run = self.formatting.character_at(fc)
+ grpprl = character_run.grpprl if character_run is not None else b""
+ style_id = chpx_style_id(grpprl)
+ if style_id is None:
+ style_id = paragraph_style_id
+ base = self.stylesheet.get(style_id).character
+ result = apply_character_sprms(grpprl, base, base, budget=self.budget)
+ prm = self._piece_prm(char_index)
+ if prm:
+ result = apply_character_sprms(prm, result, base, budget=self.budget)
+ return result
+
+ def _paragraph_properties(self, fc: int, char_index: int) -> tuple[int, PapDelta]:
+ """按样式链、PAPX、piece Prm 顺序解析段落属性。"""
+
+ paragraph_run = self.formatting.paragraph_at(fc)
+ style_id = paragraph_run.style_id if paragraph_run is not None else 0
+ style = self.stylesheet.get(style_id)
+ delta = style.paragraph
+ if paragraph_run is not None:
+ delta = delta.merge(paragraph_run.delta)
+ prm = self._piece_prm(char_index)
+ if prm:
+ delta = apply_paragraph_sprms(prm, b"", delta, budget=self.budget)
+ return style_id, delta
+
+ @staticmethod
+ def _append_run(target: list[DocTextRun], run: DocTextRun) -> None:
+ """合并相邻同样式同链接 run。"""
+
+ if not run.text:
+ return
+ if target and target[-1].style == run.style and target[-1].hyperlink == run.hyperlink:
+ previous = target[-1]
+ target[-1] = DocTextRun(previous.text + run.text, previous.style, previous.hyperlink)
+ else:
+ target.append(run)
+
+ def _push_visible_run(self, visible: list[DocTextRun], run: DocTextRun) -> None:
+ """把一个结果 run 送入当前字段或段落。"""
+
+ if not self._fields:
+ self._append_run(visible, run)
+ return
+ frame = self._fields[-1]
+ if not frame.in_result:
+ frame.instruction += run.text
+ elif frame.transparent:
+ self._append_run(visible, run)
+ else:
+ self._append_run(frame.runs, run)
+
+ def _field_begin(self) -> None:
+ """打开一个嵌套字段。"""
+
+ self._fields.append(_FieldFrame())
+
+ def _field_separator(self, paragraph_keywords: set[str]) -> None:
+ """结束字段指令并识别跨段 TOC。"""
+
+ if not self._fields:
+ return
+ frame = self._fields[-1]
+ frame.in_result = True
+ keyword = field_keyword(frame.instruction)
+ if keyword:
+ paragraph_keywords.add(keyword)
+ frame.transparent = is_toc_field(frame.instruction)
+
+ def _field_end(self, visible: list[DocTextRun], paragraph_keywords: set[str]) -> None:
+ """关闭字段,把缓存结果绑定链接后放回父上下文。"""
+
+ if not self._fields:
+ return
+ frame = self._fields.pop()
+ keyword = field_keyword(frame.instruction)
+ if keyword:
+ paragraph_keywords.add(keyword)
+ if frame.transparent:
+ return
+ for run in apply_field_result(frame.instruction, frame.runs):
+ self._push_visible_run(visible, run)
+
+ def _paragraph_anchor(self, cp_start: int, cp_end: int) -> str | None:
+ """返回段落范围内优先级最高的书签起点。"""
+
+ candidates = [
+ name
+ for cp, names in self.bookmarks.items()
+ if cp_start <= cp < cp_end
+ for name in names
+ ]
+ if not candidates:
+ return None
+ return next((name for name in candidates if name.startswith("_Toc")), candidates[0])
+
+ def _finish_paragraph(
+ self,
+ *,
+ cp_start: int,
+ cp_end: int,
+ char_index: int,
+ fc: int,
+ terminator: str,
+ runs: list[DocTextRun],
+ images: list,
+ keywords: set[str],
+ ) -> DocParagraph | None:
+ """把段落终止字符上的 PAPX 解析为完整语义段落。"""
+
+ style_id, pap = self._paragraph_properties(fc, char_index)
+ style = self.stylesheet.get(style_id)
+ cell_mark = terminator == "\x07" or bool(pap.inner_cell)
+ row_mark = bool(pap.row_mark) or bool(pap.inner_row)
+ in_table = bool(pap.in_table) or cell_mark or row_mark
+ visible = any(run.text for run in runs) or bool(images)
+ if not visible and not in_table:
+ return None
+ list_info = None
+ if pap.ilfo is not None:
+ list_info = self.lists.paragraph_info(pap.ilfo, pap.ilvl or 0)
+ outline = pap.outline_level if isinstance(pap.outline_level, int) and pap.outline_level > 0 else None
+ toc_level = style.toc_level
+ toc_active = toc_level is not None or any(frame.transparent for frame in self._fields)
+ return DocParagraph(
+ cp_start=cp_start,
+ cp_end=cp_end,
+ runs=runs,
+ images=images,
+ style_name=style.name,
+ heading_level=style.heading_level or outline,
+ is_title=style.is_title,
+ is_toc=toc_active,
+ toc_level=toc_level,
+ is_caption=any(keyword == "SEQ" for keyword in keywords),
+ is_code=style.is_code,
+ anchor=self._paragraph_anchor(cp_start, cp_end),
+ list_info=list_info,
+ in_table=in_table,
+ table_depth=max(pap.table_depth or (1 if in_table else 0), 0),
+ cell_mark=cell_mark,
+ row_mark=row_mark,
+ table_format=pap.table,
+ )
+
+ def paragraphs(
+ self,
+ cp_start: int,
+ cp_end: int,
+ *,
+ note_refs: dict[int, str] | None = None,
+ ) -> list[DocParagraph]:
+ """解析一个 story CP 范围内的全部段落。"""
+
+ self._fields = []
+ refs = note_refs or {}
+ start_index = self.text.index_of_cp(cp_start)
+ end_index = self.text.index_of_cp(cp_end)
+ paragraphs: list[DocParagraph] = []
+ visible: list[DocTextRun] = []
+ images: list = []
+ keywords: set[str] = set()
+ paragraph_start = cp_start
+ for char_index in range(start_index, min(end_index, len(self.text.chars))):
+ char = self.text.chars[char_index]
+ cp = self.text.cps[char_index]
+ fc = self.text.fcs[char_index]
+ if char == "\x13":
+ self._field_begin()
+ continue
+ if char == "\x14":
+ self._field_separator(keywords)
+ continue
+ if char == "\x15":
+ self._field_end(visible, keywords)
+ continue
+ if cp in refs:
+ self._push_visible_run(
+ visible,
+ DocTextRun(f"[{refs[cp]}]", DocCharStyle(superscript=True)),
+ )
+ continue
+ if char in {"\r", "\x07", "\x0c", "\x0e"}:
+ paragraph = self._finish_paragraph(
+ cp_start=paragraph_start,
+ cp_end=cp + 1,
+ char_index=char_index,
+ fc=fc,
+ terminator=char,
+ runs=visible,
+ images=images,
+ keywords=keywords,
+ )
+ if paragraph is not None:
+ paragraphs.append(paragraph)
+ visible = []
+ images = []
+ keywords = set()
+ paragraph_start = cp + 1
+ continue
+ if char == "\x01":
+ character_run = self.formatting.character_at(fc)
+ location = chpx_picture_location(character_run.grpprl) if character_run is not None else None
+ if location is not None:
+ payload = inline_picture(
+ self.data_stream,
+ offset=location,
+ store=self.image_store,
+ budget=self.budget,
+ )
+ if payload is not None:
+ if all(existing is not payload for existing in images):
+ images.append(payload)
+ continue
+ if char == "\x0b":
+ char = "\n"
+ elif char == "\t":
+ char = "\t"
+ elif char == "\x1e":
+ char = "-"
+ elif ord(char) < 0x20:
+ continue
+ style = self._character_style(fc, char_index)
+ if self._fields and not self._fields[-1].in_result:
+ self._push_visible_run(visible, DocTextRun(char, style))
+ elif not style.hidden and not style.deleted:
+ self._push_visible_run(visible, DocTextRun(char, style))
+ if visible or images:
+ last_index = max(start_index, min(end_index, len(self.text.chars)) - 1)
+ if last_index < len(self.text.chars):
+ paragraph = self._finish_paragraph(
+ cp_start=paragraph_start,
+ cp_end=cp_end,
+ char_index=last_index,
+ fc=self.text.fcs[last_index],
+ terminator="",
+ runs=visible,
+ images=images,
+ keywords=keywords,
+ )
+ if paragraph is not None:
+ paragraphs.append(paragraph)
+ return paragraphs
+
+
+def _paragraph_visible(paragraph: DocParagraph) -> bool:
+ """判断表格标记段落是否含有实际单元格内容。"""
+
+ return any(run.text for run in paragraph.runs) or bool(paragraph.images)
+
+
+def _cell_formats(row: _RawTableRow) -> tuple[list[int], list[DocTableCellFormat]]:
+ """为缺失 TAP 的行构造稳定伪边界和默认 cell 属性。"""
+
+ count = len(row.cells)
+ table_format = row.table_format
+ if table_format is not None and len(table_format.boundaries) >= count + 1:
+ boundaries = list(table_format.boundaries[: count + 1])
+ formats = list(table_format.cells[:count])
+ while len(formats) < count:
+ formats.append(DocTableCellFormat(right=boundaries[len(formats) + 1]))
+ return boundaries, formats
+ boundaries = list(range(count + 1))
+ return boundaries, [DocTableCellFormat(right=index + 1) for index in range(count)]
+
+
+def _materialize_table_rows(raw_rows: list[_RawTableRow], budget: DocBudget) -> list[DocTableRow]:
+ """把各行独立 twip 边界统一为 rowspan/colspan HTML 网格。"""
+
+ all_boundaries: set[int] = set()
+ row_formats: list[tuple[list[int], list[DocTableCellFormat]]] = []
+ for row in raw_rows:
+ boundaries, formats = _cell_formats(row)
+ row_formats.append((boundaries, formats))
+ all_boundaries.update(boundaries)
+ edges = sorted(all_boundaries)
+ edge_index = {value: index for index, value in enumerate(edges)}
+ vertical_origins: dict[tuple[int, int], DocTableCell] = {}
+ rows: list[DocTableRow] = []
+ for raw_row, (boundaries, formats) in zip(raw_rows, row_formats, strict=True):
+ cells: list[DocTableCell] = []
+ keys: list[tuple[int, int]] = []
+ index = 0
+ while index < len(raw_row.cells):
+ source = raw_row.cells[index]
+ cell_format = formats[index]
+ left = edge_index.get(boundaries[index], index)
+ right = edge_index.get(boundaries[index + 1], left + 1)
+ col_span = max(right - left, 1)
+ if cell_format.horizontal_continue and cells:
+ cells[-1].col_span += col_span
+ cells[-1].blocks.extend(source.blocks)
+ previous_left, _ = keys[-1]
+ keys[-1] = (previous_left, right)
+ index += 1
+ continue
+ cell = DocTableCell(blocks=source.blocks, col_span=col_span)
+ key = (left, right)
+ if cell_format.vertical_continue and key in vertical_origins:
+ vertical_origins[key].row_span += 1
+ else:
+ cells.append(cell)
+ keys.append(key)
+ if cell_format.vertical_first:
+ vertical_origins[key] = cell
+ index += 1
+ budget.charge(col_span)
+ rows.append(
+ DocTableRow(
+ cells=cells,
+ header=bool(raw_row.table_format and raw_row.table_format.header),
+ )
+ )
+ return rows
+
+
+def _parse_table(
+ paragraphs: list[DocParagraph],
+ start: int,
+ depth: int,
+ budget: DocBudget,
+) -> tuple[DocTable, int]:
+ """递归解析指定 table depth 的表格和嵌套表格。"""
+
+ index = start
+ cp_start = paragraphs[start].cp_start
+ cp_end = cp_start
+ raw_rows: list[_RawTableRow] = []
+ row_cells: list[DocTableCell] = []
+ current_blocks: list[DocElement] = []
+ while index < len(paragraphs):
+ paragraph = paragraphs[index]
+ if not paragraph.in_table or paragraph.table_depth < depth:
+ break
+ if paragraph.table_depth > depth:
+ nested, index = _parse_table(paragraphs, index, paragraph.table_depth, budget)
+ current_blocks.append(nested)
+ cp_end = max(cp_end, nested.cp_end)
+ continue
+ cp_end = max(cp_end, paragraph.cp_end)
+ if paragraph.row_mark:
+ if _paragraph_visible(paragraph):
+ current_blocks.append(paragraph)
+ if current_blocks:
+ row_cells.append(DocTableCell(blocks=current_blocks))
+ current_blocks = []
+ if row_cells:
+ raw_rows.append(_RawTableRow(row_cells, paragraph.table_format))
+ row_cells = []
+ elif paragraph.cell_mark:
+ if _paragraph_visible(paragraph):
+ current_blocks.append(paragraph)
+ row_cells.append(DocTableCell(blocks=current_blocks))
+ current_blocks = []
+ else:
+ current_blocks.append(paragraph)
+ index += 1
+ if current_blocks:
+ row_cells.append(DocTableCell(blocks=current_blocks))
+ if row_cells:
+ raw_rows.append(_RawTableRow(row_cells, None))
+ rows = _materialize_table_rows(raw_rows, budget)
+ return DocTable(cp_start=cp_start, cp_end=cp_end, rows=rows), index
+
+
+def _assemble_main_elements(
+ paragraphs: list[DocParagraph],
+ floating: list[DocImage],
+ budget: DocBudget,
+) -> list[DocElement]:
+ """把连续 table paragraph 收敛成表格,并按 CP 合入 floating 图片。"""
+
+ elements: list[DocElement] = []
+ index = 0
+ while index < len(paragraphs):
+ paragraph = paragraphs[index]
+ if paragraph.in_table and paragraph.table_depth > 0:
+ # DOC 可直接以 depth=2 的 inner-cell 开始;从 depth=1 建立隐式外层格。
+ table, index = _parse_table(paragraphs, index, 1, budget)
+ if table.rows:
+ elements.append(table)
+ continue
+ elements.append(paragraph)
+ index += 1
+ elements.extend(floating)
+ elements.sort(
+ key=lambda element: (
+ element.cp if isinstance(element, DocImage) else element.cp_start,
+ 1 if isinstance(element, DocImage) else 0,
+ )
+ )
+ return elements
+
+
+def _section_ranges(
+ table_stream: bytes,
+ fib: FileInformationBlock,
+ budget: DocBudget,
+) -> list[tuple[int, int]]:
+ """从 PlcfSed 恢复 section CP 范围,损坏时回退单 section。"""
+
+ pair = fib.pair(FCLCB_SECTION)
+ payload = bounded_slice(table_stream, pair.fc, pair.lcb)
+ if payload is None:
+ return [(0, fib.ccp_text)]
+ cps, items = parse_plc(payload, item_size=12, budget=budget)
+ if not items or len(cps) != len(items) + 1:
+ return [(0, fib.ccp_text)]
+ ranges: list[tuple[int, int]] = []
+ for start, end in zip(cps, cps[1:]):
+ if start > end or start > fib.ccp_text:
+ logger.warning("DOC PlcfSed CP values are invalid; using one recovery section")
+ return [(0, fib.ccp_text)]
+ ranges.append((start, min(end, fib.ccp_text)))
+ return ranges or [(0, fib.ccp_text)]
+
+
+def _distribute_sections(
+ ranges: list[tuple[int, int]],
+ elements: list[DocElement],
+) -> list[DocSection]:
+ """按元素起始 CP 将主文档内容绑定到 section。"""
+
+ sections = [DocSection(start, end) for start, end in ranges]
+ for element in elements:
+ cp = element.cp if isinstance(element, DocImage) else element.cp_start
+ target = sections[-1]
+ for section in sections:
+ if section.cp_start <= cp < section.cp_end or (
+ section is sections[-1] and cp == section.cp_end
+ ):
+ target = section
+ break
+ target.elements.append(element)
+ return sections
+
+
+def _header_story_ranges(
+ table_stream: bytes,
+ fib: FileInformationBlock,
+ budget: DocBudget,
+) -> list[tuple[int, int]]:
+ """返回 PlcfHdd 中相对于 header story 的范围。"""
+
+ pair = fib.pair(FCLCB_HEADER)
+ payload = bounded_slice(table_stream, pair.fc, pair.lcb)
+ if payload is None or len(payload) < 8 or len(payload) % 4:
+ return []
+ budget.charge(len(payload) // 4)
+ cps = [int.from_bytes(payload[index : index + 4], "little") for index in range(0, len(payload), 4)]
+ return [(start, end) for start, end in zip(cps, cps[1:]) if start <= end]
+
+
+def _attach_headers(
+ sections: list[DocSection],
+ assembler: _Assembler,
+ table_stream: bytes,
+ fib: FileInformationBlock,
+ budget: DocBudget,
+) -> None:
+ """把每节六种 header/footer story 的非空段落绑定到 section。"""
+
+ ranges = _header_story_ranges(table_stream, fib, budget)
+ base = fib.story_bases["header"]
+ for section_index, section in enumerate(sections):
+ group = 6 + section_index * 6
+ if group + 5 >= len(ranges):
+ break
+ for story_index in (0, 1, 4):
+ start, end = ranges[group + story_index]
+ section.headers.extend(assembler.paragraphs(base + start, base + end))
+ for story_index in (2, 3, 5):
+ start, end = ranges[group + story_index]
+ section.footers.extend(assembler.paragraphs(base + start, base + end))
+ inherited_header: DocParagraph | None = None
+ for section in sections:
+ if section.headers:
+ inherited_header = section.headers[0]
+ elif inherited_header is not None:
+ section.headers.append(inherited_header)
+
+
+def _note_ranges(
+ table_stream: bytes,
+ *,
+ ref_offset: int,
+ ref_size: int,
+ text_offset: int,
+ text_size: int,
+ story_base: int,
+ prefix: str,
+ budget: DocBudget,
+) -> tuple[dict[int, str], list[tuple[int, int, int, str]]]:
+ """解析脚注或尾注 reference CP 与正文 story 范围。"""
+
+ ref_payload = bounded_slice(table_stream, ref_offset, ref_size)
+ text_payload = bounded_slice(table_stream, text_offset, text_size)
+ if ref_payload is None or text_payload is None:
+ return {}, []
+ ref_cps, ref_items = parse_plc(ref_payload, item_size=2, budget=budget)
+ text_cps, _ = parse_plc(text_payload, item_size=0, budget=budget)
+ references: dict[int, str] = {}
+ ranges: list[tuple[int, int, int, str]] = []
+ for index, _item in enumerate(ref_items):
+ if index >= len(ref_cps) or index + 1 >= len(text_cps):
+ break
+ label = str(index + 1)
+ references[ref_cps[index]] = label
+ ranges.append(
+ (
+ ref_cps[index],
+ story_base + text_cps[index],
+ story_base + text_cps[index + 1],
+ f"{prefix}{label}",
+ )
+ )
+ return references, ranges
+
+
+def _prepend_note_label(paragraphs: list[DocParagraph], label: str) -> None:
+ """把脚注或尾注编号写入首个可见段落。"""
+
+ if not paragraphs:
+ return
+ paragraphs[0].runs.insert(0, DocTextRun(f"[{label.removeprefix('fn').removeprefix('en')}] "))
+
+
+def _attach_notes(
+ sections: list[DocSection],
+ assembler: _Assembler,
+ footnote_ranges: list[tuple[int, int, int, str]],
+ endnote_ranges: list[tuple[int, int, int, str]],
+) -> None:
+ """脚注按引用 section、尾注按最后 section 追加。"""
+
+ for reference_cp, start, end, label in footnote_ranges:
+ paragraphs = assembler.paragraphs(start, end)
+ _prepend_note_label(paragraphs, label)
+ target = sections[-1]
+ for section in sections:
+ if section.cp_start <= reference_cp < section.cp_end:
+ target = section
+ break
+ target.footnotes.extend(paragraphs)
+ for _reference_cp, start, end, label in endnote_ranges:
+ paragraphs = assembler.paragraphs(start, end)
+ _prepend_note_label(paragraphs, label)
+ sections[-1].footnotes.extend(paragraphs)
+
+
+def parse_doc_document(
+ word_document: bytes,
+ table_stream: bytes,
+ data_stream: bytes,
+ fib: FileInformationBlock,
+) -> DocDocument:
+ """解析三个核心 streams 并返回逐 section 语义文档。"""
+
+ budget = DocBudget()
+ clx = fib.pair(FCLCB_CLX)
+ if clx.lcb:
+ pieces = parse_clx(table_stream, offset=clx.fc, size=clx.lcb, budget=budget)
+ elif not fib.base.complex:
+ pieces = legacy_single_piece(
+ fc_min=fib.base.fc_min,
+ fc_mac=fib.base.fc_mac,
+ ccp_text=fib.ccp_text,
+ )
+ else:
+ raise LegacyOfficeMalformedError("complex DOC is missing its CLX piece table")
+ if not pieces and fib.total_story_cp:
+ raise LegacyOfficeMalformedError("DOC contains no recoverable text pieces")
+ lid = fib.base.lid
+ if fib.base.far_east:
+ lid_fe = int.from_bytes(word_document[0x3C:0x3E], "little") if len(word_document) >= 0x3E else 0
+ if lid_fe:
+ lid = lid_fe
+ elif len(fib.rgw) > 13 and fib.rgw[13]:
+ lid = fib.rgw[13]
+ text = extract_text(
+ word_document,
+ pieces,
+ total_cp=fib.total_story_cp,
+ codec=codec_for_lid(lid),
+ budget=budget,
+ )
+ stsh = fib.pair(FCLCB_STSHF)
+ stylesheet = parse_stylesheet(
+ table_stream,
+ offset=stsh.fc,
+ size=stsh.lcb,
+ budget=budget,
+ )
+ chpx = fib.pair(FCLCB_BTE_CHPX)
+ papx = fib.pair(FCLCB_BTE_PAPX)
+ formatting = parse_formatting_runs(
+ word_document,
+ table_stream,
+ data_stream,
+ chpx_offset=chpx.fc,
+ chpx_size=chpx.lcb,
+ papx_offset=papx.fc,
+ papx_size=papx.lcb,
+ budget=budget,
+ )
+ lists_pair = fib.pair(FCLCB_LISTS)
+ overrides_pair = fib.pair(FCLCB_LIST_OVERRIDES)
+ lists = parse_list_tables(
+ table_stream,
+ list_offset=lists_pair.fc,
+ list_size=lists_pair.lcb,
+ override_offset=overrides_pair.fc,
+ override_size=overrides_pair.lcb,
+ budget=budget,
+ )
+ names = fib.pair(FCLCB_BOOKMARK_NAMES)
+ starts = fib.pair(FCLCB_BOOKMARK_START)
+ ends = fib.pair(FCLCB_BOOKMARK_END)
+ bookmarks = parse_bookmarks(
+ table_stream,
+ names_offset=names.fc,
+ names_size=names.lcb,
+ starts_offset=starts.fc,
+ starts_size=starts.lcb,
+ ends_offset=ends.fc,
+ ends_size=ends.lcb,
+ budget=budget,
+ )
+ foot_ref = fib.pair(FCLCB_FOOTNOTE_REF)
+ foot_text = fib.pair(FCLCB_FOOTNOTE_TEXT)
+ foot_refs, foot_ranges = _note_ranges(
+ table_stream,
+ ref_offset=foot_ref.fc,
+ ref_size=foot_ref.lcb,
+ text_offset=foot_text.fc,
+ text_size=foot_text.lcb,
+ story_base=fib.story_bases["footnote"],
+ prefix="fn",
+ budget=budget,
+ )
+ end_ref = fib.pair(FCLCB_ENDNOTE_REF)
+ end_text = fib.pair(FCLCB_ENDNOTE_TEXT)
+ end_refs, end_ranges = _note_ranges(
+ table_stream,
+ ref_offset=end_ref.fc,
+ ref_size=end_ref.lcb,
+ text_offset=end_text.fc,
+ text_size=end_text.lcb,
+ story_base=fib.story_bases["endnote"],
+ prefix="en",
+ budget=budget,
+ )
+ note_refs = {**foot_refs, **end_refs}
+ store = ImageStore()
+ assembler = _Assembler(
+ text=text,
+ pieces=pieces,
+ formatting=formatting,
+ stylesheet=stylesheet,
+ lists=lists,
+ bookmarks=bookmarks,
+ data_stream=data_stream,
+ image_store=store,
+ budget=budget,
+ )
+ main_paragraphs = assembler.paragraphs(0, fib.ccp_text, note_refs=note_refs)
+ shape_pair = fib.pair(FCLCB_SHAPE_MAIN)
+ drawing_pair = fib.pair(FCLCB_DGG_INFO)
+ floating = floating_pictures(
+ table_stream,
+ word_document=word_document,
+ shape_plc_offset=shape_pair.fc,
+ shape_plc_size=shape_pair.lcb,
+ drawing_offset=drawing_pair.fc,
+ drawing_size=drawing_pair.lcb,
+ store=store,
+ budget=budget,
+ )
+ elements = _assemble_main_elements(main_paragraphs, floating, budget)
+ ranges = _section_ranges(table_stream, fib, budget)
+ sections = _distribute_sections(ranges, elements)
+ _attach_headers(sections, assembler, table_stream, fib, budget)
+ _attach_notes(sections, assembler, foot_ranges, end_ranges)
+ return DocDocument(sections=sections)
diff --git a/mineru/model/flash/doc/pieces.py b/mineru/model/flash/doc/pieces.py
new file mode 100644
index 00000000..15d22b21
--- /dev/null
+++ b/mineru/model/flash/doc/pieces.py
@@ -0,0 +1,258 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""解析 DOC CLX piece table 并恢复全局 UTF-16 CP 文本流。"""
+
+from __future__ import annotations
+
+from bisect import bisect_left
+from dataclasses import dataclass
+import struct
+
+from mineru.model.flash.legacy_office import LegacyOfficeMalformedError
+
+from .records import DocBudget, bounded_slice, get_u16, get_u32
+
+
+@dataclass(frozen=True, slots=True)
+class Piece:
+ """一个把逻辑 CP 范围映射到 WordDocument FC 的 piece。"""
+
+ cp_start: int
+ cp_end: int
+ fc: int
+ compressed: bool
+ prm: bytes = b""
+
+
+@dataclass(slots=True)
+class TextStream:
+ """字符标量及其 CP、FC 和 piece 映射。"""
+
+ chars: list[str]
+ cps: list[int]
+ fcs: list[int]
+ piece_indexes: list[int]
+
+ def index_of_cp(self, cp: int) -> int:
+ """返回首个 CP 不小于目标值的字符索引。"""
+
+ return bisect_left(self.cps, max(cp, 0))
+
+ def text_between(self, cp_start: int, cp_end: int) -> str:
+ """返回指定 CP 半开区间的 Unicode 文本。"""
+
+ return "".join(self.chars[self.index_of_cp(cp_start) : self.index_of_cp(cp_end)])
+
+
+def _prm0_grpprl(prm: int) -> bytes:
+ """把 Prm0 中已支持的单个属性还原为 grpprl。"""
+
+ isprm = (prm >> 1) & 0x7F
+ value = (prm >> 8) & 0xFF
+ opcode = {
+ 0x0C: 0x260A, # sprmPIlvl
+ 0x18: 0x2416, # sprmPFInTable
+ 0x19: 0x2417, # sprmPFTtp
+ 0x55: 0x0835, # sprmCFBold
+ 0x56: 0x0836, # sprmCFItalic
+ 0x57: 0x0837, # sprmCFStrike
+ 0x78: 0x2640, # sprmPOutLvl
+ }.get(isprm)
+ if opcode is None:
+ return b""
+ return struct.pack("<HB", opcode, value)
+
+
+def _parse_plc_pcd(plc: bytes, prcs: list[bytes], budget: DocBudget) -> list[Piece]:
+ """解析 Pcdt 内的 PlcPcd 并绑定 piece Prm。"""
+
+ if len(plc) < 16 or (len(plc) - 4) % 12:
+ raise LegacyOfficeMalformedError("DOC piece table is empty or malformed")
+ count = (len(plc) - 4) // 12
+ budget.charge(count)
+ cp_bytes = (count + 1) * 4
+ pieces: list[Piece] = []
+ previous_cp = -1
+ for index in range(count):
+ cp_start = get_u32(plc, index * 4)
+ cp_end = get_u32(plc, (index + 1) * 4)
+ pcd_offset = cp_bytes + index * 8
+ fc_raw = get_u32(plc, pcd_offset + 2)
+ prm = get_u16(plc, pcd_offset + 6) or 0
+ if cp_start is None or cp_end is None or fc_raw is None:
+ raise LegacyOfficeMalformedError("DOC piece table is truncated")
+ if cp_start < previous_cp or cp_end < cp_start:
+ raise LegacyOfficeMalformedError("DOC piece CP values are not ordered")
+ previous_cp = cp_end
+ compressed = bool(fc_raw & 0x4000_0000)
+ fc = fc_raw & 0x3FFF_FFFF
+ if compressed:
+ fc //= 2
+ grpprl = b""
+ if prm & 1:
+ prc_index = prm >> 1
+ if prc_index < len(prcs):
+ grpprl = prcs[prc_index]
+ elif prm:
+ grpprl = _prm0_grpprl(prm)
+ pieces.append(
+ Piece(
+ cp_start=int(cp_start),
+ cp_end=int(cp_end),
+ fc=int(fc),
+ compressed=compressed,
+ prm=grpprl,
+ )
+ )
+ return pieces
+
+
+def parse_clx(table_stream: bytes, *, offset: int, size: int, budget: DocBudget) -> list[Piece]:
+ """解析 CLX 中的 Prc 数组和最终 Pcdt。"""
+
+ clx = bounded_slice(table_stream, offset, size)
+ if clx is None:
+ raise LegacyOfficeMalformedError("DOC CLX range is out of bounds")
+ prcs: list[bytes] = []
+ cursor = 0
+ while cursor < len(clx):
+ kind = clx[cursor]
+ if kind == 1:
+ length = get_u16(clx, cursor + 1)
+ if length is None:
+ raise LegacyOfficeMalformedError("DOC CLX Prc is truncated")
+ payload = bounded_slice(clx, cursor + 3, length)
+ if payload is None:
+ raise LegacyOfficeMalformedError("DOC CLX Prc exceeds its range")
+ budget.charge()
+ prcs.append(payload)
+ cursor += 3 + length
+ continue
+ if kind == 2:
+ length = get_u32(clx, cursor + 1)
+ if length is None:
+ raise LegacyOfficeMalformedError("DOC CLX Pcdt is truncated")
+ plc = bounded_slice(clx, cursor + 5, length)
+ if plc is None:
+ raise LegacyOfficeMalformedError("DOC PlcPcd exceeds CLX")
+ return _parse_plc_pcd(plc, prcs, budget)
+ raise LegacyOfficeMalformedError("DOC CLX contains an unknown record")
+ raise LegacyOfficeMalformedError("DOC CLX does not contain a Pcdt")
+
+
+def legacy_single_piece(*, fc_min: int, fc_mac: int, ccp_text: int) -> list[Piece]:
+ """为没有 CLX 的非 complex 文档构造保守单 piece。"""
+
+ if fc_min < 0 or fc_mac <= fc_min:
+ return []
+ length = min(fc_mac - fc_min, max(ccp_text, 0))
+ if length <= 0:
+ return []
+ return [Piece(cp_start=0, cp_end=length, fc=fc_min, compressed=True)]
+
+
+def codec_for_lid(lid: int) -> str:
+ """把 Word LID 映射为 Python 可用的 ANSI/DBCS codec。"""
+
+ primary = lid & 0x03FF
+ if primary == 0x11:
+ return "cp932"
+ if primary == 0x12:
+ return "cp949"
+ if primary == 0x04:
+ return "cp950" if lid in {0x0404, 0x0C04, 0x1404, 0x7C04} else "cp936"
+ if primary in {0x01, 0x20, 0x29}:
+ return "cp1256"
+ if primary in {0x02, 0x19, 0x22, 0x23}:
+ return "cp1251"
+ if primary in {0x05, 0x0E, 0x15, 0x18, 0x1A, 0x1B, 0x24}:
+ return "cp1250"
+ if primary == 0x08:
+ return "cp1253"
+ if primary == 0x0D:
+ return "cp1255"
+ if primary == 0x1E:
+ return "cp874"
+ if primary in {0x1F, 0x2C}:
+ return "cp1254"
+ if primary in {0x25, 0x26, 0x27}:
+ return "cp1257"
+ if primary == 0x2A:
+ return "cp1258"
+ return "cp1252"
+
+
+def _lead_byte(codec: str, value: int) -> bool:
+ """判断一个压缩 piece 字节是否为 DBCS 首字节。"""
+
+ if codec == "cp932":
+ return 0x81 <= value <= 0x9F or 0xE0 <= value <= 0xFC
+ if codec in {"cp936", "cp949", "cp950"}:
+ return 0x81 <= value <= 0xFE
+ return False
+
+
+def extract_text(
+ word_document: bytes,
+ pieces: list[Piece],
+ *,
+ total_cp: int,
+ codec: str,
+ budget: DocBudget,
+) -> TextStream:
+ """按 piece 顺序恢复字符,并保留字符到 CP/FC 的反向映射。"""
+
+ chars: list[str] = []
+ cps: list[int] = []
+ fcs: list[int] = []
+ piece_indexes: list[int] = []
+ for piece_index, piece in enumerate(pieces):
+ if piece.cp_start >= total_cp:
+ break
+ cp_cursor = piece.cp_start
+ logical_length = min(piece.cp_end, total_cp) - piece.cp_start
+ if logical_length <= 0:
+ continue
+ if piece.compressed:
+ payload = bounded_slice(word_document, piece.fc, logical_length)
+ if payload is None:
+ continue
+ cursor = 0
+ while cursor < len(payload):
+ width = 2 if _lead_byte(codec, payload[cursor]) and cursor + 1 < len(payload) else 1
+ decoded = payload[cursor : cursor + width].decode(codec, errors="replace")
+ for char in decoded:
+ chars.append(char)
+ cps.append(cp_cursor)
+ fcs.append(piece.fc + cursor)
+ piece_indexes.append(piece_index)
+ cp_cursor += width
+ cursor += width
+ budget.charge(width)
+ else:
+ byte_length = logical_length * 2
+ payload = bounded_slice(word_document, piece.fc, byte_length)
+ if payload is None:
+ continue
+ cursor = 0
+ while cursor + 2 <= len(payload):
+ first = int(struct.unpack_from("<H", payload, cursor)[0])
+ width = 2
+ units = [first]
+ if 0xD800 <= first <= 0xDBFF and cursor + 4 <= len(payload):
+ second = int(struct.unpack_from("<H", payload, cursor + 2)[0])
+ if 0xDC00 <= second <= 0xDFFF:
+ units.append(second)
+ width = 4
+ raw = struct.pack(f"<{len(units)}H", *units)
+ char = raw.decode("utf-16le", errors="replace")
+ chars.append(char)
+ cps.append(cp_cursor)
+ fcs.append(piece.fc + cursor)
+ piece_indexes.append(piece_index)
+ unit_count = width // 2
+ cp_cursor += unit_count
+ cursor += width
+ budget.charge(unit_count)
+ return TextStream(chars=chars, cps=cps, fcs=fcs, piece_indexes=piece_indexes)
+
diff --git a/mineru/model/flash/doc/records.py b/mineru/model/flash/doc/records.py
new file mode 100644
index 00000000..4e87a3e5
--- /dev/null
+++ b/mineru/model/flash/doc/records.py
@@ -0,0 +1,78 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""DOC 二进制结构使用的有界整数、PLC 和记录预算工具。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import struct
+
+from mineru.model.flash.legacy_office import LegacyOfficeResourceLimitError
+from mineru.model.flash.legacy_office.limits import MAX_RECORDS
+
+
+@dataclass(slots=True)
+class DocBudget:
+ """限制 DOC 解析累计访问的记录和文本单元数。"""
+
+ visited: int = 0
+
+ def charge(self, amount: int = 1) -> None:
+ """计入本次访问量,超过统一上限时稳定失败。"""
+
+ if amount < 0 or self.visited + amount > MAX_RECORDS:
+ raise LegacyOfficeResourceLimitError(f"DOC records exceed max_records={MAX_RECORDS}")
+ self.visited += amount
+
+
+def get_u16(data: bytes, offset: int) -> int | None:
+ """有界读取小端 u16。"""
+
+ 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:
+ """有界读取小端 i16。"""
+
+ 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:
+ """有界读取小端 u32。"""
+
+ if offset < 0 or offset + 4 > len(data):
+ return None
+ return int(struct.unpack_from("<I", data, offset)[0])
+
+
+def bounded_slice(data: bytes, offset: int, size: int) -> bytes | None:
+ """返回无溢出的指定字节范围。"""
+
+ if offset < 0 or size < 0 or offset > len(data) - size:
+ return None
+ return data[offset : offset + size]
+
+
+def parse_plc(data: bytes, *, item_size: int, budget: DocBudget) -> tuple[list[int], list[bytes]]:
+ """解析由 CP 数组和定长数据项组成的通用 PLC。"""
+
+ if item_size < 0 or len(data) < 4:
+ return [], []
+ denominator = 4 + item_size
+ payload = len(data) - 4
+ if denominator <= 0 or payload % denominator:
+ return [], []
+ count = payload // denominator
+ budget.charge(count + 1)
+ cp_bytes = (count + 1) * 4
+ cps = [int(struct.unpack_from("<I", data, index * 4)[0]) for index in range(count + 1)]
+ items = [
+ data[cp_bytes + index * item_size : cp_bytes + (index + 1) * item_size]
+ for index in range(count)
+ ]
+ return cps, items
+
diff --git a/mineru/model/flash/doc/sprm.py b/mineru/model/flash/doc/sprm.py
new file mode 100644
index 00000000..028e0335
--- /dev/null
+++ b/mineru/model/flash/doc/sprm.py
@@ -0,0 +1,273 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""遍历并应用 Word 二进制单属性修饰符 SPRM。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, replace
+import struct
+from typing import Callable
+
+from .models import DocCharStyle, DocTableCellFormat, DocTableFormat
+from .records import DocBudget, get_i16, get_u16, get_u32
+
+
+def _operand_length(opcode: int, operand: bytes) -> int:
+ """根据 SPRM 的 spra 字段计算 operand 字节数。"""
+
+ spra = opcode >> 13
+ if spra in {0, 1}:
+ return 1
+ if spra in {2, 4, 5}:
+ return 2
+ if spra == 3:
+ return 4
+ if spra == 7:
+ return 3
+ if opcode == 0xD608:
+ return (get_u16(operand, 0) or -1) + 1
+ return (operand[0] + 1) if operand else 0
+
+
+def walk_sprms(
+ grpprl: bytes,
+ callback: Callable[[int, bytes], None],
+ *,
+ budget: DocBudget | None = None,
+) -> None:
+ """有界顺序遍历 grpprl,截断尾部按可恢复内容处理。"""
+
+ cursor = 0
+ while cursor + 2 <= len(grpprl):
+ opcode = int(struct.unpack_from("<H", grpprl, cursor)[0])
+ cursor += 2
+ length = _operand_length(opcode, grpprl[cursor:])
+ if length <= 0 or cursor + length > len(grpprl):
+ return
+ if budget is not None:
+ budget.charge()
+ callback(opcode, grpprl[cursor : cursor + length])
+ cursor += length
+
+
+def _toggle(operand: bytes, base: bool) -> bool | None:
+ """把 Word ToggleOperand 解析为相对样式基值。"""
+
+ if not operand:
+ return None
+ return {0: False, 1: True, 0x80: base, 0x81: not base}.get(operand[0])
+
+
+def chpx_style_id(grpprl: bytes) -> int | None:
+ """读取 CHPX 指定的字符样式 istd。"""
+
+ result: int | None = None
+
+ def consume(opcode: int, operand: bytes) -> None:
+ """记录最后一个有效 sprmCIstd。"""
+
+ nonlocal result
+ if opcode == 0x4A30:
+ result = get_u16(operand, 0)
+
+ walk_sprms(grpprl, consume)
+ return result
+
+
+def chpx_picture_location(grpprl: bytes) -> int | None:
+ """读取 CHPX 中的 sprmCPicLocation。"""
+
+ result: int | None = None
+
+ def consume(opcode: int, operand: bytes) -> None:
+ """记录最后一个有效图片偏移。"""
+
+ nonlocal result
+ if opcode == 0x6A03:
+ result = get_u32(operand, 0)
+
+ walk_sprms(grpprl, consume)
+ return result
+
+
+def apply_character_sprms(
+ grpprl: bytes,
+ current: DocCharStyle,
+ style_base: DocCharStyle,
+ *,
+ budget: DocBudget | None = None,
+) -> DocCharStyle:
+ """按 Word 样式覆盖顺序把 CHPX 应用到字符样式。"""
+
+ style = current
+
+ def consume(opcode: int, operand: bytes) -> None:
+ """应用当前可表达的字符属性。"""
+
+ nonlocal style
+ toggle_field = {
+ 0x0800: "deleted", # sprmCFRMarkDel
+ 0x0802: "hidden", # sprmCFFldVanish
+ 0x0835: "bold",
+ 0x0836: "italic",
+ 0x0837: "strike",
+ 0x083C: "hidden", # sprmCFVanish
+ }.get(opcode)
+ if toggle_field is not None:
+ value = _toggle(operand, bool(getattr(style_base, toggle_field)))
+ if value is not None:
+ style = replace(style, **{toggle_field: value})
+ return
+ if opcode == 0x2A3E and operand: # sprmCKul
+ style = replace(style, underline=operand[0] not in {0, 5})
+ elif opcode == 0x2A48 and operand: # sprmCIss
+ style = replace(
+ style,
+ superscript=operand[0] == 1,
+ subscript=operand[0] == 2,
+ )
+ elif opcode == 0x2A53 and operand: # sprmCFDStrike
+ style = replace(style, strike=operand[0] != 0)
+ elif opcode == 0x2A54 and operand: # sprmCEm
+ style = replace(style, emphasis=operand[0] != 0)
+
+ walk_sprms(grpprl, consume, budget=budget)
+ return style
+
+
+@dataclass(frozen=True, slots=True)
+class PapDelta:
+ """PAPX 或段落样式对可见段落属性的增量。"""
+
+ in_table: bool | None = None
+ row_mark: bool | None = None
+ outline_level: int | None | object = None
+ ilfo: int | None = None
+ ilvl: int | None = None
+ table_depth: int | None = None
+ inner_cell: bool | None = None
+ inner_row: bool | None = None
+ table: DocTableFormat | None = None
+
+ def merge(self, over: PapDelta) -> PapDelta:
+ """让后应用的段落属性覆盖当前增量。"""
+
+ return PapDelta(
+ in_table=over.in_table if over.in_table is not None else self.in_table,
+ row_mark=over.row_mark if over.row_mark is not None else self.row_mark,
+ outline_level=(
+ over.outline_level if over.outline_level is not None else self.outline_level
+ ),
+ ilfo=over.ilfo if over.ilfo is not None else self.ilfo,
+ ilvl=over.ilvl if over.ilvl is not None else self.ilvl,
+ table_depth=over.table_depth if over.table_depth is not None else self.table_depth,
+ inner_cell=over.inner_cell if over.inner_cell is not None else self.inner_cell,
+ inner_row=over.inner_row if over.inner_row is not None else self.inner_row,
+ table=over.table if over.table is not None else self.table,
+ )
+
+
+def _parse_tdef_table(operand: bytes) -> DocTableFormat | None:
+ """解析 TDefTableOperand 中的边界和横纵向合并标志。"""
+
+ if len(operand) < 3:
+ return None
+ columns = operand[2]
+ if columns > 63:
+ return None
+ boundaries: list[int] = []
+ for index in range(columns + 1):
+ value = get_i16(operand, 3 + index * 2)
+ if value is None:
+ return None
+ boundaries.append(value)
+ cells: list[DocTableCellFormat] = []
+ tc_base = 3 + (columns + 1) * 2
+ for index in range(columns):
+ flags = get_u16(operand, tc_base + index * 20) or 0
+ horizontal = flags & 0x3
+ vertical = (flags >> 5) & 0x3
+ right = boundaries[index + 1]
+ cells.append(
+ DocTableCellFormat(
+ right=right,
+ horizontal_first=horizontal >= 2,
+ horizontal_continue=horizontal == 1,
+ vertical_first=vertical == 3,
+ vertical_continue=vertical == 1,
+ )
+ )
+ return DocTableFormat(boundaries=tuple(boundaries), cells=tuple(cells))
+
+
+def apply_paragraph_sprms(
+ grpprl: bytes,
+ data_stream: bytes,
+ initial: PapDelta | None = None,
+ *,
+ budget: DocBudget | None = None,
+) -> PapDelta:
+ """应用 PAPX SPRM,并解析 huge PAPX 与表格行属性。"""
+
+ delta = initial or PapDelta()
+
+ def consume(opcode: int, operand: bytes) -> None:
+ """应用一个段落或表格属性。"""
+
+ nonlocal delta
+ if opcode == 0x2416 and operand:
+ delta = replace(delta, in_table=operand[0] != 0)
+ elif opcode == 0x2417 and operand:
+ delta = replace(delta, row_mark=operand[0] != 0)
+ elif opcode == 0x6646:
+ offset = get_u32(operand, 0)
+ length = get_u16(data_stream, offset) if offset is not None else None
+ if offset is not None and length is not None and offset + 2 + length <= len(data_stream):
+ delta = apply_paragraph_sprms(
+ data_stream[offset + 2 : offset + 2 + length],
+ b"",
+ delta,
+ budget=budget,
+ )
+ elif opcode == 0x2640 and operand:
+ delta = replace(delta, outline_level=operand[0] + 1 if operand[0] < 9 else -1)
+ elif opcode == 0x260A and operand:
+ delta = replace(delta, ilvl=int(operand[0]))
+ elif opcode == 0x460B:
+ delta = replace(delta, ilfo=get_u16(operand, 0))
+ elif opcode == 0x6649:
+ depth = get_u32(operand, 0)
+ if depth is not None:
+ delta = replace(delta, table_depth=int(depth))
+ elif opcode == 0x664A:
+ raw = get_u32(operand, 0)
+ if raw is not None:
+ signed = struct.unpack("<i", struct.pack("<I", raw))[0]
+ delta = replace(delta, table_depth=max(0, (delta.table_depth or 0) + signed))
+ elif opcode == 0x244B and operand:
+ delta = replace(delta, inner_cell=operand[0] != 0)
+ elif opcode == 0x244C and operand:
+ delta = replace(delta, inner_row=operand[0] != 0)
+ elif opcode == 0xD608:
+ table = _parse_tdef_table(operand)
+ if table is not None:
+ header = delta.table.header if delta.table is not None else False
+ delta = replace(delta, table=replace(table, header=header))
+ elif opcode == 0x3404 and operand:
+ table = delta.table or DocTableFormat()
+ delta = replace(delta, table=replace(table, header=operand[0] != 0))
+ elif opcode == 0xD62B and len(operand) >= 3 and delta.table is not None:
+ cell_index = operand[1]
+ flag = operand[2]
+ cells = list(delta.table.cells)
+ if cell_index < len(cells):
+ cells[cell_index] = replace(
+ cells[cell_index],
+ vertical_continue=flag == 1,
+ vertical_first=flag == 3,
+ )
+ delta = replace(delta, table=replace(delta.table, cells=tuple(cells)))
+
+ walk_sprms(grpprl, consume, budget=budget)
+ return delta
+
diff --git a/mineru/model/flash/doc/styles.py b/mineru/model/flash/doc/styles.py
new file mode 100644
index 00000000..7ab135df
--- /dev/null
+++ b/mineru/model/flash/doc/styles.py
@@ -0,0 +1,217 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""解析 Word STSH/STD 样式表并解析继承链。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import re
+
+from loguru import logger
+
+from .models import DocCharStyle
+from .records import DocBudget, bounded_slice, get_u16
+from .sprm import PapDelta, apply_character_sprms, apply_paragraph_sprms
+
+ISTD_NIL = 0x0FFF
+
+
+@dataclass(frozen=True, slots=True)
+class ResolvedStyle:
+ """一个样式继承完成后的可见属性。"""
+
+ name: str = ""
+ character: DocCharStyle = DocCharStyle()
+ paragraph: PapDelta = PapDelta()
+ heading_level: int | None = None
+ is_title: bool = False
+ toc_level: int | None = None
+ is_code: bool = False
+
+
+@dataclass(frozen=True, slots=True)
+class _RawStyle:
+ """STSH 内尚未解析继承的 STD。"""
+
+ sti: int
+ name: str
+ base: int
+ paragraph_grpprl: bytes
+ character_grpprl: bytes
+ paragraph_style: bool
+
+
+class Stylesheet:
+ """按 istd 提供解析后样式的只读集合。"""
+
+ def __init__(self, styles: dict[int, ResolvedStyle] | None = None) -> None:
+ """保存已解析样式并准备默认样式。"""
+
+ self._styles = styles or {}
+ self._default = ResolvedStyle()
+
+ def get(self, style_id: int) -> ResolvedStyle:
+ """返回指定样式,不存在时使用空默认值。"""
+
+ return self._styles.get(style_id, self._default)
+
+
+def _style_semantics(sti: int, name: str) -> tuple[int | None, bool, int | None, bool]:
+ """从内建 ID 与样式名识别标题、目录和代码语义。"""
+
+ normalized = re.sub(r"\s+", " ", name.strip()).casefold()
+ heading_level = sti if 1 <= sti <= 9 else None
+ if heading_level is None:
+ match = re.match(r"^(?:heading|标题)\s*([1-9])$", normalized)
+ if match:
+ heading_level = int(match.group(1))
+ is_title = normalized in {"title", "标题", "文档标题"} or sti == 15
+ toc_level: int | None = None
+ match = re.match(r"^(?:toc|目录)\s*([1-9])$", normalized)
+ if match:
+ toc_level = int(match.group(1)) - 1
+ is_code = any(token in normalized for token in ("code", "preformatted", "source code", "代码"))
+ return heading_level, is_title, toc_level, is_code
+
+
+def _parse_std(record: bytes, base_size: int) -> _RawStyle | None:
+ """解析一条 STD 的名称、继承和 UPX 内容。"""
+
+ if len(record) < max(base_size, 10):
+ return None
+ first = get_u16(record, 0)
+ second = get_u16(record, 2)
+ third = get_u16(record, 4)
+ if first is None or second is None or third is None:
+ return None
+ sti = first & 0x0FFF
+ kind = second & 0x000F
+ base = (second >> 4) & 0x0FFF
+ upx_count = third & 0x000F
+ name_offset = max(base_size, 10)
+ name_length = get_u16(record, name_offset)
+ if name_length is None:
+ return None
+ name_bytes = name_length * 2
+ raw_name = bounded_slice(record, name_offset + 2, name_bytes)
+ if raw_name is None:
+ return None
+ name = raw_name.decode("utf-16le", errors="replace")
+ cursor = name_offset + 2 + name_bytes + 2
+ upx: list[bytes] = []
+ for _ in range(upx_count):
+ if cursor % 2:
+ cursor += 1
+ length = get_u16(record, cursor)
+ if length is None:
+ break
+ payload = bounded_slice(record, cursor + 2, length)
+ if payload is None:
+ break
+ upx.append(payload)
+ cursor += 2 + length
+ paragraph_style = kind == 1
+ if paragraph_style:
+ paragraph_grpprl = upx[0][2:] if upx and len(upx[0]) >= 2 else b""
+ character_grpprl = upx[1] if len(upx) > 1 else b""
+ elif kind == 2:
+ paragraph_grpprl = b""
+ character_grpprl = upx[0] if upx else b""
+ else:
+ paragraph_grpprl = b""
+ character_grpprl = b""
+ return _RawStyle(
+ sti=sti,
+ name=name,
+ base=base,
+ paragraph_grpprl=paragraph_grpprl,
+ character_grpprl=character_grpprl,
+ paragraph_style=paragraph_style,
+ )
+
+
+def parse_stylesheet(
+ table_stream: bytes,
+ *,
+ offset: int,
+ size: int,
+ budget: DocBudget,
+) -> Stylesheet:
+ """解析 STSH,并在循环样式链处安全截断继承。"""
+
+ payload = bounded_slice(table_stream, offset, size)
+ if payload is None or len(payload) < 8:
+ return Stylesheet()
+ header_size = get_u16(payload, 0)
+ style_count = get_u16(payload, 2)
+ base_size = get_u16(payload, 4)
+ if header_size is None or style_count is None or base_size is None:
+ return Stylesheet()
+ cursor = 2 + header_size
+ raw_styles: dict[int, _RawStyle] = {}
+ for style_id in range(style_count):
+ length = get_u16(payload, cursor)
+ if length is None:
+ break
+ cursor += 2
+ if length == 0:
+ continue
+ record = bounded_slice(payload, cursor, length)
+ if record is None:
+ break
+ cursor += length
+ budget.charge()
+ parsed = _parse_std(record, base_size)
+ if parsed is not None:
+ raw_styles[style_id] = parsed
+
+ memo: dict[int, ResolvedStyle] = {}
+
+ def resolve(style_id: int) -> ResolvedStyle:
+ """迭代解析一个样式的 based-on 链。"""
+
+ if style_id in memo:
+ return memo[style_id]
+ chain: list[int] = []
+ visiting: set[int] = set()
+ cursor_id: int | None = style_id
+ base = ResolvedStyle()
+ while cursor_id is not None:
+ if cursor_id in memo:
+ base = memo[cursor_id]
+ break
+ if cursor_id in visiting:
+ logger.warning(f"DOC style inheritance cycle at istd={cursor_id}")
+ break
+ raw = raw_styles.get(cursor_id)
+ if raw is None:
+ break
+ visiting.add(cursor_id)
+ chain.append(cursor_id)
+ cursor_id = raw.base if raw.base not in {ISTD_NIL, cursor_id} else None
+ for current_id in reversed(chain):
+ raw = raw_styles[current_id]
+ paragraph = apply_paragraph_sprms(raw.paragraph_grpprl, b"", base.paragraph, budget=budget)
+ character = apply_character_sprms(
+ raw.character_grpprl,
+ base.character,
+ base.character,
+ budget=budget,
+ )
+ heading, is_title, toc_level, is_code = _style_semantics(raw.sti, raw.name)
+ base = ResolvedStyle(
+ name=raw.name or base.name,
+ character=character,
+ paragraph=paragraph,
+ heading_level=heading if heading is not None else base.heading_level,
+ is_title=is_title or base.is_title,
+ toc_level=toc_level if toc_level is not None else base.toc_level,
+ is_code=is_code or base.is_code,
+ )
+ memo[current_id] = base
+ return base
+
+ for style_id in raw_styles:
+ resolve(style_id)
+ return Stylesheet(memo)
+
diff --git a/mineru/model/flash/legacy_office/officeart.py b/mineru/model/flash/legacy_office/officeart.py
index ad4d7989..a2c28f21 100644
--- a/mineru/model/flash/legacy_office/officeart.py
+++ b/mineru/model/flash/legacy_office/officeart.py
@@ -202,22 +202,50 @@ def extract_excel_shapes(
return shapes
+def _bitmap_payload(body: bytes, instance: int) -> bytes | None:
+ """跳过 BLIP UID 和 tag,返回位图原始载荷。"""
+
+ doubled = instance in {0x46B, 0x6E3, 0x6E1, 0x7A9}
+ start = (32 if doubled else 16) + 1
+ return body[start:] if start < len(body) else None
+
+
+def _dib_to_bmp(data: bytes) -> bytes:
+ """为裸 DIB 补齐 BMP 文件头,无法推断时仍保留原始载荷。"""
+
+ if data.startswith(b"BM") or len(data) < 4:
+ return data
+ header_size = int(struct.unpack_from("<I", data, 0)[0])
+ if header_size < 12 or header_size > len(data):
+ return data
+ palette_bytes = 0
+ if header_size >= 40 and len(data) >= 36:
+ bit_count = int(struct.unpack_from("<H", data, 14)[0])
+ colors_used = int(struct.unpack_from("<I", data, 32)[0])
+ colors = colors_used or ((1 << bit_count) if bit_count <= 8 else 0)
+ palette_bytes = colors * 4
+ pixel_offset = min(14 + header_size + palette_bytes, 14 + len(data))
+ return b"BM" + struct.pack("<IHHI", 14 + len(data), 0, 0, pixel_offset) + data
+
+
def decode_blip(record: OfficeArtRecord) -> OfficeImagePayload | None:
- """解码 JPEG、PNG、EMF 或 WMF BLIP,并限制矢量解压输出。"""
+ """解码常见位图和 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):
+ if record.record_type in {0xF01D, 0xF01E, 0xF01F, 0xF029}:
+ data = _bitmap_payload(body, instance)
+ if data is None:
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 == 0xF01E:
+ return OfficeImagePayload(data=data, extension="png", content_type="image/png")
+ if record.record_type == 0xF029:
+ return OfficeImagePayload(data=data, extension="tiff", content_type="image/tiff")
+ return OfficeImagePayload(data=_dib_to_bmp(data), extension="bmp", content_type="image/bmp")
if record.record_type not in {0xF01A, 0xF01B}:
return None
@@ -233,13 +261,22 @@ def decode_blip(record: OfficeArtRecord) -> OfficeImagePayload | None:
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:
+ data = b""
+ reached_eof = False
+ for window_bits in (-zlib.MAX_WBITS, zlib.MAX_WBITS):
+ try:
+ inflater = zlib.decompressobj(window_bits)
+ candidate = inflater.decompress(payload, MAX_ENTRY_BYTES + 1)
+ candidate += inflater.flush(MAX_ENTRY_BYTES + 1 - len(candidate))
+ except zlib.error:
+ continue
+ if inflater.eof:
+ data = candidate
+ reached_eof = True
+ break
+ if not reached_eof:
return None
- if len(data) > MAX_ENTRY_BYTES or not inflater.eof:
+ if len(data) > MAX_ENTRY_BYTES:
raise LegacyOfficeResourceLimitError(
"metafile BLIP decompression exceeded its limit"
)
@@ -252,17 +289,61 @@ def decode_blip(record: OfficeArtRecord) -> OfficeImagePayload | None:
return OfficeImagePayload(data=data, extension="wmf", content_type="image/wmf")
+def first_blip(
+ data: bytes,
+ *,
+ charge: Callable[[], None] | None = None,
+) -> OfficeImagePayload | None:
+ """深度优先返回一段 OfficeArt 数据中的首个可支持 BLIP。"""
+
+ for record in iter_descendants(data, charge=charge):
+ if record.record_type == OFFICEART_BSE:
+ decoded = _decode_bse_body(record.payload, charge=charge)
+ if decoded is not None:
+ return decoded
+ decoded = decode_blip(record)
+ if decoded is not None:
+ return decoded
+ return None
+
+
+def extract_word_shapes(
+ data: bytes,
+ *,
+ charge: Callable[[], None] | None = None,
+) -> list[OfficeArtShape]:
+ """按 Word drawing 顺序提取 shape id、pib 和隐藏状态。"""
+
+ 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_bse_body(
body: bytes,
*,
charge: Callable[[], None] | None = None,
+ delay_stream: bytes | None = None,
) -> OfficeImagePayload | None:
- """从 FBSE body 的可选内嵌 BLIP 中恢复图片。"""
+ """从 FBSE body 的内嵌或延迟 BLIP 中恢复图片。"""
if len(body) < 36:
return None
inner_offset = 36 + int(body[33])
- inner = record_at(body, inner_offset, charge=charge)
+ inner = record_at(body, inner_offset, charge=charge) if inner_offset < len(body) else None
+ if inner is None and delay_stream is not None:
+ delayed_size = int(struct.unpack_from("<I", body, 20)[0])
+ reference_count = int(struct.unpack_from("<I", body, 24)[0])
+ delayed_offset = int(struct.unpack_from("<I", body, 28)[0])
+ if reference_count and delayed_offset != 0xFFFF_FFFF:
+ delayed_end = delayed_offset + delayed_size
+ if delayed_end >= delayed_offset and delayed_end <= len(delay_stream):
+ inner = record_at(delay_stream, delayed_offset, end=delayed_end, charge=charge)
return decode_blip(inner) if inner is not None else None
@@ -270,6 +351,7 @@ def decode_bstore(
data: bytes,
*,
charge: Callable[[], None] | None = None,
+ delay_stream: bytes | None = None,
) -> dict[int, OfficeImagePayload]:
"""按一基 BSE 序号解码 drawing group 中的图片资源。"""
@@ -281,7 +363,11 @@ def decode_bstore(
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)
+ decoded = _decode_bse_body(
+ bse.payload,
+ charge=charge,
+ delay_stream=delay_stream,
+ )
if decoded is None:
continue
asset_total += len(decoded.data)
diff --git a/mineru/model/flash/model.py b/mineru/model/flash/model.py
index 00ed38ed..0c5cb480 100644
--- a/mineru/model/flash/model.py
+++ b/mineru/model/flash/model.py
@@ -34,6 +34,20 @@ class DocxModel:
return converter.pages
+class DocModel:
+ """将 Word 97–2003 Converter 包装为无状态模型。"""
+
+ def predict(self, file_binary: BinaryIO) -> list[list[dict[str, Any]]]:
+ """转换调用方持有的 DOC 二进制流,并返回逐 section model-list。"""
+
+ # 延迟加载旧版 DOC 解析器,避免其他格式提前加载 olefile。
+ from .doc.doc_converter import DocConverter
+
+ converter = DocConverter()
+ converter.convert(file_binary)
+ return converter.pages
+
+
class PptxModel:
"""将 PPTX Converter 包装为无状态模型。"""
diff --git a/mineru/types.py b/mineru/types.py
index c77e28eb..c372e35f 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", "ppt", "pptx", "xls", "xlsx"]
+ file_suffix: Literal["pdf", "doc", "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", "ppt", "pptx", "xls", "xlsx"]
+ file_suffix: Literal["pdf", "doc", "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/tests/unittest/_legacy_doc_test_utils.py b/tests/unittest/_legacy_doc_test_utils.py
new file mode 100644
index 00000000..805113d3
--- /dev/null
+++ b/tests/unittest/_legacy_doc_test_utils.py
@@ -0,0 +1,101 @@
+"""构造不依赖 Word 的最小 Word 97–2003 测试文件。"""
+
+from __future__ import annotations
+
+import struct
+
+from _legacy_ppt_test_utils import _build_cfb
+
+
+def _piece_table(text_fc: int, cp_count: int, *, compressed: bool) -> bytes:
+ """构造只含一个 piece 的 CLX。"""
+
+ fc_raw = text_fc * 2 | 0x4000_0000 if compressed else text_fc
+ plc = struct.pack("<II", 0, cp_count)
+ plc += b"\x00\x00" + struct.pack("<I", fc_raw) + b"\x00\x00"
+ return b"\x02" + struct.pack("<I", len(plc)) + plc
+
+
+def _section_plc(section_ends: list[int]) -> bytes:
+ """构造只提供 CP 边界、Sed 使用零值的 PlcfSed。"""
+
+ starts = [0, *section_ends]
+ return struct.pack(f"<{len(starts)}I", *starts) + b"\x00" * (12 * len(section_ends))
+
+
+def build_doc(
+ text: str,
+ *,
+ section_ends: list[int] | None = None,
+ compressed: bool = False,
+ flags_extra: int = 0,
+ n_fib: int = 0x00C1,
+ footnote_text: str | None = None,
+ codec: str = "cp1252",
+ lid: int = 0x0409,
+) -> bytes:
+ """构造带 CLX 和 PlcfSed 的最小 DOC OLE 文件。"""
+
+ main_encoded = text.encode(codec) if compressed else text.encode("utf-16le")
+ main_cp_count = len(main_encoded) if compressed else len(main_encoded) // 2
+ footnote_value = footnote_text or ""
+ footnote_encoded = footnote_value.encode(codec) if compressed else footnote_value.encode("utf-16le")
+ footnote_cp_count = len(footnote_encoded) if compressed else len(footnote_encoded) // 2
+ encoded = main_encoded + footnote_encoded
+ cp_count = main_cp_count + footnote_cp_count
+ text_fc = 1024
+ clx = _piece_table(text_fc, cp_count, compressed=compressed)
+ section_ends = section_ends or [main_cp_count]
+ sections = _section_plc(section_ends)
+ table = clx + sections
+
+ pair_count = 75
+ pairs = [(0, 0)] * pair_count
+ pairs[6] = (len(clx), len(sections))
+ pairs[33] = (0, len(clx))
+ if footnote_text is not None:
+ reference_cp = text.index("\x02")
+ footnote_ref = struct.pack("<IIH", reference_cp, main_cp_count, 1)
+ footnote_ranges = struct.pack("<II", 0, footnote_cp_count)
+ pairs[2] = (len(table), len(footnote_ref))
+ table += footnote_ref
+ pairs[3] = (len(table), len(footnote_ranges))
+ table += footnote_ranges
+ else:
+ # 合法空脚注 reference PLC:仅保留终止 CP。
+ pairs[2] = (len(table), 4)
+ table += struct.pack("<I", 0)
+
+ base = bytearray(32)
+ struct.pack_into("<HH", base, 0, 0xA5EC, n_fib)
+ struct.pack_into("<H", base, 6, lid)
+ flags = 0x0004 | 0x0200 | flags_extra
+ struct.pack_into("<H", base, 10, flags)
+ struct.pack_into("<II", base, 24, text_fc, text_fc + len(encoded))
+ rgw = [0] * 14
+ if flags & 0x4000:
+ rgw[13] = lid
+ rglw = [0] * 11
+ rglw[0] = text_fc + len(encoded)
+ rglw[3] = main_cp_count
+ rglw[4] = footnote_cp_count
+ fib = bytes(base)
+ fib += struct.pack("<H", len(rgw)) + struct.pack(f"<{len(rgw)}H", *rgw)
+ fib += struct.pack("<H", len(rglw)) + struct.pack(f"<{len(rglw)}I", *rglw)
+ fib += struct.pack("<H", pair_count)
+ fib += b"".join(struct.pack("<II", offset, size) for offset, size in pairs)
+ fib += struct.pack("<H", 0)
+ word_document = fib + b"\x00" * (text_fc - len(fib)) + encoded
+ return _build_cfb(
+ [
+ ("1Table", table),
+ ("Data", b""),
+ ("WordDocument", word_document),
+ ]
+ )
+
+
+def utf16_cp(text: str) -> int:
+ """返回字符串占用的 UTF-16 code unit 数。"""
+
+ return len(text.encode("utf-16le")) // 2
diff --git a/tests/unittest/test_flash_legacy_doc.py b/tests/unittest/test_flash_legacy_doc.py
new file mode 100644
index 00000000..73560820
--- /dev/null
+++ b/tests/unittest/test_flash_legacy_doc.py
@@ -0,0 +1,293 @@
+from __future__ import annotations
+
+import asyncio
+from collections import Counter
+from io import BytesIO
+from pathlib import Path
+
+from bs4 import BeautifulSoup
+import pytest
+
+from mineru.backend.analyze import aio_doc_analyze, doc_analyze
+from mineru.backend.postprocess.lists import fix_office_list_blocks
+from mineru.model.flash import DocModel
+from mineru.model.flash.doc.fields import sanitize_hyperlink_target
+from mineru.model.flash.doc.models import DocCharStyle, DocTableCell
+from mineru.model.flash.doc.parser import _RawTableRow, _materialize_table_rows
+from mineru.model.flash.doc.records import DocBudget
+from mineru.model.flash.doc.sprm import apply_character_sprms
+from mineru.model.flash.legacy_office import (
+ LegacyOfficeEncryptedError,
+ LegacyOfficeMalformedError,
+ LegacyOfficeMissingPartError,
+ LegacyOfficeResourceLimitError,
+)
+from mineru.types import BlockType, MiddleJson, ModelJson, TableBlock
+
+from _legacy_doc_test_utils import build_doc, utf16_cp
+from _legacy_ppt_test_utils import _build_cfb
+
+
+_PROJECT_ROOT = Path(__file__).resolve().parents[2]
+_REAL_DOC = (
+ _PROJECT_ROOT
+ / "output"
+ / "office_roundtrip_research_20260824"
+ / "legacy"
+ / "docx_01.doc"
+)
+
+
+def test_doc_model_preserves_empty_sections_and_ignores_page_breaks() -> None:
+ """验证 section 是唯一分页来源,空 section 保留且分页符不额外切页。"""
+
+ text = "\fFirst\rSecond\r"
+ first_end = utf16_cp("\fFirst\r")
+ stream = BytesIO(build_doc(text, section_ends=[0, first_end, utf16_cp(text)]))
+
+ pages = DocModel().predict(stream)
+
+ assert not stream.closed
+ assert pages == [[], [{"type": BlockType.TEXT, "content": "First"}], [{"type": BlockType.TEXT, "content": "Second"}]]
+
+
+def test_doc_analyze_sync_and_async_return_strict_doc_contract() -> None:
+ """验证同步和异步 Analyze 均保留 DOC 严格后缀和 Flash/TXT 元数据。"""
+
+ file_bytes = build_doc("Hello\r")
+ middle, model = doc_analyze(file_bytes, file_suffix="doc")
+ async_middle, async_model = asyncio.run(aio_doc_analyze(file_bytes, file_suffix="doc"))
+
+ assert isinstance(model, ModelJson)
+ assert isinstance(middle, MiddleJson)
+ assert model.file_suffix == middle.file_suffix == "doc"
+ assert model.effort == middle.effort == "flash"
+ assert model.parse_mode == middle.parse_mode == "txt"
+ assert async_model == model
+ assert async_middle == middle
+
+
+ ("text", "compressed", "kwargs"),
+ [
+ ("A😀B\r", False, {}),
+ ("café\r", True, {}),
+ ("Привет, мир!\r", True, {"codec": "cp1251", "lid": 0x0419}),
+ ("こんにちは世界。\r", True, {"codec": "cp932", "lid": 0x0411, "flags_extra": 0x4000}),
+ ],
+)
+def test_doc_piece_text_preserves_non_bmp_and_compressed_codepage(
+ text: str,
+ compressed: bool,
+ kwargs: dict[str, object],
+) -> None:
+ """验证 UTF-16 非 BMP CP 和压缩 ANSI piece 均恢复原文本。"""
+
+ pages = DocModel().predict(BytesIO(build_doc(text, compressed=compressed, **kwargs)))
+
+ assert pages == [[{"type": BlockType.TEXT, "content": text.rstrip("\r")}]]
+
+
+def test_doc_footnote_reference_and_body_bind_to_reference_section() -> None:
+ """验证脚注引用使用上标样式,脚注正文追加到引用所在 section。"""
+
+ pages = DocModel().predict(
+ BytesIO(
+ build_doc(
+ "Body\x02\rTail\r",
+ section_ends=[6, 11],
+ footnote_text="Foot note\r",
+ )
+ )
+ )
+
+ assert '<text style="superscript">[1]</text>' in pages[0][0]["content"]
+ assert pages[0][-1] == {"type": BlockType.PAGE_FOOTNOTE, "content": "[1] Foot note"}
+ assert all(block.get("type") != BlockType.PAGE_FOOTNOTE for block in pages[1])
+
+
+def test_doc_hyperlink_field_keeps_safe_target_and_drops_dangerous_target() -> None:
+ """验证字段缓存结果保留,危险 URL 只降级为普通文本。"""
+
+ text = (
+ '\x13 HYPERLINK "https://example.test/a" \x14Safe\x15\r'
+ '\x13 HYPERLINK "javascript:alert(1)" \x14Danger\x15\r'
+ )
+ pages = DocModel().predict(BytesIO(build_doc(text)))
+
+ assert "<url>https://example.test/a</url>" in pages[0][0]["content"]
+ assert pages[0][1] == {"type": BlockType.TEXT, "content": "Danger"}
+
+
+ ("target", "expected"),
+ [
+ ("https://example.test", "https://example.test"),
+ ("#bookmark", "#bookmark"),
+ ("docs/readme.doc", "docs/readme.doc"),
+ ("file:///tmp/a.doc", None),
+ (r"C:\\docs\\a.doc", None),
+ (r"\\server\\share\\a.doc", None),
+ ("data:text/plain,x", None),
+ ],
+)
+def test_doc_hyperlink_security_policy(target: str, expected: str | None) -> None:
+ """验证 DOC 链接白名单拒绝本地和可执行目标。"""
+
+ assert sanitize_hyperlink_target(target) == expected
+
+
+def test_doc_character_sprms_preserve_visible_styles_and_hide_revisions() -> None:
+ """验证常见 CHPX 样式、上下标、隐藏和删除修订状态。"""
+
+ grpprl = (
+ b"\x35\x08\x01" # bold
+ b"\x36\x08\x01" # italic
+ b"\x3e\x2a\x01" # underline
+ b"\x37\x08\x01" # strike
+ b"\x48\x2a\x01" # superscript
+ b"\x3c\x08\x01" # hidden
+ b"\x00\x08\x01" # deleted revision
+ )
+
+ style = apply_character_sprms(grpprl, DocCharStyle(), DocCharStyle())
+
+ assert style.bold and style.italic and style.underline and style.strike
+ assert style.superscript and not style.subscript
+ assert style.hidden and style.deleted
+
+
+def test_doc_exact_list_label_is_consumed_before_strict_projection() -> None:
+ """验证 Roman/复合列表标签优先于通用十进制编号且私有字段被删除。"""
+
+ blocks = [
+ {
+ "type": BlockType.LIST,
+ "attribute": "ordered",
+ "start": 4,
+ "ilevel": 0,
+ "content": [
+ {"type": BlockType.TEXT, "content": "item", "list_label": "IV."},
+ ],
+ }
+ ]
+
+ assert fix_office_list_blocks(blocks)[0]["content"] == [
+ {"type": BlockType.TEXT, "content": "IV. item"}
+ ]
+
+
+def test_doc_table_grid_materializes_colspan_and_rowspan() -> None:
+ """验证 Word table edge 网格能同时恢复横向和纵向合并。"""
+
+ from mineru.model.flash.doc.models import DocTableCellFormat, DocTableFormat
+
+ first = DocTableCell(blocks=[])
+ raw_rows = [
+ _RawTableRow(
+ [first, DocTableCell()],
+ DocTableFormat(
+ boundaries=(0, 100, 200),
+ cells=(
+ DocTableCellFormat(100, horizontal_first=True, vertical_first=True),
+ DocTableCellFormat(200, horizontal_continue=True),
+ ),
+ ),
+ ),
+ _RawTableRow(
+ [DocTableCell(), DocTableCell()],
+ DocTableFormat(
+ boundaries=(0, 100, 200),
+ cells=(
+ DocTableCellFormat(100, vertical_continue=True),
+ DocTableCellFormat(200),
+ ),
+ ),
+ ),
+ ]
+
+ rows = _materialize_table_rows(raw_rows, DocBudget())
+
+ assert rows[0].cells[0].col_span == 2
+ assert rows[0].cells[0].row_span == 2
+
+
+def test_doc_rejects_word95_encryption_rtf_and_missing_word_stream() -> None:
+ """验证不支持版本、加密、RTF 冒充和缺失核心 stream 使用稳定错误。"""
+
+ with pytest.raises(LegacyOfficeMalformedError, match="Word 95"):
+ DocModel().predict(BytesIO(build_doc("old\r", n_fib=0x0065)))
+ with pytest.raises(LegacyOfficeEncryptedError):
+ DocModel().predict(BytesIO(build_doc("secret\r", flags_extra=0x0100)))
+ with pytest.raises(LegacyOfficeMalformedError):
+ DocModel().predict(BytesIO(b"{\\rtf1 renamed}"))
+ with pytest.raises(LegacyOfficeMissingPartError):
+ DocModel().predict(BytesIO(_build_cfb([("1Table", b"table")])))
+
+
+def test_doc_budget_uses_stable_resource_limit(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 DOC 记录预算超过固定上限时使用共享错误类型。"""
+
+ import mineru.model.flash.doc.records as records
+
+ monkeypatch.setattr(records, "MAX_RECORDS", 1)
+ budget = records.DocBudget()
+ budget.charge()
+ with pytest.raises(LegacyOfficeResourceLimitError):
+ budget.charge()
+
+
[email protected](not _REAL_DOC.exists(), reason="real Office roundtrip fixture is local-only")
+def test_real_doc_recovers_sections_structure_and_sidecars(tmp_path: Path) -> None:
+ """验证真实 DOC 的 section、目录、表格、图片和严格 export 闭包。"""
+
+ middle, model = doc_analyze(_REAL_DOC.read_bytes(), file_suffix="doc")
+ counts = Counter(block.get("type") for page in model.pages for block in page)
+
+ assert len(model.pages) == len(middle.pages) == 3
+ assert counts[BlockType.DOC_TITLE] == 1
+ assert counts[BlockType.PARAGRAPH_TITLE] == 37
+ assert counts[BlockType.INDEX] == 1
+ assert counts[BlockType.LIST] == 5
+ assert counts[BlockType.TABLE] == 8
+ assert counts[BlockType.HEADER] == 4
+ assert counts[BlockType.FOOTER] == 1
+ assert counts[BlockType.IMAGE] >= 44
+
+ table_blocks = [
+ block
+ for page in middle.pages
+ for block in page.blocks
+ if isinstance(block, TableBlock)
+ ]
+ assert len(table_blocks) == 8
+ soups = [BeautifulSoup(block.content[0].content, "html.parser") for block in table_blocks]
+ assert sum(max(len(soup.find_all("table")) - 1, 0) for soup in soups) == 3
+ assert sum(len(soup.find_all("img")) for soup in soups) == 5
+ assert any(len(soup.find_all("tr")) == 39 for soup in soups)
+ assert any(
+ len(
+ [
+ cell
+ for cell in soup.find_all(["td", "th"])
+ if cell.has_attr("rowspan") or cell.has_attr("colspan")
+ ]
+ )
+ == 141
+ for soup in soups
+ )
+
+ export = middle.export(tmp_path / "export")
+ payload = export.middle_json.model_dump_json(exclude_none=True)
+ assert export.json_path.exists()
+ assert len(export.image_paths) >= 49
+ assert all(path.exists() and path.stat().st_size > 0 for path in export.image_paths)
+ assert "image_base64" not in payload
+ assert "data:image/" not in payload
+
+
+def test_doc_does_not_add_parser_or_legacy_model_routes() -> None:
+ """验证 DOC 仅接入 Flash Backend Analyze,不暴露 parser 或旧模型路径。"""
+
+ assert not (_PROJECT_ROOT / "mineru" / "parser" / "doc.py").exists()
+ assert not (_PROJECT_ROOT / "mineru" / "model" / "doc").exists()
diff --git a/tests/unittest/test_flash_legacy_ppt.py b/tests/unittest/test_flash_legacy_ppt.py
index 410bd7b8..87de6e7e 100644
--- a/tests/unittest/test_flash_legacy_ppt.py
+++ b/tests/unittest/test_flash_legacy_ppt.py
@@ -116,7 +116,7 @@ def test_ppt_encryption_marker_is_rejected_before_record_parsing() -> None:
ppt_parser.parse_ppt_document(b"not parsed", current_user=bytes(current_user))
[email protected]("file_suffix", ["doc"])
[email protected]("file_suffix", ["rtf"])
def test_unimplemented_legacy_suffixes_remain_rejected(file_suffix: str) -> None:
"""验证本阶段没有提前开放 DOC 严格类型或运行时入口。"""
diff --git a/tests/unittest/test_flash_office_models.py b/tests/unittest/test_flash_office_models.py
index 4a342b09..11aa7512 100644
--- a/tests/unittest/test_flash_office_models.py
+++ b/tests/unittest/test_flash_office_models.py
@@ -12,7 +12,8 @@ import pytest
import mineru.model.flash as flash_models
import mineru.model.flash.model as flat_model_module
-from mineru.model.flash import DocxModel, PdfModel, PptModel, PptxModel, XlsModel, XlsxModel
+from mineru.model.flash import DocModel, DocxModel, PdfModel, PptModel, PptxModel, XlsModel, XlsxModel
+from mineru.model.flash.doc import doc_converter as doc_converter_module
from mineru.model.flash.docx import docx_converter as docx_converter_module
from mineru.model.flash.docx import main as docx_main
from mineru.model.flash.pptx import main as pptx_main
@@ -59,6 +60,7 @@ def test_flash_office_model_conversion(
@pytest.mark.parametrize(
("model_class", "converter_module", "converter_name"),
[
+ (DocModel, doc_converter_module, "DocConverter"),
(DocxModel, docx_converter_module, "DocxConverter"),
(PptxModel, pptx_converter_module, "PptxConverter"),
(PptModel, ppt_converter_module, "PptConverter"),
@@ -153,6 +155,7 @@ def test_models_are_exported_from_flash_root() -> None:
assert flash_models.__all__ == [
"PdfModel",
+ "DocModel",
"DocxModel",
"PptModel",
"PptxModel",
@@ -160,6 +163,7 @@ def test_models_are_exported_from_flash_root() -> None:
"XlsxModel",
]
assert PdfModel is flat_model_module.PdfModel
+ assert DocModel is flat_model_module.DocModel
assert DocxModel is flat_model_module.DocxModel
assert PptxModel is flat_model_module.PptxModel
assert PptModel is flat_model_module.PptModel
@@ -170,6 +174,7 @@ def test_models_are_exported_from_flash_root() -> None:
@pytest.mark.parametrize(
("package_name", "model_name"),
[
+ ("mineru.model.flash.doc", "DocModel"),
("mineru.model.flash.docx", "DocxModel"),
("mineru.model.flash.pptx", "PptxModel"),
("mineru.model.flash.ppt", "PptModel"),
@@ -194,6 +199,7 @@ def test_importing_pdf_model_does_not_load_office_converters() -> None:
"from mineru.model.flash import PdfModel",
"assert PdfModel.__name__ == 'PdfModel'",
"assert 'mineru.model.flash.docx.docx_converter' not in sys.modules",
+ "assert 'mineru.model.flash.doc.doc_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",
@@ -215,6 +221,7 @@ def test_importing_pdf_model_does_not_load_office_converters() -> None:
@pytest.mark.parametrize(
"module_name",
[
+ "mineru.model.doc",
"mineru.model.docx",
"mineru.model.ppt",
"mineru.model.pptx",
diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.py
index e84923f0..981e8c86 100644
--- a/tests/unittest/test_pdf_analyze_visual_blocks.py
+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py
@@ -1250,7 +1250,7 @@ def test_aio_doc_analyze_propagates_sync_entrypoint_error(
asyncio.run(analyze.aio_doc_analyze(b"invalid-document"))
[email protected]("file_suffix", ["docx", "ppt", "pptx", "xls", "xlsx"])
[email protected]("file_suffix", ["doc", "docx", "ppt", "pptx", "xls", "xlsx"])
def test_doc_analyze_office_returns_model_json_without_pdf_processing(
monkeypatch: pytest.MonkeyPatch,
file_suffix: str,
@@ -1267,7 +1267,7 @@ def test_doc_analyze_office_returns_model_json_without_pdf_processing(
return source_model_list
selected_model.predict.side_effect = fake_office_predict
- for suffix in ("docx", "ppt", "pptx", "xls", "xlsx"):
+ for suffix in ("doc", "docx", "ppt", "pptx", "xls", "xlsx"):
model = selected_model if suffix == file_suffix else MagicMock()
model_factories[suffix] = MagicMock(return_value=model)
@@ -1340,7 +1340,7 @@ def test_doc_analyze_rejects_unsupported_suffix_before_resource_initialization(
"""验证非法后缀会在创建 PDF 文档或 Office 模型前直接报错。"""
pdf_document = MagicMock()
model_factories = {
- suffix: MagicMock() for suffix in ("docx", "ppt", "pptx", "xls", "xlsx")
+ suffix: MagicMock() for suffix in ("doc", "docx", "ppt", "pptx", "xls", "xlsx")
}
monkeypatch.setattr(pipeline, "PDFDocument", pdf_document)
monkeypatch.setattr(office, "_OFFICE_MODEL_MAP", model_factories)