Skip to content

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

Enhance document metadata extraction by integrating source properties and improving error handling

myhloli4861ce08e973
diff --git a/docs/next/metadata.md b/docs/next/metadata.md
new file mode 100644
index 00000000..af3174e0
--- /dev/null
+++ b/docs/next/metadata.md
@@ -0,0 +1,24 @@
+# 原始文档元数据
+
+文件格式元数据的唯一提取实现归 DocVortex。Doclib 入库通过 `docvortex.extract_metadata()`
+获取标题、作者、主题、关键词、语言和计数;MinerU 各解析入口使用相同接口,并通过
+Model/Middle JSON 的可选 `metadata.document` 传递完整属性。
+
+源属性在 PDF 选页重写之前保存;其中 `page_count_kind` 区分物理页、声明布局页和结构单位,
+不应把选页数量、幻灯片数或工作表数当作整本 PDF 页数。Doclib 调度页数保留原有产品语义。
+图片转 PDF 不在本次范围内提取 EXIF,也不将转换器生成的信息冒充原图属性。
+
+`metadata.producer` 仍是 JSON 生产者,原文件生成软件位于 `metadata.document`。
+JSON 协议保持 2.0;旧数据缺少新字段仍可读取,但旧版严格读取器需要先升级。
+完整扩展信息保存在解析 JSON 中,不增加数据库列或详情 API 字段,不强制回填旧缓存。
+
+Doclib 仅负责数据库映射、截断和调度。作者以 `; ` 拼接,关键词以 `, ` 拼接,语言取首项。
+解析完成后非空源属性更新现有列及 FTS 标题作者,不按推理 tier 判断源属性质量,也不清空旧值。
+元数据不同的缓存批次保持原有不合并规则。
+
+本次移除 17 项已经归属 DocVortex 的基础直接依赖;这些包仍随 DocVortex 安装。
+测试专用的 pypdf、reportlab、lxml 在 test extra 中显式声明。tokenizers 仍是基础依赖,
+因为无 Transformers 的 ONNX 公式识别会直接使用它。
+
+发布顺序:先验证并发布包含公共接口的 DocVortex 0.2.5,再将 MinerU 最低版本要求提升到该版本。
+本地集成验收使用两边构建的 wheel,不能用旧版 DocVortex 验证新调用链。
diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.py
index d90eb962..e02e5446 100644
--- a/mineru/backend/analyze.py
+++ b/mineru/backend/analyze.py
@@ -2,8 +2,8 @@
"""统一 PDF、EPUB、HTML、OFD、CSV 与 Office/RTF 文档分析的稳定公共门面。"""
from __future__ import annotations
-from docvortex.schema import DocumentMetadata, Producer
-from ..integrations.docvortex import build_metadata
+from docvortex.schema import DocumentMetadata, DocumentProperties, Producer
+from ..integrations.docvortex import build_metadata, read_source_properties
import asyncio
from typing import cast
@@ -37,6 +37,7 @@ def doc_analyze(
file_suffix: FileSuffix = "pdf",
source_context: HtmlSourceContext | None = None,
vlm_config: VlmConfig | None = None,
+ source_properties: DocumentProperties | None = None,
) -> tuple[MiddleJson, ModelJson]:
"""生产严格 ModelJson,并在统一边界构造严格 MiddleJson。"""
if file_suffix not in FILE_SUFFIXES:
@@ -46,6 +47,9 @@ def doc_analyze(
if effort not in _SUPPORTED_ANALYZE_EFFORTS:
raise ValueError(f"Unsupported analyze effort: {effort}")
+ if source_properties is None:
+ source_properties = read_source_properties(file_bytes, file_suffix, source_context)
+
if file_suffix == "pdf":
from .analysis.pdf.pipeline import analyze_pdf
@@ -81,7 +85,11 @@ def doc_analyze(
model_json = ModelJson(
pages=result.model_list,
page_index_map=page_index_map or [],
- metadata=DocumentMetadata(file_suffix=file_suffix, producer=Producer(name="mineru", version=mineru_version)),
+ metadata=DocumentMetadata(
+ file_suffix=file_suffix,
+ producer=Producer(name="mineru", version=mineru_version),
+ document=source_properties.model_copy(deep=True),
+ ),
extensions=build_metadata(effort=result.effort, parse_mode=result.parse_mode),
)
from .postprocess.document import model_json_to_middle_json
@@ -102,6 +110,7 @@ async def aio_doc_analyze(
file_suffix: FileSuffix = "pdf",
source_context: HtmlSourceContext | None = None,
vlm_config: VlmConfig | None = None,
+ source_properties: DocumentProperties | None = None,
) -> tuple[MiddleJson, ModelJson]:
"""在线程中执行统一文档分析,避免阻塞调用方事件循环。"""
return await asyncio.to_thread(
@@ -114,4 +123,5 @@ async def aio_doc_analyze(
file_suffix=file_suffix,
source_context=source_context,
vlm_config=vlm_config,
+ source_properties=source_properties,
)
diff --git a/mineru/doclib/core/file_io.py b/mineru/doclib/core/file_io.py
index 34648804..0c2ecc72 100644
--- a/mineru/doclib/core/file_io.py
+++ b/mineru/doclib/core/file_io.py
@@ -8,22 +8,10 @@ import os
from dataclasses import dataclass
from pathlib import Path
-from ...filetypes import CSV_EXTENSIONS, EPUB_EXTENSIONS, ODF_EXTENSIONS, OFD_EXTENSIONS, OFFICE_EXTENSIONS
-from docvortex.document.pdf.document import PDFDocument
-
-# Optional office doc support
-try:
- from docx import Document
-except ImportError:
- Document = None # type: ignore[assignment]
-try:
- from pptx import Presentation # type: ignore[reportMissingImports]
-except ImportError:
- Presentation = None # type: ignore[assignment]
-try:
- from openpyxl import load_workbook
-except ImportError:
- load_workbook = None # type: ignore[assignment]
+from typing import TypedDict
+
+from docvortex.schema import DocumentMetadata
+from ...filetypes import TEXT_EXTENSIONS, IMAGE_EXTENSIONS
# Metadata truncation limits
TRUNC_TITLE = 500
@@ -34,6 +22,7 @@ TRUNC_KEYWORDS = 1000
class MetadataExtractionError(Exception):
def __init__(self, code: str, message: str) -> None:
+ """保留 Doclib 的公开错误码和消息。"""
super().__init__(message)
self.code = code
@@ -73,227 +62,85 @@ async def get_file_stat(filepath: str) -> FileStat:
# ── metadata extraction ────────────────────────────────────────────
-async def extract_metadata(filepath: str) -> dict:
- """Extract metadata from file. Returns dict with keys matching docs table columns.
- All string fields are protectively truncated."""
- ext = Path(filepath).suffix.lower().lstrip(".")
+class DoclibMetadata(TypedDict):
+ """映射现有数据库列及入库阶段的属性诊断。"""
+
+ page_count: int | None
+ title: str | None
+ author: str | None
+ subject: str | None
+ keywords: str | None
+ language: str | None
+ is_image_based: int
+ error_code: str | None
+ error_msg: str | None
- result = {
+
+def metadata_to_doclib(metadata: DocumentMetadata | None) -> DoclibMetadata:
+ """将共享源属性投影为产品字段,截断仅发生在数据库边界。"""
+ result: DoclibMetadata = {
"page_count": None,
"title": None,
"author": None,
"subject": None,
"keywords": None,
+ "language": None,
"is_image_based": 0,
+ "error_code": None,
+ "error_msg": None,
}
-
- if ext == "pdf":
- await _extract_pdf_meta(filepath, result)
-
- elif ext in OFD_EXTENSIONS:
- await _extract_ofd_meta(filepath, result)
-
- elif ext in OFFICE_EXTENSIONS:
- await _extract_office_meta(filepath, ext, result)
-
- elif ext in CSV_EXTENSIONS:
+ if metadata is None or metadata.document is None:
+ return result
+ properties = metadata.document
+ result.update(
+ title=properties.title,
+ author="; ".join(properties.authors) or None,
+ subject=properties.subject,
+ keywords=", ".join(properties.keywords) or None,
+ language=properties.languages[0] if properties.languages else None,
+ page_count=properties.page_count,
+ )
+ if metadata.file_suffix in {"doc", "docx", "rtf"}:
+ # 源文件声明的布局页数不改变重排版文档的既有调度口径。
result["page_count"] = 1
-
- elif ext in EPUB_EXTENSIONS:
- await _extract_epub_meta(filepath, result)
-
- # truncate all string fields
- for field, limit in [
+ elif metadata.file_suffix in {"odt", "ods", "odp"}:
+ result["page_count"] = result["page_count"] or 1
+ for field, limit in (
("title", TRUNC_TITLE),
("author", TRUNC_AUTHOR),
("subject", TRUNC_SUBJECT),
("keywords", TRUNC_KEYWORDS),
- ]:
- val = result.get(field)
- if val and len(val) > limit:
- result[field] = val[:limit]
-
+ ):
+ value = result[field]
+ if isinstance(value, str):
+ result[field] = value[:limit]
return result
-# ── PDF metadata ───────────────────────────────────────────────────
-
-
-async def _extract_pdf_meta(filepath: str, result: dict) -> None:
- def _extract() -> None:
- pdf_doc = None
- try:
- try:
- pdf_doc = PDFDocument(filepath)
- result["page_count"] = pdf_doc.page_count
- except Exception as exc:
- raise MetadataExtractionError("open_failed", str(exc) or "Failed to open document") from exc
-
- try:
- meta = pdf_doc.metadata
- except Exception as exc:
- raise MetadataExtractionError("read_metadata_failed", str(exc) or "Failed to read document metadata") from exc
-
- try:
- result["title"] = meta.get("Title") or None
- result["author"] = meta.get("Author") or None
- result["subject"] = meta.get("Subject") or None
- result["keywords"] = meta.get("Keywords") or None
- except Exception as exc:
- raise MetadataExtractionError("read_metadata_failed", str(exc) or "Failed to read document metadata") from exc
- finally:
- if pdf_doc is not None:
- pdf_doc.close()
-
- await asyncio.to_thread(_extract)
-
-
-# ── Office metadata ────────────────────────────────────────────────
-
-
-async def _extract_office_meta(filepath: str, ext: str, result: dict) -> None:
- def _extract() -> None:
- if ext == "docx":
- if Document is None:
- return
- try:
- doc = Document(filepath)
- except Exception as exc:
- raise MetadataExtractionError("open_failed", str(exc) or "Failed to open document") from exc
-
- try:
- cp = doc.core_properties
- result["title"] = cp.title or None
- result["author"] = cp.author or None
- result["subject"] = cp.subject or None
- result["keywords"] = cp.keywords or None
- except Exception as exc:
- raise MetadataExtractionError("read_metadata_failed", str(exc) or "Failed to read document metadata") from exc
-
- elif ext == "pptx":
- if Presentation is None:
- return
- try:
- prs = Presentation(filepath)
- result["page_count"] = len(prs.slides)
- except Exception as exc:
- raise MetadataExtractionError("open_failed", str(exc) or "Failed to open document") from exc
-
- try:
- cp = prs.core_properties
- result["title"] = cp.title or None
- result["author"] = cp.author or None
- result["subject"] = cp.subject or None
- result["keywords"] = cp.keywords or None
- except Exception as exc:
- raise MetadataExtractionError("read_metadata_failed", str(exc) or "Failed to read document metadata") from exc
-
- elif ext == "xlsx":
- if load_workbook is None:
- return
- wb = None
- try:
- wb = load_workbook(filepath, read_only=True)
- result["page_count"] = len(wb.sheetnames)
- except Exception as exc:
- raise MetadataExtractionError("open_failed", str(exc) or "Failed to open document") from exc
- try:
- cp = wb.properties
- result["title"] = cp.title or None
- result["author"] = cp.creator or None
- result["subject"] = cp.subject or None
- result["keywords"] = cp.keywords or None
- except Exception as exc:
- raise MetadataExtractionError("read_metadata_failed", str(exc) or "Failed to read document metadata") from exc
- finally:
- if wb is not None:
- wb.close()
-
- elif ext in ODF_EXTENSIONS:
- from docvortex.analyzers.native.office.odf.metadata import extract_odf_metadata
-
- try:
- with open(filepath, "rb") as odf_file:
- metadata = extract_odf_metadata(odf_file, ext) # type: ignore[arg-type]
- except Exception as exc:
- raise MetadataExtractionError("open_failed", str(exc) or "Failed to open ODF document") from exc
- result.update(metadata)
-
- elif ext == "rtf":
- from docvortex.analyzers.native.office.rtf.converter import extract_rtf_metadata
-
- try:
- with open(filepath, "rb") as rtf_file:
- metadata = extract_rtf_metadata(rtf_file)
- except Exception as exc:
- raise MetadataExtractionError("open_failed", str(exc) or "Failed to open RTF document") from exc
- result.update(metadata)
- result["page_count"] = 1
-
- elif ext in ("doc", "ppt", "xls"):
- _extract_legacy_office_meta(filepath, result)
-
- await asyncio.to_thread(_extract)
-
-
-async def _extract_epub_meta(filepath: str, result: dict) -> None:
- """在线程中读取 EPUB OPF 元数据和 spine 逻辑页数。"""
-
- def _extract() -> None:
- """打开 EPUB 文件流并把原生 metadata 合并到 doclib 结果。"""
- from docvortex.analyzers.native.epub import extract_epub_metadata
-
- try:
- with open(filepath, "rb") as epub_file:
- metadata = extract_epub_metadata(epub_file)
- except Exception as exc:
- raise MetadataExtractionError("open_failed", str(exc) or "Failed to open EPUB document") from exc
- result.update(metadata)
-
- await asyncio.to_thread(_extract)
-
-
-async def _extract_ofd_meta(filepath: str, result: dict) -> None:
- """在线程中读取 OFD DocInfo 和声明页数。"""
-
- def _extract() -> None:
- """打开 OFD 文件流并合并原生元数据。"""
- from docvortex.analyzers.native.ofd import extract_ofd_metadata
-
- try:
- with open(filepath, "rb") as ofd_file:
- metadata = extract_ofd_metadata(ofd_file)
- except Exception as exc:
- raise MetadataExtractionError("open_failed", str(exc) or "Failed to open OFD document") from exc
- result.update(metadata)
-
- 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
+async def extract_metadata(filepath: str) -> DoclibMetadata:
+ """在线程中调用 DocVortex 公共接口;纯文本与图片维持原有入库行为。"""
+ from docvortex import extract_metadata as extract
+ from docvortex.errors import DocumentError
+
+ if Path(filepath).suffix.lower().lstrip(".") in TEXT_EXTENSIONS | IMAGE_EXTENSIONS:
+ return metadata_to_doclib(None)
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()
+ extracted = await asyncio.to_thread(extract, filepath)
+ except DocumentError as exc:
+ raise MetadataExtractionError(exc.code, str(exc)) from exc
+ result = metadata_to_doclib(extracted.metadata)
+ if extracted.diagnostics:
+ result["error_code"] = "read_metadata_failed"
+ result["error_msg"] = "; ".join(item.message for item in extracted.diagnostics)[:500]
+ return result
+
+
+__all__ = [
+ "DoclibMetadata",
+ "MetadataExtractionError",
+ "FileStat",
+ "compute_sha256",
+ "get_file_stat",
+ "extract_metadata",
+ "metadata_to_doclib",
+]
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index acec445f..36926c34 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -38,7 +38,14 @@ from ...parser.page_range import (
)
from ...types import QUALITY_TIERS, TIER_ORDER, PageInfo, Tier, select_default_quality_tier, select_parsing_rule_tier
from ..core.db import DatabaseManager
-from ..core.file_io import FileStat, MetadataExtractionError, compute_sha256, extract_metadata, get_file_stat
+from ..core.file_io import (
+ FileStat,
+ MetadataExtractionError,
+ compute_sha256,
+ extract_metadata,
+ get_file_stat,
+ metadata_to_doclib,
+)
from ..core.fts import FTSManager
from ..remote_api import resolve_remote_api_key
from ..rows import DocRow, FileRow, ParseBatchRow, ParseRow, Sha256Row, ShortIdRow, WatchTargetRow
@@ -178,6 +185,7 @@ async def ensure_doc_record(
subject: str | None,
keywords: str | None,
is_image_based: int = 0,
+ language: str | None = None,
error_code: str | None,
error_msg: str | None,
first_seen_at: int,
@@ -191,8 +199,8 @@ async def ensure_doc_record(
short_id = sha256[:length]
await db.execute(
"INSERT OR IGNORE INTO docs (sha256, short_id, size_bytes, file_type, page_count, "
- "title, author, subject, keywords, is_image_based, error_code, error_msg, first_seen_at, updated_at) "
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ "title, author, subject, keywords, is_image_based, error_code, error_msg, first_seen_at, updated_at, language) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
sha256,
short_id,
@@ -208,6 +216,7 @@ async def ensure_doc_record(
error_msg,
first_seen_at,
updated_at,
+ language,
),
)
inserted = cast(ShortIdRow | None, await db.fetchone("SELECT short_id FROM docs WHERE sha256=?", (sha256,)))
@@ -524,6 +533,8 @@ class ParseService:
metadata_error_msg = None
try:
metadata = await extract_metadata(path)
+ metadata_error_code = metadata.get("error_code")
+ metadata_error_msg = metadata.get("error_msg")
except MetadataExtractionError as exc:
metadata_error_code = exc.code
metadata_error_msg = str(exc)[:500] or "Failed to extract document metadata"
@@ -585,6 +596,7 @@ class ParseService:
subject=metadata["subject"],
keywords=metadata["keywords"],
is_image_based=int(metadata.get("is_image_based") or 0),
+ language=metadata.get("language"),
error_code=metadata_error_code,
error_msg=metadata_error_msg,
first_seen_at=now,
@@ -1023,6 +1035,12 @@ class ParseService:
md = result.markdown(add_markers=False) if hasattr(result, "markdown") else ""
md_text += md + "\n"
+ # 原文件属性不受推理档位限制,先更新数据库和已有索引,再处理正文索引。
+ await self._update_source_metadata(sha256, result)
+ refreshed_doc = await self.db.fetchone("SELECT title, author FROM docs WHERE sha256=?", (sha256,))
+ if refreshed_doc:
+ file_row = cast(FileRow, {**file_row, **refreshed_doc})
+
# update fts_contents (tier-gated)
await self._maybe_update_fts(sha256, tier, md_text, file_row)
@@ -1360,6 +1378,23 @@ class ParseService:
author=file_row.get("author") or "",
)
+ async def _update_source_metadata(self, sha256: str, result: ParseResult) -> None:
+ """原文档属性填补现有列并同步索引,空值不清空已有信息。"""
+ values = metadata_to_doclib(result.middle_json.metadata)
+ await self.db.execute(
+ "UPDATE docs SET title=COALESCE(?,title), author=COALESCE(?,author), "
+ "subject=COALESCE(?,subject), keywords=COALESCE(?,keywords), language=COALESCE(?,language), "
+ "updated_at=? WHERE sha256=?",
+ (values["title"], values["author"], values["subject"], values["keywords"], values["language"], _now_ms(), sha256),
+ )
+ await self.db.execute(
+ "UPDATE fts_contents SET title=COALESCE((SELECT title FROM docs WHERE sha256=?),''), "
+ "author=COALESCE((SELECT author FROM docs WHERE sha256=?),'') WHERE sha256=?",
+ (sha256, sha256, sha256),
+ )
+ if result.middle_json.metadata.file_suffix == "pdf" and values["page_count"] is not None:
+ await self.db.execute("UPDATE docs SET page_count=? WHERE sha256=?", (values["page_count"], sha256))
+
async def _maybe_update_docs_meta(self, sha256: str, tier: Tier) -> None:
doc = await self.db.fetchone("SELECT meta_tier FROM docs WHERE sha256=?", (sha256,))
if doc is None:
diff --git a/mineru/integrations/docvortex.py b/mineru/integrations/docvortex.py
index 0f1a35bd..0934c225 100644
--- a/mineru/integrations/docvortex.py
+++ b/mineru/integrations/docvortex.py
@@ -4,7 +4,8 @@ from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, ConfigDict, JsonValue
-from docvortex.schema import MiddleJson, ModelJson
+from docvortex.schema import DocumentProperties, FileSuffix, MiddleJson, ModelJson
+from docvortex.document.contracts import HtmlSourceContext
class MinerUMetadata(BaseModel):
@@ -20,10 +21,30 @@ def build_metadata(*, effort: str, parse_mode: str) -> dict[str, JsonValue]:
tiers = {"flash": "flash", "medium": "basic", "high": "standard", "xhigh": "advanced"}
if effort not in tiers:
raise ValueError(f"Unsupported actual analyze effort: {effort}")
- metadata = MinerUMetadata(tier=tiers[effort], parse_mode=parse_mode)
+ metadata = MinerUMetadata.model_validate({"tier": tiers[effort], "parse_mode": parse_mode})
return {"mineru": metadata.model_dump(mode="json")}
+def read_source_properties(
+ data: bytes,
+ suffix: FileSuffix,
+ source_context: HtmlSourceContext | None = None,
+) -> DocumentProperties:
+ """提取原始输入属性;正文引擎决定输入有效性,属性失败仅记录诊断。"""
+ from docvortex import extract_metadata
+ from docvortex.errors import DocumentError
+ from loguru import logger
+
+ try:
+ result = extract_metadata(data, file_suffix=suffix, source_context=source_context)
+ except DocumentError as exc:
+ logger.warning("Source metadata unavailable: {}", exc)
+ return DocumentProperties()
+ for diagnostic in result.diagnostics:
+ logger.warning("Source metadata: {}", diagnostic.message)
+ return result.metadata.document or DocumentProperties()
+
+
def with_mineru_metadata(document: ModelJson | MiddleJson, metadata: MinerUMetadata) -> None:
"""附加产品扩展并保留其他应用信息,不修改文档生产者。"""
document.extensions = {**document.extensions, "mineru": metadata.model_dump(mode="json")}
@@ -35,4 +56,4 @@ def validate_mineru_metadata(document: ModelJson | MiddleJson) -> None:
MinerUMetadata.model_validate(document.extensions["mineru"])
-__all__ = ["MinerUMetadata", "build_metadata", "with_mineru_metadata", "validate_mineru_metadata"]
+__all__ = ["read_source_properties", "MinerUMetadata", "build_metadata", "with_mineru_metadata", "validate_mineru_metadata"]
diff --git a/mineru/parser/mineru_parser.py b/mineru/parser/mineru_parser.py
index 28d59ce5..3c5ba79a 100644
--- a/mineru/parser/mineru_parser.py
+++ b/mineru/parser/mineru_parser.py
@@ -11,6 +11,8 @@ from pathlib import Path
from typing import Any, Literal, cast
from ..backend.analyze import aio_doc_analyze, doc_analyze
+from ..integrations.docvortex import read_source_properties
+from docvortex.schema import DocumentProperties
from ..config import VlmConfig, config
from ..errors import InvalidRequestError
from ..filetypes import IMAGE_EXTENSIONS, PAGE_RANGE_PARSE_EXTENSIONS
@@ -35,6 +37,7 @@ class _PreparedInput:
source_context: HtmlSourceContext | None = None
retained_page_indices: list[int] | None = None
broken_page_indices: list[int] | None = None
+ source_properties: DocumentProperties | None = None
class MinerUParser(DocumentParser):
@@ -114,6 +117,7 @@ class MinerUParser(DocumentParser):
file_suffix=prepared.file_suffix,
source_context=prepared.source_context,
vlm_config=self.vlm_config,
+ source_properties=prepared.source_properties,
)
async def _arun_analysis(self, prepared: _PreparedInput) -> tuple[MiddleJson, ModelJson]:
@@ -127,6 +131,7 @@ class MinerUParser(DocumentParser):
file_suffix=prepared.file_suffix,
source_context=prepared.source_context,
vlm_config=self.vlm_config,
+ source_properties=prepared.source_properties,
)
def _prepare_input(
@@ -176,11 +181,6 @@ class MinerUParser(DocumentParser):
f"Page range is only supported for PDF files; '{source_suffix}' uses full-document parsing.",
"page_range",
)
- file_bytes, retained_page_indices, broken_page_indices = self._maybe_adjust_pdf_bytes(
- file_bytes,
- suffix,
- page_range,
- )
resolved_source_context = source_context
if suffix == "html" and resolved_source_context is None:
from docvortex.analyzers.native.html import HtmlSourceContext
@@ -190,6 +190,16 @@ class MinerUParser(DocumentParser):
source_uri=resolved_path.as_uri(),
local_resource_root=resolved_path.parent,
)
+ source_properties = (
+ DocumentProperties()
+ if source_suffix in IMAGE_EXTENSIONS
+ else read_source_properties(file_bytes, cast(FileSuffix, suffix), resolved_source_context)
+ )
+ file_bytes, retained_page_indices, broken_page_indices = self._maybe_adjust_pdf_bytes(
+ file_bytes,
+ suffix,
+ page_range,
+ )
return _PreparedInput(
file_name=file_name,
file_bytes=file_bytes,
@@ -197,6 +207,7 @@ class MinerUParser(DocumentParser):
source_context=resolved_source_context,
retained_page_indices=retained_page_indices,
broken_page_indices=broken_page_indices,
+ source_properties=source_properties,
)
def _maybe_adjust_pdf_bytes(
diff --git a/pyproject.toml b/pyproject.toml
index 29cbbe45..9b2d72d4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -40,7 +40,6 @@ classifiers = [
dependencies = [
"docvortex>=0.2.2,<1.0.0",
"mineru-vl-utils>=1.2.1,<2",
- "metafile-render>=0.3.0,<1.0.0",
"mineru-llama-cpp>=0.1.0,<1",
"click>=8.1.7",
"loguru>=0.7.2",
@@ -50,30 +49,15 @@ dependencies = [
"httpx",
"pillow>=11.0.0",
"pypdfium2>=5.10.1",
- "pypdf>=5.6.0",
"PyYAML>=6.0.1,<7",
"packaging",
- "reportlab",
- "ziamath>=0.13,<0.14",
"modelscope>=1.26.0",
"huggingface-hub[hf_xet]>=0.32.4",
"filelock>=3.0.0",
"json-repair>=0.46.2",
- "latex2mathml>=3.81.0,<4",
"opencv-python>=4.11.0.86",
- "fast-langdetect>=0.2.3,<0.3.0",
"openai>=1.70.0,<3",
"beautifulsoup4>=4.13.5,<5",
- "nh3>=0.3.6,<0.4",
- "magika>=0.6.2,<1.1.0",
- "python-docx>=1.2.0,<2",
- 'pypptx-with-oxml>=1.0.3,<2',
- "mammoth>=1.11.0,<2",
- "mathml2omml==0.0.2",
- "pylatexenc>=2.10,<3",
- "lxml>=4.0.0,<7.0.0",
- "openpyxl>=3.1.5,<4",
- "olefile>=0.47,<1",
"aiosqlite>=0.20.0,<1",
"watchfiles>=1.0.0,<2",
"fastapi",
@@ -85,7 +69,6 @@ dependencies = [
"jieba>=0.42.1",
"onnxruntime>=1.17.0",
"ftfy>=6.3.1,<7",
- "fonttools>=4.0.0,<5",
"shapely>=2.0.7,<3",
"pyclipper>=1.3.0,<2",
"tokenizers>=0.22.0,<0.23.1",
@@ -96,6 +79,9 @@ dev = [
"lxml-stubs",
]
test = [
+ "pypdf>=5.6.0",
+ "reportlab",
+ "lxml>=4.0.0,<7.0.0",
"pytest",
"pytest-cov",
"coverage",
diff --git a/tests/unittest/test_doclib_file_io.py b/tests/unittest/test_doclib_file_io.py
index a84c3eb8..c2ae37f1 100644
--- a/tests/unittest/test_doclib_file_io.py
+++ b/tests/unittest/test_doclib_file_io.py
@@ -1,90 +1,102 @@
+"""验证 Doclib 只通过 DocVortex 公共接口读取并映射属性。"""
+
from __future__ import annotations
import asyncio
+from pathlib import Path
-from mineru.doclib.core import file_io
-
-
-def test_extract_pdf_meta_serializes_pdfium_calls(monkeypatch) -> None:
- assert not hasattr(file_io, "open_pdfium_document")
-
- state = {"closed_doc": False}
-
- class _FakePdf:
- @property
- def page_count(self) -> int:
- return 7
-
- @property
- def metadata(self) -> dict[str, str]:
- return {
- "Title": "Test Title",
- "Author": "Test Author",
- "Subject": "Test Subject",
- "Keywords": "alpha,beta",
- }
+import docvortex
+import pytest
+from docvortex.errors import DocumentError
+from docvortex.result import Diagnostic, MetadataResult
+from docvortex.schema import DocumentMetadata, DocumentProperties, Producer
- def close(self) -> None:
- state["closed_doc"] = True
-
- monkeypatch.setattr(file_io, "PDFDocument", lambda filepath: _FakePdf())
+from mineru.doclib.core import file_io
- result = {
- "page_count": None,
- "title": None,
- "author": None,
- "subject": None,
- "keywords": None,
- "is_image_based": 0,
- }
- asyncio.run(file_io._extract_pdf_meta("dummy.pdf", result))
+def metadata_result() -> MetadataResult:
+ """构造超长和多值属性,检查数据库映射不反向修改源对象。"""
+ return MetadataResult(
+ DocumentMetadata(
+ file_suffix="pdf",
+ producer=Producer(name="docvortex", version="0.2.5"),
+ document=DocumentProperties(
+ title="标题" * 400,
+ authors=["Alice", "Bob"],
+ subject="Subject",
+ keywords=["alpha", "beta"],
+ languages=["zh-CN", "en"],
+ page_count=7,
+ page_count_kind="physical",
+ ),
+ )
+ )
+
+
+def test_extract_metadata_delegates_and_limits_only_database(monkeypatch: pytest.MonkeyPatch) -> None:
+ """真实的提取职责交给 DocVortex,字符串截断只在 Doclib 映射发生。"""
+ extracted = metadata_result()
+ calls: list[str] = []
+
+ def extract(source: str) -> MetadataResult:
+ """替换公共接口,确认调用原始路径并传递完整结果。"""
+ calls.append(source)
+ return extracted
+
+ monkeypatch.setattr(docvortex, "extract_metadata", extract)
+ result = asyncio.run(file_io.extract_metadata("sample.pdf"))
+ assert calls == ["sample.pdf"]
assert result["page_count"] == 7
- assert result["title"] == "Test Title"
- assert result["author"] == "Test Author"
- assert result["subject"] == "Test Subject"
- assert result["keywords"] == "alpha,beta"
- assert state["closed_doc"] is True
-
-
-def test_extract_pdf_metadata_open_failure_uses_open_failed(monkeypatch) -> None:
- def _fail_open(filepath):
- raise RuntimeError("cannot open pdf")
+ assert result["author"] == "Alice; Bob"
+ assert result["keywords"] == "alpha, beta"
+ assert result["language"] == "zh-CN"
+ assert len(result["title"]) == 500
+ assert len(extracted.metadata.document.title) == 800
+ assert not hasattr(file_io, "PDFDocument")
- monkeypatch.setattr(file_io, "PDFDocument", _fail_open)
- try:
- asyncio.run(file_io.extract_metadata("dummy.pdf"))
- except file_io.MetadataExtractionError as exc:
- assert exc.code == "open_failed"
- assert "cannot open pdf" in str(exc)
- else:
- raise AssertionError("PDF open failure should be classified")
+def test_extract_metadata_open_error_preserves_code(monkeypatch: pytest.MonkeyPatch) -> None:
+ """输入错误映射到 Doclib 稳定错误,不把失败伪装成空属性。"""
+ def extract(source: str) -> MetadataResult:
+ """模拟共享引擎无法打开文件。"""
+ raise DocumentError("open_failed", "cannot open document")
-def test_extract_pdf_metadata_read_failure_uses_read_metadata_failed(monkeypatch) -> None:
- state = {"closed_doc": False}
+ monkeypatch.setattr(docvortex, "extract_metadata", extract)
+ with pytest.raises(file_io.MetadataExtractionError) as exc:
+ asyncio.run(file_io.extract_metadata("sample.pdf"))
+ assert exc.value.code == "open_failed"
- class _FakePdf:
- @property
- def page_count(self) -> int:
- return 7
- @property
- def metadata(self) -> dict[str, str]:
- raise RuntimeError("cannot read title")
+def test_partial_metadata_keeps_values_and_diagnostic(monkeypatch: pytest.MonkeyPatch) -> None:
+ """可选属性失败时保留页数和已有标题,错误由入库层记录。"""
+ extracted = metadata_result()
+ extracted.diagnostics = (Diagnostic("read_metadata_failed", "bad XMP"),)
- def close(self) -> None:
- state["closed_doc"] = True
+ def extract(source: str) -> MetadataResult:
+ """返回部分成功的属性提取结果。"""
+ return extracted
- monkeypatch.setattr(file_io, "PDFDocument", lambda filepath: _FakePdf())
-
- try:
- asyncio.run(file_io.extract_metadata("dummy.pdf"))
- except file_io.MetadataExtractionError as exc:
- assert exc.code == "read_metadata_failed"
- assert "cannot read title" in str(exc)
- else:
- raise AssertionError("PDF metadata read failure should be classified")
-
- assert state["closed_doc"] is True
+ monkeypatch.setattr(docvortex, "extract_metadata", extract)
+ result = asyncio.run(file_io.extract_metadata("sample.pdf"))
+ assert result["page_count"] == 7
+ assert result["title"]
+ assert result["error_code"] == "read_metadata_failed"
+ assert result["error_msg"] == "bad XMP"
+
+
[email protected]("suffix", ["doc", "docx", "rtf"])
+def test_declared_pages_do_not_change_reflow_scheduling(suffix: str) -> None:
+ """源软件声明页数仍随 JSON 保留,调度维持单逻辑文档口径。"""
+ extracted = metadata_result()
+ extracted.metadata.file_suffix = suffix
+ extracted.metadata.document.page_count_kind = "declared"
+ assert file_io.metadata_to_doclib(extracted.metadata)["page_count"] == 1
+ assert extracted.metadata.document.page_count == 7
+
+
+def test_text_ingest_does_not_claim_document_metadata(tmp_path: Path) -> None:
+ """纯文本沿用 Doclib 原有能力,不扩大 DocVortex 输入类型。"""
+ source = tmp_path / "file.txt"
+ source.write_text("body")
+ assert asyncio.run(file_io.extract_metadata(str(source)))["title"] is None
diff --git a/tests/unittest/test_flash_epub.py b/tests/unittest/test_flash_epub.py
index 40b47a0b..e9bd048f 100644
--- a/tests/unittest/test_flash_epub.py
+++ b/tests/unittest/test_flash_epub.py
@@ -148,6 +148,9 @@ def test_doclib_extracts_epub_metadata(tmp_path: Path) -> None:
"subject": "Testing",
"keywords": "Testing, epub, mineru",
"is_image_based": 0,
+ "language": None,
+ "error_code": None,
+ "error_msg": None,
}
diff --git a/tests/unittest/test_source_metadata.py b/tests/unittest/test_source_metadata.py
new file mode 100644
index 00000000..4bb5c770
--- /dev/null
+++ b/tests/unittest/test_source_metadata.py
@@ -0,0 +1,139 @@
+"""验证原始文档属性跨 MinerU 输入处理、JSON 和 Doclib 的传递。"""
+
+from __future__ import annotations
+
+import asyncio
+from io import BytesIO
+from pathlib import Path
+
+from docvortex.schema import DocumentMetadata, DocumentProperties, MiddleJson, PageInfo, Producer
+from pypdf import PdfWriter
+import pytest
+
+from mineru.backend.analysis.contracts import AnalysisResult
+from mineru.backend.analyze import aio_doc_analyze, doc_analyze
+from mineru.doclib.core.db import DatabaseManager
+from mineru.doclib.core.fts import FTSManager
+from mineru.doclib.services.config_svc import ConfigService
+from mineru.doclib.services.parse_svc import ParseService, ensure_doc_record
+from mineru.parser import MinerUParser, ParseResult
+
+
+def source_pdf() -> bytes:
+ """构造两页带标题和作者的 PDF,用于验证抽页不丢原始属性。"""
+ writer = PdfWriter()
+ writer.add_blank_page(width=100, height=100)
+ writer.add_blank_page(width=100, height=100)
+ writer.add_metadata({"/Title": "Original title", "/Author": "Source author"})
+ stream = BytesIO()
+ writer.write(stream)
+ return stream.getvalue()
+
+
[email protected]("asynchronous", [False, True])
+def test_parser_preserves_source_metadata_before_selection(tmp_path: Path, asynchronous: bool) -> None:
+ """同步和异步解析均保存完整源文档计数,而非重写后的一页。"""
+ source = tmp_path / "document.pdf"
+ source.write_bytes(source_pdf())
+ parser = MinerUParser(tier="flash", parse_mode="txt")
+ result = asyncio.run(parser.parse_async(source, page_range="2")) if asynchronous else parser.parse(source, page_range="2")
+ props = result.middle_json.metadata.document
+ assert (props.title, props.authors, props.page_count) == ("Original title", ["Source author"], 2)
+ assert result.middle_json.pages[0].page_idx == 1
+ assert result.middle_json.metadata.producer.name == "mineru"
+ assert result._model_output.metadata.document == props
+ assert ParseResult.from_json(result.to_json()).middle_json.metadata.document == props
+ assert result.structured_content()["metadata"]["document"]["title"] == "Original title"
+
+
[email protected]("effort", ["flash", "medium", "high", "xhigh"])
[email protected]("asynchronous", [False, True])
+def test_backend_all_tiers_receive_same_source_metadata(
+ monkeypatch: pytest.MonkeyPatch,
+ effort: str,
+ asynchronous: bool,
+) -> None:
+ """直接分析入口不依赖 parser 预处理,也不把源属性归入某个推理档位。"""
+ from mineru.backend.analysis.pdf import pipeline
+
+ def analyze(data: bytes, **kwargs: object) -> AnalysisResult:
+ """替代模型推理,只保留真实统一分析门面的元数据行为。"""
+ return AnalysisResult(model_list=[[]], effort=effort, parse_mode="txt", elapsed=0.0)
+
+ monkeypatch.setattr(pipeline, "analyze_pdf", analyze)
+ result = (
+ asyncio.run(aio_doc_analyze(source_pdf(), effort=effort)) if asynchronous else doc_analyze(source_pdf(), effort=effort)
+ )
+ middle, model = result
+ assert middle.metadata.document == model.metadata.document
+ assert model.metadata.document.page_count == 2
+ assert model.metadata.document.title == "Original title"
+
+
+def test_doclib_source_columns_and_fts_are_independent_of_tier(tmp_path: Path) -> None:
+ """真实 SQLite 验证属性补齐不降级高档正文索引,空字段不清除旧信息。"""
+
+ async def scenario() -> None:
+ """创建入库记录,使用新源属性刷新现有列和已有索引。"""
+ db = DatabaseManager(str(tmp_path / "db.sqlite"))
+ await db.initialize()
+ fts = FTSManager(db)
+ service = ParseService(db, fts, ConfigService(db), str(tmp_path), parse_lock_timeout_sec=30)
+ sha = "a" * 64
+ await ensure_doc_record(
+ db,
+ sha256=sha,
+ size_bytes=10,
+ file_type="pdf",
+ page_count=1,
+ title="Old",
+ author="Old author",
+ subject="Keep subject",
+ keywords="Keep keywords",
+ language="en",
+ error_code=None,
+ error_msg=None,
+ first_seen_at=1,
+ updated_at=1,
+ )
+ await fts.replace(sha256=sha, tier="advanced", text="Preserved body", title="Old", author="Old author")
+ metadata = DocumentMetadata(
+ file_suffix="pdf",
+ producer=Producer(name="mineru", version="test"),
+ document=DocumentProperties(
+ title="New title", authors=["Alice", "Bob"], languages=["zh-CN"], page_count=9, page_count_kind="physical"
+ ),
+ )
+ result = ParseResult(MiddleJson(pages=[PageInfo(page_idx=0)], is_full_document=False, metadata=metadata))
+ await service._update_source_metadata(sha, result)
+ row = await db.fetchone("SELECT * FROM docs WHERE sha256=?", (sha,))
+ assert (row["title"], row["author"], row["language"], row["page_count"]) == ("New title", "Alice; Bob", "zh-CN", 9)
+ assert row["subject"] == "Keep subject" and row["keywords"] == "Keep keywords"
+ index = await db.fetchone("SELECT * FROM fts_contents WHERE sha256=?", (sha,))
+ assert index["tier"] == "advanced" and index["title"] == "New title" and index["author"] == "Alice; Bob"
+ assert "Preserved" in index["text"]
+ result.middle_json.metadata.document = None
+ await service._update_source_metadata(sha, result)
+ assert (await db.fetchone("SELECT title FROM docs WHERE sha256=?", (sha,)))["title"] == "New title"
+
+ asyncio.run(scenario())
+
+
+def test_doclib_ingest_gets_html_metadata_without_parsing(tmp_path: Path) -> None:
+ """真实入库流程无需正文任务完成,即可保存 HTML 标题作者和语言。"""
+
+ async def scenario() -> None:
+ """使用临时数据库与源 HTML 走入库服务。"""
+ db = DatabaseManager(str(tmp_path / "db.sqlite"))
+ await db.initialize()
+ service = ParseService(db, FTSManager(db), ConfigService(db), str(tmp_path), parse_lock_timeout_sec=30)
+ source = tmp_path / "source.html"
+ source.write_text(
+ '<html lang="zh-CN"><head><title>入库标题</title><meta name="author" content="作者"></head><body>正文</body></html>'
+ )
+ refresh = await service.refresh_file(str(source), ensure_ingested=True)
+ assert refresh.file is not None
+ row = await db.fetchone("SELECT * FROM docs WHERE sha256=?", (refresh.file.sha256,))
+ assert (row["title"], row["author"], row["language"]) == ("入库标题", "作者", "zh-CN")
+
+ asyncio.run(scenario())