Skip to content

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

feat: support legacy Office binary formats (doc/xls/ppt) end-to-end

jinzhenjc92e6f8abcc0
diff --git a/AGENTS.md b/AGENTS.md
new file mode 120000
index 00000000..681311eb
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1 @@
+CLAUDE.md
\ No newline at end of file
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 00000000..ff7cff4a
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,206 @@
+# MinerU 项目编码规范
+
+## 开发环境
+
+使用 **uv** 管理 Python 虚拟环境和依赖。
+
+```bash
+# 在项目根目录 MinerU-Repo 中创建虚拟环境
+uv venv .venv
+
+# 激活虚拟环境
+source .venv/bin/activate
+
+# 安装依赖
+uv pip install -e ".[core]"
+```
+
+运行 Python 代码须在项目根目录 `MinerU-Repo` 中执行:
+
+```bash
+.venv/bin/python -m mineru.path.to.submodule
+```
+
+## GitHub Issue / PR 处理规范
+
+处理 GitHub issue 时,commit message 和 PR body 中不要使用会导致 issue 在 merge 后自动关闭的关键词。
+
+禁止使用:
+- `fixes #123` / `fix #123`
+- `closes #123` / `close #123`
+- `resolves #123` / `resolve #123`
+
+需要关联 issue 时,使用不会自动关闭 issue 的表述:
+- `Refs #123`
+- `Related to #123`
+- `Issue: #123`
+
+## Import 规范
+
+mineru 模块内部子模块之间的引用统一使用 **relative import**,不使用 `import mineru.xxx` 形式的绝对导入。
+
+```python
+# 正确 — relative import
+from .base import DocumentParser
+from ..utils.enum_class import MakeMode
+
+# 错误 — 项目内不允许 absolute import 引用自身模块
+from mineru.api.base import DocumentParser
+from mineru.utils.enum_class import MakeMode
+```
+
+只引用外部第三方库时使用 absolute import(如 `from loguru import logger`)。
+
+## 格式化
+
+- 格式化工具:**ruff**
+- 保存时自动格式化:开启
+- 保存时自动 organize imports:开启
+- 行宽:**128**
+
+## Lint 规则
+
+启用的规则集:
+- **C** — 复杂度/编码规范 (mccabe, pycodestyle 约定等)
+- **E** — pycodestyle 错误
+- **F** — pyflakes 检查
+- **W** — pycodestyle 警告
+- **ANN** — flake8-annotations(类型注解)
+
+忽略的规则:
+- **C901** — 函数过复杂(允许必要的复杂函数)
+- **ANN002** — `*args` 不需要类型注解
+- **ANN003** — `**kwargs` 不需要类型注解
+- **ANN204** — 特殊方法(如 `__init__`)不需要返回类型注解
+- **ANN401** — 允许使用 `Any` 类型标注
+
+## 编程原则
+
+### 确定性优先
+
+agent 通过静态分析理解代码。避免运行时注册、猴子补丁、`globals()` 等动态模式,使用显式映射。
+
+```python
+# 差 — agent 无法静态追踪
+registry.register(MyParser)
+
+# 好 — 显式映射
+TIER_TO_EFFORT: dict[Tier, Effort] = {
+ "flash": "flash",
+ "basic": "low",
+ "standard": "medium",
+ "advanced": "high",
+}
+```
+
+### 入口一致性
+
+每个模块的 `__init__.py` 必须明确导出 `__all__`,让 agent 能快速获取模块边界。
+
+```python
+# mineru/api/__init__.py
+from .base import DocumentParser
+from .parse_result import ParseResult
+
+__all__ = ["DocumentParser", "ParseResult"]
+```
+
+### 类型优先
+
+公开函数必须有完整类型注解。避免 `**kwargs: Any` 透传内部配置。
+
+```python
+# 差 — agent 不知道合法参数
+def parse(path, **kwargs): ...
+
+# 好
+def parse(
+ path: str | Path,
+ *,
+ tier: Tier = "standard",
+ ocr_mode: Literal["auto", "txt", "ocr"] = "auto",
+ image_analysis: bool = True,
+ page_range: str = "",
+) -> ParseResult: ...
+```
+
+### 副作用隔离
+
+模块级别不得有隐式副作用(读取环境变量、创建目录、注册 handler 等)。`import` 只应定义符号。
+
+```python
+# 差 — import 时执行
+os.makedirs(DEFAULT_OUTPUT_DIR, exist_ok=True)
+
+# 好 — 使用时执行
+def parse(...):
+ Path(output_dir).mkdir(parents=True, exist_ok=True)
+```
+
+### 惰性加载
+
+对外 API 层的 `import` 不得触发重依赖(torch、transformers 等)。重依赖应在函数体内按需导入。
+
+```python
+class MinerUParser(DocumentParser):
+ def __init__(self, *, tier: Tier = "standard", **kwargs):
+ super().__init__(**kwargs)
+ from ..backend.analyze import doc_analyze # 惰性加载
+
+ self._analyze_fn = doc_analyze
+```
+
+## Middle JSON Schema 2.0 架构
+
+pr-5415 重构后,Middle JSON 已收敛为 schema 2.0 的统一结构,不再有 pipeline/vlm/office 三套独立实现。
+
+### 1. 统一分析入口
+
+`backend/analyze.py:doc_analyze()` 是 PDF 与 Office 文档的唯一公共入口,通过 `file_suffix` 路由到 `backend/analysis/pdf/pipeline.py:analyze_pdf` 或 `backend/analysis/office.py:analyze_office`,最终经 `backend/postprocess/pages.py:model_list_to_pages()` 产出统一 `pages`。`MinerUParser` 是 `DocumentParser` 的唯一实现,替代旧的 `PdfHybridParser`/`PdfFlashParser`/`DocxParser` 等。
+
+### 2. MiddleJson 顶层字段(schema 2.0)
+
+`mineru/types.py:MiddleJson` 严格定义:
+
+| 字段 | 类型 | 说明 |
+|------|------|------|
+| `pages` | `list[PageInfo]` | 严格按 `page_idx` 升序的页面数组 |
+| `is_full_document` | `bool` | 是否整本文档解析(空 `page_index_map` 时为 `True`) |
+| `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` | MinerU 版本号 |
+
+不再有 `_backend`/`_version_name`/`pdf_info`/`_ocr_enable`/`_vlm_ocr_enable` 等旧字段。
+
+### 2.1 ModelJson 严格容器
+
+`doc_analyze` 返回 `tuple[MiddleJson, ModelJson]`。`ModelJson` 持有 raw model-list(`pages: list[list[dict]]`)+ `page_index_map: list[int]`(空列表表示整本文档),并提供 `is_full_document`/`resolved_page_indices` 派生属性。`backend/postprocess/document.py:model_json_to_middle_json()` 是 ModelJson → MiddleJson 的唯一编排入口,内部调用 `model_json_to_pages()` + `apply_llm_aided_postprocess()`。
+
+### 3. PageInfo 结构
+
+`PageInfo` 只有两个字段:`page_idx: int`(从 0 起)+ `blocks: list[PageBlock]`。不再有 `page_size`/`preproc_blocks`/`para_blocks`/`discarded_blocks`/`images`/`tables`/`interline_equations`/`_layout_tree`/`layout_bboxes` 等字段——所有内容统一在 `blocks` 树里表达。
+
+### 4. Block 类型体系
+
+`mineru/types.py` 使用 Pydantic 模型替代旧 `Block`/`Line`/`Span` dataclass:
+
+- 叶子块(`TextBlock`/`EquationBlock`/`ImageBodyBlock` 等)直接持有 `content: str`
+- 视觉父块(`ImageBlock`/`TableBlock`/`ChartBlock`/`CodeBlock`)持有 `content: list[child blocks]`,子块包含唯一 body + 可选 caption/footnote
+- `BlockType.INTERLINE_EQUATION` 已重命名为 `BlockType.EQUATION`
+- 不再有 `Line`/`Span` 独立类型,行级和 span 级 bbox 不再生成
+
+### 5. 统一 render 入口
+
+`render/api.py:render(middle_json, output_format, options)` 是唯一渲染入口,支持:
+
+- `RenderFormat.MARKDOWN` → `render_markdown`
+- `RenderFormat.HTML` → `render_html`
+- `RenderFormat.DOCX` → `render_docx`
+- `RenderFormat.STRUCTURED_CONTENT` → `render_structured_content`
+
+`render/_internal/` 下按目标格式分目录组织共享逻辑(`common/`/`markdown/`/`html/`/`docx/`)。不再有 `pipeline_union_make`/`vlm_union_make`/`office_union_make` 三套逻辑,`content_list` 格式和 `render_content_list` 函数已删除。
+
+### 6. ParseResult 与 MiddleJson 的关系
+
+`ParseResult` 持有 `MiddleJson` 实例,`pages` 改为 property 委托给 `middle_json.pages`。`to_dict()`/`from_dict()` 处理 schema 2.0 与旧 1.0 payload 的双向兼容(1.0 经 `backend/postprocess/legacy_schema_adapter.py:legacy_page_to_model_list` 回推为 model_list 重走后处理)。
diff --git a/docs/en/reference/output_files.md b/docs/en/reference/output_files.md
index fa661aa6..6ba08bdb 100644
--- a/docs/en/reference/output_files.md
+++ b/docs/en/reference/output_files.md
@@ -115,7 +115,8 @@ The following sections provide detailed descriptions of each file's purpose and
| Field Name | Type | Description |
|------------|------|-------------|
| `pages` | `list[PageInfo]` | Array of parsing results for each page, strictly increasing by `page_idx` |
-| `file_suffix` | `string` | Input file type: `pdf`, `docx`, `pptx`, or `xlsx` |
+| `is_full_document` | `bool` | Whether the input is a full document (empty `page_index_map`) |
+| `file_suffix` | `string` | Input file type: `pdf`, `doc`, `docx`, `ppt`, `pptx`, `xls`, or `xlsx` |
| `effort` | `string` | Analysis effort: `flash`, `low`, `medium`, `high`, or `xhigh` |
| `parse_mode` | `string` | Parse mode: `txt` or `ocr` |
| `mineru_version` | `string` | MinerU version number |
diff --git a/docs/en/usage/quick_usage.md b/docs/en/usage/quick_usage.md
index 43aa3de0..8ce08de0 100644
--- a/docs/en/usage/quick_usage.md
+++ b/docs/en/usage/quick_usage.md
@@ -13,7 +13,7 @@ MinerU has built-in command line tools that allow users to quickly use MinerU fo
mineru -p <input_path> -o <output_path>
```
> [!TIP]
->- `<input_path>`: Local `PDF` / image / `DOCX` / `PPTX` / `XLSX` file or directory
+>- `<input_path>`: Local `PDF` / image / `DOC`/`DOCX` / `PPT`/`PPTX` / `XLS`/`XLSX` file or directory
>- `<output_path>`: Output directory
>- Without `--api-url`, the CLI launches a temporary local `mineru-api`
>- With `--api-url`, the CLI connects to an existing local or remote FastAPI service directly
diff --git a/docs/zh/reference/output_files.md b/docs/zh/reference/output_files.md
index e95c2d6e..96e85a6b 100644
--- a/docs/zh/reference/output_files.md
+++ b/docs/zh/reference/output_files.md
@@ -115,7 +115,8 @@
| 字段名 | 类型 | 说明 |
|--------|------|------|
| `pages` | `list[PageInfo]` | 每一页的解析结果数组,按 `page_idx` 严格升序 |
-| `file_suffix` | `string` | 输入文件类型:`pdf`、`docx`、`pptx` 或 `xlsx` |
+| `is_full_document` | `bool` | 是否整本文档解析(`page_index_map` 为空时为 `True`) |
+| `file_suffix` | `string` | 输入文件类型:`pdf`、`doc`、`docx`、`ppt`、`pptx`、`xls` 或 `xlsx` |
| `effort` | `string` | 分析强度:`flash`、`low`、`medium`、`high` 或 `xhigh` |
| `parse_mode` | `string` | 解析模式:`txt` 或 `ocr` |
| `mineru_version` | `string` | MinerU 版本号 |
diff --git a/docs/zh/usage/quick_usage.md b/docs/zh/usage/quick_usage.md
index 907d90f2..d70a0033 100644
--- a/docs/zh/usage/quick_usage.md
+++ b/docs/zh/usage/quick_usage.md
@@ -13,7 +13,7 @@ MinerU内置了命令行工具,用户可以通过命令行快速使用MinerU
mineru -p <input_path> -o <output_path>
```
> [!TIP]
-> - `<input_path>`:本地 `PDF` / 图片 / `DOCX` / `PPTX` / `XLSX` 文件或目录
+> - `<input_path>`:本地 `PDF` / 图片 / `DOC`/`DOCX` / `PPT`/`PPTX` / `XLS`/`XLSX` 文件或目录
> - `<output_path>`:输出目录
> - 未传 `--api-url` 时,CLI 会自动拉起本地临时 `mineru-api`
> - 传入 `--api-url` 时,CLI 会直连远端或已有本地 FastAPI 服务
diff --git a/mineru/doclib/background/compaction.py b/mineru/doclib/background/compaction.py
index c59fca13..f44cb374 100644
--- a/mineru/doclib/background/compaction.py
+++ b/mineru/doclib/background/compaction.py
@@ -25,7 +25,7 @@ def _normalize_batch_pages(batch_payload: dict[str, Any]) -> list[dict[str, Any]
2.0 batch:page 只有 page_idx + blocks,直接用。
1.0 batch:page 含 preproc_blocks/para_blocks/discarded_blocks/page_size,
- 走 legacy_schema_adapter 回推为 raw model_list,再走 model_list_to_pages 转 2.0。
+ 走 legacy_schema_adapter 回推为 raw model_list,再走 model_json_to_pages 转 2.0。
"""
raw_pages = batch_payload.get("pages", [])
if batch_payload.get("schema_version") == MIDDLE_JSON_SCHEMA_VERSION:
@@ -33,12 +33,27 @@ def _normalize_batch_pages(batch_payload: dict[str, Any]) -> list[dict[str, Any]
# 1.0 batch:走 legacy 适配器转换
from ...backend.postprocess.legacy_schema_adapter import legacy_page_to_model_list
- from ...backend.postprocess.pages import model_list_to_pages
+ from ...backend.postprocess.pages import model_json_to_pages
+ from ...parser.base import (
+ _LEGACY_DEFAULT_EFFORT,
+ _LEGACY_DEFAULT_FILE_SUFFIX,
+ _LEGACY_DEFAULT_PARSE_MODE,
+ )
+ from ...types import ModelJson
+ from ...version import __version__ as mineru_version
model_list = [legacy_page_to_model_list(page) for page in raw_pages]
if not model_list or not any(model_list):
return []
- pages = model_list_to_pages(model_list)
+ model_json = ModelJson(
+ pages=model_list,
+ page_index_map=[],
+ file_suffix=_LEGACY_DEFAULT_FILE_SUFFIX,
+ effort=_LEGACY_DEFAULT_EFFORT,
+ parse_mode=_LEGACY_DEFAULT_PARSE_MODE,
+ mineru_version=mineru_version,
+ )
+ pages = model_json_to_pages(model_json)
return [page.to_dict() for page in pages]
diff --git a/mineru/doclib/core/file_io.py b/mineru/doclib/core/file_io.py
index 2167a4d9..085fe82b 100644
--- a/mineru/doclib/core/file_io.py
+++ b/mineru/doclib/core/file_io.py
@@ -200,4 +200,36 @@ async def _extract_office_meta(filepath: str, ext: str, result: dict) -> None:
if wb is not None:
wb.close()
+ elif ext in ("doc", "ppt", "xls"):
+ _extract_legacy_office_meta(filepath, result)
+
await asyncio.to_thread(_extract)
+
+
+def _extract_legacy_office_meta(filepath: str, result: dict) -> None:
+ """用 olefile 提取 OLE2 SummaryInformation 属性。
+
+ 旧 Office 二进制格式(doc/xls/ppt)无 python-docx/pptx/openpyxl 支持。
+ page_count 无法从 OLE 属性获取:doc 是 reflow 文档,xls workbook 无页数概念,
+ ppt 幻灯片数需深度解析 PowerPoint Document stream,由 parse_svc 默认值 1 兜底。
+ """
+ try:
+ import olefile # type: ignore[import-untyped]
+ except ImportError:
+ return
+ ole = None
+ try:
+ ole = olefile.OleFileIO(filepath)
+ except Exception as exc:
+ raise MetadataExtractionError("open_failed", str(exc) or "Failed to open OLE2 document") from exc
+ try:
+ meta = ole.get_metadata()
+ result["title"] = meta.title or None
+ result["author"] = meta.author or None
+ result["subject"] = meta.subject or None
+ result["keywords"] = meta.keywords or None
+ except Exception as exc:
+ raise MetadataExtractionError("read_metadata_failed", str(exc) or "Failed to read OLE2 metadata") from exc
+ finally:
+ if ole is not None:
+ ole.close()
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index 38e70f18..c67677c1 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -17,7 +17,6 @@ from ...errors import InvalidRequestError, MineruError
from ...filetypes import (
IMAGE_EXTENSIONS,
INGESTIBLE_EXTENSIONS,
- LEGACY_OFFICE_EXTENSION_UPGRADES,
OFFICE_EXTENSIONS,
TEXT_EXTENSIONS,
TIERED_PARSE_EXTENSIONS,
@@ -586,9 +585,9 @@ class ParseService:
# Office: no page_count → default to 1
page_count = metadata["page_count"]
if page_count is None:
- if ext in ("docx",):
+ if ext in ("doc", "docx"):
page_count = 1 # reflow docs
- elif ext in ("pptx", "xlsx"):
+ elif ext in ("ppt", "pptx", "xls", "xlsx"):
page_count = 1 # will be updated by metadata extraction
now = _now_ms()
@@ -1633,9 +1632,5 @@ def _safe_filename(page_range: str, done_at: int) -> str:
def _unsupported_file_type_message(ext_or_name: str) -> str:
- ext = ext_or_name.lower().lstrip(".")
- upgrade_ext = LEGACY_OFFICE_EXTENSION_UPGRADES.get(ext)
- if upgrade_ext:
- return f".{ext} files are not supported; please convert to .{upgrade_ext}."
display = ext_or_name if ext_or_name.startswith(".") else Path(ext_or_name).name
return f"File type is not supported for parsing: {display}"
diff --git a/mineru/filetypes.py b/mineru/filetypes.py
index 984ae342..614c64aa 100644
--- a/mineru/filetypes.py
+++ b/mineru/filetypes.py
@@ -6,10 +6,8 @@ from .types import QUALITY_TIERS, Tier, validate_tier
# ── file types ─────────────────────────────────────────────────────
-# Unsupported legacy Office formats:
-# "doc",
-# "xls",
-# "ppt",
+# Legacy Office binary formats (Word 97–2003 / Excel 97–2003 / PowerPoint 97–2003)
+# are natively parsed by mineru.model.flash.{doc,xls,ppt} converters.
# Unsupported document/e-book/archive-like formats:
# "epub",
# "key",
@@ -27,7 +25,7 @@ PDF_EXTENSIONS: frozenset[str] = frozenset({"pdf"})
IMAGE_EXTENSIONS: frozenset[str] = frozenset({"png", "jpg", "jpeg", "webp", "gif", "bmp", "tiff", "jp2"})
-OFFICE_EXTENSIONS: frozenset[str] = frozenset({"docx", "pptx", "xlsx"})
+OFFICE_EXTENSIONS: frozenset[str] = frozenset({"doc", "docx", "ppt", "pptx", "xls", "xlsx"})
HTML_EXTENSIONS: frozenset[str] = frozenset({"html", "htm"})
@@ -62,8 +60,11 @@ TEXT_FILE_TYPES: frozenset[str] = frozenset(FILE_TYPE_BY_EXTENSION[ext] for ext
MIME_TYPE_BY_EXTENSION: dict[str, str] = {
"pdf": "application/pdf",
+ "doc": "application/msword",
"docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "ppt": "application/vnd.ms-powerpoint",
"pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ "xls": "application/vnd.ms-excel",
"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"html": "text/html",
"htm": "text/html",
@@ -77,12 +78,6 @@ MIME_TYPE_BY_EXTENSION: dict[str, str] = {
"tiff": "image/tiff",
}
-LEGACY_OFFICE_EXTENSION_UPGRADES: dict[str, str] = {
- "doc": "docx",
- "ppt": "pptx",
- "xls": "xlsx",
-}
-
def normalize_parse_extension(path_or_ext: str | Path) -> str:
text = str(path_or_ext)
diff --git a/mineru/parser/base.py b/mineru/parser/base.py
index b41a8c79..d620332a 100644
--- a/mineru/parser/base.py
+++ b/mineru/parser/base.py
@@ -18,7 +18,7 @@ from ..utils.pdf_document import PDFDocument
MIDDLE_JSON_SCHEMA_VERSION: str = "2.0"
_LEGACY_SCHEMA_VERSION: str = "1.0"
-_LEGACY_DEFAULT_FILE_SUFFIX: Literal["pdf", "docx", "pptx", "xlsx"] = "pdf"
+_LEGACY_DEFAULT_FILE_SUFFIX: Literal["pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx"] = "pdf"
_LEGACY_DEFAULT_EFFORT: Literal["flash", "low", "medium", "high", "xhigh"] = "medium"
_LEGACY_DEFAULT_PARSE_MODE: Literal["txt", "ocr"] = "txt"
_PDF_RETAINED_PAGE_INDICES_KEY = "_pdf_retained_page_indices"
@@ -101,15 +101,27 @@ class ParseResult:
raise ValueError("ParseResult JSON must contain a list field named pages.")
from ..backend.postprocess.legacy_schema_adapter import legacy_page_to_model_list
- from ..backend.postprocess.pages import model_list_to_pages
+ from ..backend.postprocess.pages import model_json_to_pages
+ from ..types import ModelJson
+ from ..version import __version__ as mineru_version
model_list = [legacy_page_to_model_list(page) for page in raw_pages]
- pages = model_list_to_pages(model_list) if model_list else []
-
- from ..version import __version__ as mineru_version
+ if model_list:
+ model_json = ModelJson(
+ pages=model_list,
+ page_index_map=[],
+ file_suffix=_LEGACY_DEFAULT_FILE_SUFFIX,
+ effort=_LEGACY_DEFAULT_EFFORT,
+ parse_mode=_LEGACY_DEFAULT_PARSE_MODE,
+ mineru_version=mineru_version,
+ )
+ pages = model_json_to_pages(model_json)
+ else:
+ pages = []
return MiddleJson(
pages=pages,
+ is_full_document=True,
file_suffix=_LEGACY_DEFAULT_FILE_SUFFIX,
effort=_LEGACY_DEFAULT_EFFORT,
parse_mode=_LEGACY_DEFAULT_PARSE_MODE,
diff --git a/mineru/parser/mineru_parser.py b/mineru/parser/mineru_parser.py
index f0214989..75d0e775 100644
--- a/mineru/parser/mineru_parser.py
+++ b/mineru/parser/mineru_parser.py
@@ -12,7 +12,7 @@ from typing import Any, Literal
from ..backend.analyze import aio_doc_analyze, doc_analyze
from ..errors import InvalidRequestError
from ..filetypes import IMAGE_EXTENSIONS
-from ..types import MiddleJson, PageInfo, Tier
+from ..types import MiddleJson, ModelJson, PageInfo, Tier
from ..utils.backend_options import effort_for_tier
from .base import DocumentParser, ParseResult
@@ -20,8 +20,8 @@ logger = logging.getLogger(__name__)
_Effort = Literal["flash", "low", "medium", "high", "xhigh"]
_ParseMode = Literal["auto", "txt", "ocr"]
-_FileSuffix = Literal["pdf", "docx", "pptx", "xlsx"]
-_SUPPORTED_SUFFIXES: frozenset[str] = frozenset({"pdf", "docx", "pptx", "xlsx"})
+_FileSuffix = Literal["pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx"]
+_SUPPORTED_SUFFIXES: frozenset[str] = frozenset({"pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx"})
@dataclass
@@ -94,7 +94,7 @@ class MinerUParser(DocumentParser):
broken_page_indices=prepared.broken_page_indices,
)
- def _run_analysis(self, prepared: _PreparedInput) -> tuple[MiddleJson, Any]:
+ def _run_analysis(self, prepared: _PreparedInput) -> tuple[MiddleJson, ModelJson]:
return doc_analyze(
prepared.file_bytes,
effort=self.effort,
@@ -104,7 +104,7 @@ class MinerUParser(DocumentParser):
file_suffix=prepared.file_suffix,
)
- async def _arun_analysis(self, prepared: _PreparedInput) -> tuple[MiddleJson, Any]:
+ async def _arun_analysis(self, prepared: _PreparedInput) -> tuple[MiddleJson, ModelJson]:
return await aio_doc_analyze(
prepared.file_bytes,
effort=self.effort,
diff --git a/mineru/utils/guess_suffix_or_lang.py b/mineru/utils/guess_suffix_or_lang.py
index 2ec027f8..a4feb6a6 100644
--- a/mineru/utils/guess_suffix_or_lang.py
+++ b/mineru/utils/guess_suffix_or_lang.py
@@ -9,6 +9,7 @@ from magika import Magika
DEFAULT_LANG = "txt"
PDF_SIG_BYTES = b"%PDF"
+OLE2_SIG_BYTES = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
OOXML_ROOT_RELS = "_rels/.rels"
OOXML_CONTENT_TYPES = "[Content_Types].xml"
OOXML_PACKAGE_REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
@@ -19,6 +20,14 @@ OOXML_MAIN_CONTENT_TYPES = {
("application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"): "pptx",
("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"): "xlsx",
}
+# OLE2 compound file 内部 stream 名 → 旧 Office 格式后缀
+# doc: WordDocument stream;xls: Workbook 或 Book stream;ppt: PowerPoint Document stream
+OLE2_STREAM_SUFFIX_MAP: dict[str, str] = {
+ "WordDocument": "doc",
+ "Workbook": "xls",
+ "Book": "xls",
+ "PowerPoint Document": "ppt",
+}
magika = Magika()
@@ -155,11 +164,46 @@ def _guess_ooxml_suffix_by_path(file_path: Path) -> str | None:
return None
+def _guess_ole2_suffix_by_bytes(file_bytes: bytes) -> str | None:
+ """用 OLE2 magic + olefile 内部 stream 区分 doc/xls/ppt。
+
+ olefile 是纯 Python 库且已是核心依赖(mineru.model.flash.legacy_office 使用)。
+ 在 OOXML 识别失败后、Magika 兜底前插入此层,避免 Magika 对 OLE2 返回 unknown。
+ """
+ if len(file_bytes) < 8 or file_bytes[:8] != OLE2_SIG_BYTES:
+ return None
+ try:
+ import olefile # type: ignore[import-untyped]
+
+ with olefile.OleFileIO(BytesIO(file_bytes)) as ole:
+ for stream_name in ole.listdir(streams=True):
+ name = "/".join(stream_name)
+ suffix = OLE2_STREAM_SUFFIX_MAP.get(name)
+ if suffix:
+ return suffix
+ except Exception:
+ return None
+ return None
+
+
+def _guess_ole2_suffix_by_path(file_path: Path) -> str | None:
+ """从文件路径读取 OLE2 容器并识别旧 Office 格式。"""
+ try:
+ with open(file_path, "rb") as f:
+ return _guess_ole2_suffix_by_bytes(f.read())
+ except OSError:
+ return None
+
+
def guess_suffix_by_bytes(file_bytes: bytes, file_path: str | None = None) -> str:
ooxml_suffix = _guess_ooxml_suffix_by_bytes(file_bytes)
if ooxml_suffix:
return ooxml_suffix
+ ole2_suffix = _guess_ole2_suffix_by_bytes(file_bytes)
+ if ole2_suffix:
+ return ole2_suffix
+
suffix = magika.identify_bytes(file_bytes).prediction.output.label
if (
file_path
@@ -179,6 +223,10 @@ def guess_suffix_by_path(file_path: str | Path) -> str:
if ooxml_suffix:
return ooxml_suffix
+ ole2_suffix = _guess_ole2_suffix_by_path(file_path)
+ if ole2_suffix:
+ return ole2_suffix
+
suffix = magika.identify_path(file_path).prediction.output.label
if suffix in ["ai", "html"] and file_path.suffix.lower() in [".pdf"]:
try:
diff --git a/tests/unittest/test_filetypes.py b/tests/unittest/test_filetypes.py
new file mode 100644
index 00000000..643db9c8
--- /dev/null
+++ b/tests/unittest/test_filetypes.py
@@ -0,0 +1,33 @@
+from __future__ import annotations
+
+from mineru.filetypes import (
+ FILE_TYPE_BY_EXTENSION,
+ INGESTIBLE_EXTENSIONS,
+ MIME_TYPE_BY_EXTENSION,
+ OFFICE_EXTENSIONS,
+ PARSEABLE_EXTENSIONS,
+ is_flash_only_parse_extension,
+)
+
+
+def test_office_extensions_includes_legacy_binary_formats() -> None:
+ assert {"doc", "docx", "ppt", "pptx", "xls", "xlsx"} <= OFFICE_EXTENSIONS
+
+
+def test_legacy_office_extensions_are_parseable_and_ingestible() -> None:
+ for ext in ("doc", "ppt", "xls"):
+ assert ext in PARSEABLE_EXTENSIONS
+ assert ext in INGESTIBLE_EXTENSIONS
+ assert is_flash_only_parse_extension(ext)
+
+
+def test_file_type_by_extension_maps_legacy_office_to_self() -> None:
+ assert FILE_TYPE_BY_EXTENSION["doc"] == "doc"
+ assert FILE_TYPE_BY_EXTENSION["ppt"] == "ppt"
+ assert FILE_TYPE_BY_EXTENSION["xls"] == "xls"
+
+
+def test_mime_type_by_extension_covers_legacy_office() -> None:
+ assert MIME_TYPE_BY_EXTENSION["doc"] == "application/msword"
+ assert MIME_TYPE_BY_EXTENSION["ppt"] == "application/vnd.ms-powerpoint"
+ assert MIME_TYPE_BY_EXTENSION["xls"] == "application/vnd.ms-excel"
diff --git a/tests/unittest/test_guess_suffix_ole2.py b/tests/unittest/test_guess_suffix_ole2.py
new file mode 100644
index 00000000..429be9e0
--- /dev/null
+++ b/tests/unittest/test_guess_suffix_ole2.py
@@ -0,0 +1,26 @@
+from __future__ import annotations
+
+from mineru.utils.guess_suffix_or_lang import (
+ _guess_ole2_suffix_by_bytes,
+ guess_suffix_by_bytes,
+)
+
+# 最小 OLE2 compound file header(512 bytes header + 不可读 stream 目录)
+# 用于测试 magic bytes 检查;olefile 打开后会因结构不完整返回 None
+_OLE2_HEADER_ONLY = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" + b"\x00" * 512
+
+
+def test_guess_ole2_suffix_returns_none_for_non_ole2_bytes() -> None:
+ assert _guess_ole2_suffix_by_bytes(b"%PDF-1.4 test") is None
+ assert _guess_ole2_suffix_by_bytes(b"plain text") is None
+
+
+def test_guess_ole2_suffix_returns_none_for_ole2_without_known_streams() -> None:
+ """OLE2 magic 但无 WordDocument/Workbook/PowerPoint Document stream 时返回 None。"""
+ assert _guess_ole2_suffix_by_bytes(_OLE2_HEADER_ONLY) is None
+
+
+def test_guess_suffix_by_bytes_falls_through_to_magika_for_unknown_ole2() -> None:
+ """OLE2 magic 但无已知 stream 时,交给 Magika 兜底(不返回 unknown_ole2)。"""
+ suffix = guess_suffix_by_bytes(_OLE2_HEADER_ONLY)
+ assert isinstance(suffix, str)
diff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.py
index b8cab111..c60c77af 100644
--- a/tests/unittest/test_parse_result_contract.py
+++ b/tests/unittest/test_parse_result_contract.py
@@ -72,6 +72,7 @@ def test_parse_result_from_dict_restores_pages() -> None:
],
)
],
+ is_full_document=True,
file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__,
)
)
@@ -85,7 +86,7 @@ def test_parse_result_from_dict_restores_pages() -> None:
def test_parse_result_to_dict_includes_schema_version_without_meta() -> None:
- result = ParseResult(middle_json=MiddleJson(pages=[PageInfo(page_idx=0)], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))
+ result = ParseResult(middle_json=MiddleJson(pages=[PageInfo(page_idx=0)], is_full_document=True, file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))
payload = result.to_dict()
@@ -124,12 +125,14 @@ def test_parse_result_from_json_restores_pages() -> None:
restored = ParseResult.from_json(json.dumps(data))
assert restored.to_dict() == ParseResult.from_dict(data).to_dict()
+ assert restored.middle_json.is_full_document is True
+ assert restored.middle_json.file_suffix == "pdf"
def test_parse_result_export_pages_returns_defensive_copy_from_cache() -> None:
img_bytes = b"defensive-table-image"
page, image_cache, inline_image = _table_page_with_cached_inline_image(img_bytes)
- result = ParseResult(middle_json=MiddleJson(pages=[page], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__), _image_cache=image_cache)
+ result = ParseResult(middle_json=MiddleJson(pages=[page], is_full_document=True, file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__), _image_cache=image_cache)
first_export = result.export_pages()
first_export[0].blocks[0].content[0].content = "mutated by caller"
@@ -148,7 +151,7 @@ def test_parse_result_export_rewrites_inline_table_base64_images() -> None:
img_bytes = b"table-image"
page, image_cache, inline_image = _table_page_with_cached_inline_image(img_bytes)
- result = ParseResult(middle_json=MiddleJson(pages=[page], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__), _image_cache=image_cache)
+ result = ParseResult(middle_json=MiddleJson(pages=[page], is_full_document=True, file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__), _image_cache=image_cache)
images = result.images()
exported_page = result.export_pages()[0]
exported_body = exported_page.blocks[0].content[0]