Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: implement legacy schema adapter for MinerU 3.4.5 Middle JSON conversion
myhloli56d51942c553
diff --git a/docs/next/decisions/0033-middle-json-inline-spans.md b/docs/next/decisions/0033-middle-json-inline-spans.mdindex aaa81de3..3035ca8c 100644--- a/docs/next/decisions/0033-middle-json-inline-spans.md+++ b/docs/next/decisions/0033-middle-json-inline-spans.md@@ -21,8 +21,9 @@ Schema 2.0 使用自然语言字符串中的 `<eq>`、`<text style>` 和- 算法正文新增 `algorithm_body` 并使用 Span;普通代码、行间公式、表格 HTML、Chart HTML、图片专用内容和 Mermaid 继续使用专用字符串。- HTML v1 wire 使用明确 DOM metadata 精确恢复 Span,不从展示标签反推。-- 1.0/2.0 payload 与旧 Doclib 缓存不迁移,必须从源文件重新解析;删除- `legacy_schema_adapter`。+- 当前运行时仍严格使用 schema 3.0;仅对 MinerU 3.4.5 页面结构及对应的 1.0+ pages 包装保留 `legacy_schema_adapter`,先转换为结构化 raw ModelJson 再进入统一后处理。+- 其它未知旧 payload 仍必须从源文件重新解析,不恢复字符串与 Span 的联合公开类型。## 结果diff --git a/docs/next/middle-json.md b/docs/next/middle-json.mdindex 3c5c92f3..039ea2d7 100644--- a/docs/next/middle-json.md+++ b/docs/next/middle-json.md@@ -27,7 +27,8 @@ Middle JSON 已经收敛为 schema 3.0 的严格 Pydantic 模型:`mineru/types- 以当前代码中的 Pydantic 严格模型为起点(schema 3.0)。- 区分“已经解决”、“部分解决”、“仍需工作”。- Agent 引用与稳定 page/block locator 是 P0 目标。-- 1.0/2.0 payload 和缓存视为 stale,必须从源文件重新解析,不提供自动迁移。+- MinerU 3.4.5 页面及对应 1.0 pages 包装经 `legacy_schema_adapter` 转换;其它旧 payload+ 和无法识别的缓存视为 stale,必须从源文件重新解析。- render 统一不能只看入口 facade,还要收敛格式-specific 分支。## 与其他文档的关系diff --git a/docs/next/middle-json/README.md b/docs/next/middle-json/README.mdindex c05b52f7..31fea990 100644--- a/docs/next/middle-json/README.md+++ b/docs/next/middle-json/README.md@@ -60,7 +60,7 @@ Middle JSON 下一版要达到以下目标:- 稳定 page/block locator。- 可从 Agent answer 追溯到 page / block / bbox / source hash。-- 旧 middle json 能被明确识别为 stale 并触发重新解析。+- 可识别的 MinerU 3.4.5 middle json 能迁移,其它旧数据能被标记为 stale 并触发重新解析。- `ParseResult.from_dict()` 可以恢复 API / 缓存结果。- 默认选择 / tier 产生的不同质量结果能被 doclib 正确区分和缓存。diff --git a/docs/next/middle-json/current-medium.md b/docs/next/middle-json/current-medium.mdindex 90387f40..a6d73ee3 100644--- a/docs/next/middle-json/current-medium.md+++ b/docs/next/middle-json/current-medium.md@@ -150,8 +150,8 @@ Markdown、HTML、DOCX 与 Structured Content renderer 按 Span discriminator## 缓存与兼容-- `ParseResult.from_dict()` 仅接受 `schema_version="3.0"`;-- 1.0/2.0 与缺失版本返回“重新解析源文件”的明确错误;-- Doclib 将旧 batch/cache 视为 stale 并重新调度;-- `legacy_schema_adapter` 已删除;+- `ParseResult.from_dict()` 直接接受 `schema_version="3.0"`;+- MinerU 3.4.5 `pdf_info` 与对应 1.0 pages 包装经 `legacy_schema_adapter` 回推;+- Doclib compaction 使用同一适配器迁移可识别旧 batch,无法识别时仍按 stale 处理;+- 2.0 与其它未知旧版本返回“重新解析源文件”的明确错误;- 不提供 `str | list[InlineSpan]` 联合,也不恢复旧版带 bbox/图片职责的 Line/Span。diff --git a/mineru/backend/postprocess/legacy_schema_adapter.py b/mineru/backend/postprocess/legacy_schema_adapter.pynew file mode 100644index 00000000..1b0e4098--- /dev/null+++ b/mineru/backend/postprocess/legacy_schema_adapter.py@@ -0,0 +1,734 @@+# Copyright (c) Opendatalab. All rights reserved.+"""MinerU 3.4.5 Middle JSON page 到当前 raw ModelJson 的适配器。++3.4.5 的页面仍使用 ``preproc_blocks``/``para_blocks``、``lines`` 和+``spans``,自然语言行内语义则通过旧字符串标签或旧 span 字段表达。本模块只负责+把单页回推成当前 ``model_json_to_pages`` 能消费的 raw block 列表;文档 envelope+及当前 MiddleJson 的元数据由调用方负责。+"""++from __future__ import annotations++import html+import math+import re+from typing import Any++from ...types import INLINE_STYLE_ORDER, InlineSpan, parse_inline_spans+from ...utils.hyperlink import OFFICE_EXTERNAL_HYPERLINK_SCHEMES, sanitize_hyperlink_target+from .inline import join_inline_spans++# 这些父块在 3.4.5 中通过 ``blocks`` 保存 body/caption/footnote;当前 raw+# ModelJson 则要求先展平成同级 block,再由统一后处理重新分组。+_VISUAL_PARENT_TYPES: frozenset[str] = frozenset(+ {+ "image",+ "image_block",+ "table",+ "chart",+ "code",+ "algorithm",+ }+)++_INLINE_CONTENT_BLOCK_TYPES: frozenset[str] = frozenset(+ {+ "text",+ "ref_text",+ "doc_title",+ "paragraph_title",+ "header",+ "footer",+ "page_number",+ "aside_text",+ "page_footnote",+ "image_caption",+ "image_footnote",+ "table_caption",+ "table_footnote",+ "chart_caption",+ "chart_footnote",+ "code_caption",+ "code_footnote",+ "caption",+ "footnote",+ "algorithm",+ "phonetic",+ }+)++_STRING_CONTENT_BLOCK_TYPES: frozenset[str] = frozenset(+ {+ "equation",+ "image_body",+ "table_body",+ "chart_body",+ "code_body",+ }+)++_BLOCK_TYPE_ALIASES: dict[str, str] = {+ "abstract": "text",+ "vertical_text": "text",+ "phonetic": "text",+ "formula_number": "text",+ "discarded": "aside_text",+ "interline_equation": "equation",+ "image_block": "image",+ "algorithm_body": "code_body",+ "algorithm_caption": "code_caption",+ "algorithm_footnote": "code_footnote",+ "header_image": "image_body",+ "footer_image": "image_body",+}++_INLINE_START_RE = re.compile(+ r"<(?P<tag>eq|code|text|hyperlink|sup|sub|strong|b|em|i|s|u)(?P<attrs>\s[^<>]*?)?>",+ re.IGNORECASE,+)+_STYLE_ATTR_RE = re.compile(r"\bstyle\s*=\s*([\"'])(?P<style>.*?)\1", re.IGNORECASE | re.DOTALL)+_URL_RE = re.compile(r"<url>(?P<url>.*?)</url>", re.IGNORECASE | re.DOTALL)+_DIRECT_TAG_STYLES: dict[str, str] = {+ "strong": "bold",+ "b": "bold",+ "em": "italic",+ "i": "italic",+ "s": "strikethrough",+ "u": "underline",+ "sup": "superscript",+ "sub": "subscript",+}++# 3.4.5 PDF 的异常零面积框需要替换后才能通过当前严格 bbox 校验。+_PLACEHOLDER_BBOX: tuple[float, float, float, float] = (0.0, 0.0, 0.001, 0.001)+++def legacy_page_to_model_list(page: dict[str, Any]) -> list[dict[str, Any]]:+ """把 MinerU 3.4.5 的单页 Middle JSON 转换为当前 raw model-list。"""+ if not isinstance(page, dict):+ raise ValueError("legacy Middle JSON page must be a dict")++ width, height = _parse_page_size(page.get("page_size"))+ source_blocks = page.get("preproc_blocks")+ if source_blocks is None:+ source_blocks = page.get("para_blocks", [])+ if not isinstance(source_blocks, list):+ raise ValueError("legacy Middle JSON page blocks must be a list")++ discarded_blocks = page.get("discarded_blocks", [])+ if not isinstance(discarded_blocks, list):+ raise ValueError("legacy Middle JSON discarded_blocks must be a list")++ legacy_blocks = [*source_blocks, *discarded_blocks]+ model_list: list[dict[str, Any]] = []+ for group_index, block in enumerate(legacy_blocks):+ if not isinstance(block, dict):+ raise ValueError("legacy Middle JSON block entries must be dicts")+ group_start = len(model_list)+ _collect_blocks(block, width, height, model_list, inherited=None)+ if width <= 0 or height <= 0:+ _assign_synthetic_group_bbox(model_list[group_start:], group_index, len(legacy_blocks))+ return model_list+++def _parse_page_size(value: Any) -> tuple[float, float]:+ """读取合法 page_size;缺失、非数值或非正值统一返回零值。"""+ if not isinstance(value, (list, tuple)) or len(value) < 2:+ return 0.0, 0.0+ width, height = value[:2]+ if any(isinstance(item, bool) or not isinstance(item, (int, float)) for item in (width, height)):+ return 0.0, 0.0+ parsed_width, parsed_height = float(width), float(height)+ if not all(math.isfinite(item) and item > 0 for item in (parsed_width, parsed_height)):+ return 0.0, 0.0+ return parsed_width, parsed_height+++def _assign_synthetic_group_bbox(blocks: list[dict[str, Any]], group_index: int, group_count: int) -> None:+ """为无 page_size 文档分配互不重叠的占位框,并保持原顶层块的子项同组。"""+ safe_count = max(group_count, 1)+ y0 = (group_index + 0.2) / safe_count+ y1 = (group_index + 0.8) / safe_count+ bbox = (0.05, y0, 0.95, y1)+ for block in blocks:+ block["bbox"] = bbox+ lines = block.get("lines")+ if isinstance(lines, list):+ for line in lines:+ if isinstance(line, dict):+ line["bbox"] = list(bbox)+++def _collect_blocks(+ block: dict[str, Any],+ width: float,+ height: float,+ output: list[dict[str, Any]],+ *,+ inherited: dict[str, Any] | None,+) -> None:+ """递归展平视觉父块,并把普通叶子转换为当前 raw block。"""+ source_type = str(block.get("type", "") or "")+ nested = block.get("blocks")+ if source_type in _VISUAL_PARENT_TYPES and isinstance(nested, list) and nested:+ child_context = _visual_child_context(block, source_type, inherited)+ for child in nested:+ if not isinstance(child, dict):+ raise ValueError("legacy visual block children must be dicts")+ _collect_blocks(child, width, height, output, inherited=child_context)+ return++ block_type = _normalize_block_type(block)+ if block_type == "list" and isinstance(nested, list) and nested:+ output.append(_convert_leaf_block(block, block_type, width, height, inherited))+ output.extend(_flatten_nested_list_items(nested, width, height))+ return+ if block_type == "index" and isinstance(nested, list) and nested:+ output.append(_flatten_nested_index(block, nested, width, height))+ return+ if block_type == "list" and isinstance(block.get("lines"), list) and block["lines"]:+ output.append(_convert_leaf_block(block, block_type, width, height, inherited))+ output.extend(_convert_pdf_list_items(block, width, height))+ return++ raw = _convert_leaf_block(block, block_type, width, height, inherited)+ output.append(raw)+++def _visual_child_context(+ block: dict[str, Any],+ source_type: str,+ inherited: dict[str, Any] | None,+) -> dict[str, Any]:+ """收集视觉父块上需要下沉到 body 的元数据。"""+ context = dict(inherited or {})+ context["bbox"] = block.get("bbox", context.get("bbox"))+ sub_type = block.get("sub_type")+ if not isinstance(sub_type, str) or not sub_type.strip():+ sub_type = "algorithm" if source_type == "algorithm" else None+ if sub_type:+ context["sub_type"] = sub_type+ if isinstance(block.get("guess_lang"), str) and block["guess_lang"].strip():+ context["guess_lang"] = block["guess_lang"].strip()+ if "cell_merge" in block:+ context["cell_merge"] = block.get("cell_merge")+ return context+++def _flatten_nested_list_items(nested: list[Any], width: float, height: float) -> list[dict[str, Any]]:+ """把 3.4.5 Office 嵌套列表叶子展平为当前 PDF list 可关联的文本块。"""+ items: list[dict[str, Any]] = []+ for child in nested:+ if not isinstance(child, dict):+ raise ValueError("legacy list children must be dicts")+ child_type = _normalize_block_type(child)+ child_nested = child.get("blocks")+ if child_type == "list" and isinstance(child_nested, list):+ items.extend(_flatten_nested_list_items(child_nested, width, height))+ continue+ if child_type not in {"text", "ref_text"}:+ child_type = "text"+ items.append(_convert_leaf_block(child, child_type, width, height, inherited=None))+ return items+++def _flatten_nested_index(+ block: dict[str, Any],+ nested: list[Any],+ width: float,+ height: float,+) -> dict[str, Any]:+ """把 3.4.5 Office 嵌套目录折叠为当前 PDF index 使用的换行 Span。"""+ contents: list[list[dict[str, Any]]] = []++ def collect(children: list[Any]) -> None:+ """按深度优先顺序收集目录叶子的结构化行内内容。"""+ for child in children:+ if not isinstance(child, dict):+ raise ValueError("legacy index children must be dicts")+ child_nested = child.get("blocks")+ if _normalize_block_type(child) == "index" and isinstance(child_nested, list):+ collect(child_nested)+ continue+ converted = _convert_leaf_block(child, "text", width, height, inherited=None)+ content = converted.get("content")+ if isinstance(content, list) and content:+ contents.append([span for span in content if isinstance(span, dict)])++ collect(nested)+ joined: list[dict[str, Any]] = []+ for content_index, content in enumerate(contents):+ if content_index:+ _append_text_span(joined, "\n", ())+ _extend_span_dicts(joined, content)+ return {+ "type": "index",+ "bbox": _normalize_bbox(block.get("bbox"), width, height),+ "content": [span.model_dump(mode="json") for span in parse_inline_spans(joined)],+ }+++def _convert_pdf_list_items(block: dict[str, Any], width: float, height: float) -> list[dict[str, Any]]:+ """把 3.4.5 PDF list 的物理行恢复为当前 bbox 关联需要的文本项。"""+ raw_lines = [line for line in block.get("lines", []) if isinstance(line, dict)]+ if not raw_lines:+ return []+ has_item_flags = any(line.get("is_list_start_line") or line.get("is_list_end_line") for line in raw_lines)+ line_groups: list[list[dict[str, Any]]] = []+ current_group: list[dict[str, Any]] = []+ for line in raw_lines:+ if current_group and (line.get("is_list_start_line") or not has_item_flags):+ line_groups.append(current_group)+ current_group = []+ current_group.append(line)+ if line.get("is_list_end_line"):+ line_groups.append(current_group)+ current_group = []+ if current_group:+ line_groups.append(current_group)++ item_type = "ref_text" if block.get("sub_type") == "ref_text" else "text"+ items: list[dict[str, Any]] = []+ for lines in line_groups:+ synthetic_block = {+ "type": item_type,+ "bbox": _union_line_bboxes(lines, block.get("bbox")),+ "lines": lines,+ }+ items.append(_convert_leaf_block(synthetic_block, item_type, width, height, inherited=None))+ return items+++def _union_line_bboxes(lines: list[dict[str, Any]], fallback: Any) -> Any:+ """合并一个旧列表项的物理行框,缺失时回退列表父框。"""+ bboxes = [line.get("bbox") for line in lines]+ valid = [+ bbox+ for bbox in bboxes+ if isinstance(bbox, (list, tuple))+ and len(bbox) == 4+ and all(isinstance(item, (int, float)) and not isinstance(item, bool) for item in bbox)+ ]+ if not valid:+ return fallback+ return [+ min(float(bbox[0]) for bbox in valid),+ min(float(bbox[1]) for bbox in valid),+ max(float(bbox[2]) for bbox in valid),+ max(float(bbox[3]) for bbox in valid),+ ]+++def _convert_leaf_block(+ block: dict[str, Any],+ block_type: str,+ width: float,+ height: float,+ inherited: dict[str, Any] | None,+) -> dict[str, Any]:+ """把一个 3.4.5 叶子块转换为当前 raw block 字典。"""+ inherited = inherited or {}+ raw_bbox = block.get("bbox", inherited.get("bbox"))+ bbox = _normalize_bbox(raw_bbox, width, height)+ lines = block.get("lines")+ legacy_lines = lines if isinstance(lines, list) else []+ effective_sub_type = _effective_sub_type(block, block_type, inherited)++ raw: dict[str, Any] = {"type": block_type, "bbox": bbox}+ if _uses_inline_content(block_type, effective_sub_type):+ raw["content"] = _extract_inline_content(block, legacy_lines, preserve_line_breaks=block_type == "index")+ elif block_type in _STRING_CONTENT_BLOCK_TYPES:+ raw["content"] = _extract_string_content(block, legacy_lines, block_type)++ image_fields = _extract_image_fields(block, legacy_lines)+ raw.update(image_fields)++ normalized_lines = _normalize_lines(legacy_lines, width, height)+ if normalized_lines:+ raw["lines"] = normalized_lines++ _copy_leaf_metadata(raw, block, block_type, effective_sub_type, inherited)+ return raw+++def _effective_sub_type(block: dict[str, Any], block_type: str, inherited: dict[str, Any]) -> str | None:+ """解析 code/image/chart body 的有效 sub_type。"""+ sub_type = block.get("sub_type", inherited.get("sub_type"))+ if isinstance(sub_type, str) and sub_type.strip():+ return sub_type.strip()+ if block_type == "code_body":+ return "code"+ return None+++def _uses_inline_content(block_type: str, sub_type: str | None) -> bool:+ """判断当前 raw block 是否必须使用结构化 InlineSpan 列表。"""+ return block_type in _INLINE_CONTENT_BLOCK_TYPES or (block_type == "code_body" and sub_type == "algorithm")+++def _extract_inline_content(+ block: dict[str, Any],+ lines: list[Any],+ *,+ preserve_line_breaks: bool,+) -> list[dict[str, Any]]:+ """从旧 lines/spans 或直接 content 构造严格 InlineSpan 列表。"""+ line_contents: list[list[InlineSpan]] = []+ for line in lines:+ if not isinstance(line, dict):+ continue+ spans = line.get("spans")+ if not isinstance(spans, list):+ continue+ converted: list[dict[str, Any]] = []+ for span in spans:+ if not isinstance(span, dict):+ continue+ _append_legacy_span(converted, span)+ parsed = parse_inline_spans(converted)+ if parsed:+ line_contents.append(parsed)++ if not line_contents:+ direct_content = block.get("content")+ converted = _convert_direct_inline_content(direct_content)+ return [span.model_dump(mode="json") for span in parse_inline_spans(converted)]++ if preserve_line_breaks:+ joined: list[dict[str, Any]] = []+ for line_index, content in enumerate(line_contents):+ if line_index:+ _append_text_span(joined, "\n", ())+ _extend_span_dicts(joined, [span.model_dump(mode="json") for span in content])+ return [span.model_dump(mode="json") for span in parse_inline_spans(joined)]++ joined_spans = join_inline_spans(line_contents)+ return [span.model_dump(mode="json") for span in joined_spans]+++def _convert_direct_inline_content(content: Any) -> list[dict[str, Any]]:+ """转换没有 lines 包装的旧字符串或 span 列表。"""+ if isinstance(content, str):+ return _parse_legacy_markup(content)+ if not isinstance(content, list):+ return []+ output: list[dict[str, Any]] = []+ for item in content:+ if isinstance(item, dict):+ _append_legacy_span(output, item)+ elif isinstance(item, str):+ _extend_span_dicts(output, _parse_legacy_markup(item))+ return output+++def _append_legacy_span(output: list[dict[str, Any]], span: dict[str, Any]) -> None:+ """把一个 3.4.5 span 追加为当前 InlineSpan 字典。"""+ span_type = str(span.get("type", "text") or "text")+ content = span.get("content")+ if span_type in {"inline_equation", "equation_inline", "interline_equation", "equation"}:+ normalized = str(content or "").strip()+ if normalized:+ output.append({"type": "equation_inline", "content": normalized})+ return+ if span_type in {"code", "code_inline"}:+ if isinstance(content, str) and content:+ output.append({"type": "code_inline", "content": content})+ return+ if span_type == "hyperlink":+ _append_legacy_hyperlink(output, span)+ return+ if not isinstance(content, str) or not content:+ return++ styles = _normalize_styles(span.get("styles", span.get("style")))+ if styles:+ _append_text_span(output, content, styles)+ else:+ _extend_span_dicts(output, _parse_legacy_markup(content))+++def _append_legacy_hyperlink(output: list[dict[str, Any]], span: dict[str, Any]) -> None:+ """转换结构化旧 hyperlink;不安全目标降级为可见子内容。"""+ children: list[dict[str, Any]] = []+ raw_children = span.get("children")+ if isinstance(raw_children, list):+ for child in raw_children:+ if isinstance(child, dict):+ _append_legacy_span(children, child)+ elif isinstance(span.get("content"), str):+ styles = _normalize_styles(span.get("styles", span.get("style")))+ if styles:+ _append_text_span(children, span["content"], styles)+ else:+ _extend_span_dicts(children, _parse_legacy_markup(span["content"]))++ safe_children = [child for child in children if child.get("type") != "hyperlink"]+ safe_url = sanitize_hyperlink_target(+ html.unescape(str(span.get("url", ""))),+ allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,+ allow_relative=True,+ allow_fragment=True,+ )+ if safe_url and safe_children:+ output.append({"type": "hyperlink", "url": safe_url, "content": safe_children})+ else:+ _extend_span_dicts(output, safe_children)+++def _parse_legacy_markup(content: str) -> list[dict[str, Any]]:+ """按 3.4.5 的私有字符串标签协议解析行内内容。"""+ output: list[dict[str, Any]] = []+ cursor = 0+ while match := _INLINE_START_RE.search(content, cursor):+ _append_text_span(output, content[cursor : match.start()], ())+ tag = match.group("tag").lower()+ closing = _find_matching_close(content, tag, match.end())+ if closing is None:+ _append_text_span(output, match.group(0), ())+ cursor = match.end()+ continue++ inner = content[match.end() : closing[0]]+ original = content[match.start() : closing[1]]+ parsed = _parse_legacy_element(tag, match.group("attrs") or "", inner)+ if parsed is None:+ _append_text_span(output, original, ())+ else:+ _extend_span_dicts(output, parsed)+ cursor = closing[1]+ _append_text_span(output, content[cursor:], ())+ return output+++def _find_matching_close(content: str, tag: str, start: int) -> tuple[int, int] | None:+ """查找旧标签的配对结束位置,并兼容同名嵌套。"""+ token_re = re.compile(rf"<(?P<close>/)?{re.escape(tag)}(?:\s[^<>]*?)?>", re.IGNORECASE)+ depth = 1+ for match in token_re.finditer(content, start):+ depth += -1 if match.group("close") else 1+ if depth == 0:+ return match.start(), match.end()+ return None+++def _parse_legacy_element(tag: str, attrs: str, inner: str) -> list[dict[str, Any]] | None:+ """把一个完整旧标签转换为当前 InlineSpan 字典。"""+ if tag == "eq":+ latex = html.unescape(inner).strip()+ return [{"type": "equation_inline", "content": latex}] if latex else []+ if tag == "code":+ code = html.unescape(inner)+ return [{"type": "code_inline", "content": code}] if code else []+ if tag == "hyperlink":+ return _parse_markup_hyperlink(inner)++ children = _parse_legacy_markup(inner)+ styles = _parse_style_attribute(attrs) if tag == "text" else [_DIRECT_TAG_STYLES[tag]]+ return _apply_styles(children, styles)+++def _parse_markup_hyperlink(inner: str) -> list[dict[str, Any]] | None:+ """解析旧 hyperlink 标签;危险 URL 只移除链接语义。"""+ match = _URL_RE.search(inner)+ if match is None:+ return None+ label_content = f"{inner[: match.start()]}{inner[match.end() :]}"+ children = [span for span in _parse_legacy_markup(label_content) if span.get("type") != "hyperlink"]+ if not children:+ return []+ safe_url = sanitize_hyperlink_target(+ html.unescape(match.group("url")),+ allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,+ allow_relative=True,+ allow_fragment=True,+ )+ if safe_url is None:+ return children+ return [{"type": "hyperlink", "url": safe_url, "content": children}]+++def _parse_style_attribute(attrs: str) -> list[str]:+ """读取旧 ``text style`` 属性并过滤为当前白名单样式。"""+ match = _STYLE_ATTR_RE.search(attrs)+ return _normalize_styles(match.group("style") if match else None)+++def _normalize_styles(value: Any) -> list[str]:+ """按当前固定顺序去重旧样式,并消解同时上下标的非法组合。"""+ if isinstance(value, str):+ candidates = [item.strip().lower() for item in value.split(",")]+ elif isinstance(value, (list, tuple, set)):+ candidates = [str(item).strip().lower() for item in value]+ else:+ candidates = []+ style_set = {item for item in candidates if item in INLINE_STYLE_ORDER}+ if "superscript" in style_set and "subscript" in style_set:+ style_set.remove("subscript")+ return [style for style in INLINE_STYLE_ORDER if style in style_set]+++def _apply_styles(spans: list[dict[str, Any]], styles: list[str]) -> list[dict[str, Any]]:+ """把旧包装标签的样式递归应用到文字及链接文字。"""+ if not styles:+ return spans+ output: list[dict[str, Any]] = []+ for span in spans:+ span_type = span.get("type")+ if span_type == "text":+ merged_styles = _normalize_styles([*_normalize_styles(span.get("styles")), *styles])+ _append_text_span(output, str(span.get("content", "")), merged_styles)+ elif span_type == "hyperlink" and isinstance(span.get("content"), list):+ children = _apply_styles([child for child in span["content"] if isinstance(child, dict)], styles)+ output.append({**span, "content": children})+ else:+ output.append(dict(span))+ return output+++def _append_text_span(output: list[dict[str, Any]], content: str, styles: Any) -> None:+ """追加非空文字,并合并相邻同样式 TextSpan。"""+ if not content:+ return+ normalized_styles = _normalize_styles(styles)+ if output and output[-1].get("type") == "text" and output[-1].get("styles", []) == normalized_styles:+ output[-1]["content"] = f"{output[-1].get('content', '')}{content}"+ return+ span: dict[str, Any] = {"type": "text", "content": content}+ if normalized_styles:+ span["styles"] = normalized_styles+ output.append(span)+++def _extend_span_dicts(output: list[dict[str, Any]], spans: list[dict[str, Any]]) -> None:+ """追加一组 Span,并规范化序列边界上的相邻文字。"""+ for span in spans:+ if span.get("type") == "text" and isinstance(span.get("content"), str):+ _append_text_span(output, span["content"], span.get("styles", []))+ else:+ output.append(dict(span))+++def _extract_string_content(block: dict[str, Any], lines: list[Any], block_type: str) -> str:+ """从旧 spans 提取公式、视觉主体、表格 HTML 或代码字符串。"""+ parts: list[str] = []+ for line in lines:+ if not isinstance(line, dict):+ continue+ line_parts: list[str] = []+ spans = line.get("spans")+ if not isinstance(spans, list):+ continue+ for span in spans:+ if not isinstance(span, dict):+ continue+ value = span.get("html") if block_type == "table_body" and span.get("html") is not None else span.get("content")+ normalized = _stringify_visual_content(value)+ if normalized:+ line_parts.append(normalized)+ if line_parts:+ parts.append("".join(line_parts))++ if not parts:+ direct = block.get("html") if block_type == "table_body" and block.get("html") is not None else block.get("content")+ return _stringify_visual_content(direct)+ return "\n".join(parts) if block_type == "code_body" else "".join(parts)+++def _stringify_visual_content(value: Any) -> str:+ """把旧视觉识别列表稳定折叠为当前字符串载荷。"""+ if isinstance(value, str):+ return value+ if isinstance(value, list):+ return "\n".join(str(item) for item in value if str(item).strip())+ return "" if value is None else str(value)+++def _extract_image_fields(block: dict[str, Any], lines: list[Any]) -> dict[str, str]:+ """从 block 或第一个视觉 span 提升当前支持的图片载荷字段。"""+ fields: dict[str, str] = {}+ for field_name in ("image_path", "image_base64", "image_url"):+ value = block.get(field_name)+ if isinstance(value, str) and value:+ fields[field_name] = value+ if fields:+ return fields+ for line in lines:+ if not isinstance(line, dict):+ continue+ spans = line.get("spans")+ if not isinstance(spans, list):+ continue+ for span in spans:+ if not isinstance(span, dict):+ continue+ for field_name in ("image_path", "image_base64", "image_url"):+ value = span.get(field_name)+ if isinstance(value, str) and value and field_name not in fields:+ fields[field_name] = value+ if fields:+ return fields+ return fields+++def _copy_leaf_metadata(+ raw: dict[str, Any],+ block: dict[str, Any],+ block_type: str,+ sub_type: str | None,+ inherited: dict[str, Any],+) -> None:+ """复制当前后处理仍会读取、且不会越过严格模型边界的字段。"""+ if block.get("level") is not None:+ raw["level"] = block["level"]+ if sub_type:+ raw["sub_type"] = sub_type+ guess_lang = block.get("guess_lang", inherited.get("guess_lang"))+ if block_type == "code_body" and isinstance(guess_lang, str) and guess_lang.strip():+ raw["guess_lang"] = guess_lang.strip()+ if block_type == "table_body" and "cell_merge" in inherited:+ raw["cell_merge"] = inherited["cell_merge"]+ if block_type in {"doc_title", "paragraph_title", "page_footnote"}:+ anchor = block.get("anchor")+ if isinstance(anchor, str) and anchor.strip():+ raw["anchor"] = anchor.strip()+++def _normalize_block_type(block: dict[str, Any]) -> str:+ """把 3.4.5 block discriminator 映射到当前 raw block 类型。"""+ block_type = str(block.get("type", "") or "")+ if block_type == "title":+ return "doc_title" if block.get("level") == 1 else "paragraph_title"+ return _BLOCK_TYPE_ALIASES.get(block_type, block_type)+++def _normalize_bbox(value: Any, width: float, height: float) -> tuple[float, float, float, float]:+ """把旧 bbox 规范为当前严格的 0-1 非零面积坐标。"""+ if not isinstance(value, (list, tuple)) or len(value) != 4:+ return _PLACEHOLDER_BBOX+ if any(isinstance(item, bool) or not isinstance(item, (int, float)) for item in value):+ return _PLACEHOLDER_BBOX+ coords = tuple(float(item) for item in value)+ if not all(math.isfinite(item) for item in coords):+ return _PLACEHOLDER_BBOX+ if width > 0 and height > 0:+ coords = (coords[0] / width, coords[1] / height, coords[2] / width, coords[3] / height)+ elif not all(0.0 <= item <= 1.0 for item in coords):+ return _PLACEHOLDER_BBOX+ clamped = tuple(min(max(item, 0.0), 1.0) for item in coords)+ if clamped[2] <= clamped[0] or clamped[3] <= clamped[1]:+ return _PLACEHOLDER_BBOX+ return clamped # type: ignore[return-value]+++def _normalize_lines(lines: list[Any], width: float, height: float) -> list[dict[str, list[float]]]:+ """保留跨页文本合并需要的行框,并转换到当前归一化坐标。"""+ result: list[dict[str, list[float]]] = []+ for line in lines:+ if not isinstance(line, dict):+ continue+ bbox = _normalize_bbox(line.get("bbox"), width, height)+ result.append({"bbox": list(bbox)})+ return result+++__all__ = ["legacy_page_to_model_list"]diff --git a/mineru/doclib/background/compaction.py b/mineru/doclib/background/compaction.pyindex 8388139e..35745d9c 100644--- a/mineru/doclib/background/compaction.py+++ b/mineru/doclib/background/compaction.py@@ -21,11 +21,45 @@ logger = logging.getLogger("mineru.compaction")def _normalize_batch_pages(batch_payload: dict[str, Any]) -> list[dict[str, Any]]:- """只接受 3.0 batch;旧缓存由正常缺失路径重新调度解析。"""- if batch_payload.get("schema_version") != MIDDLE_JSON_SCHEMA_VERSION:+ """统一读取 3.0 batch,或把 3.4.5/1.0 页面转换为当前 page 字典。"""+ schema_version = batch_payload.get("schema_version")+ raw_pages = batch_payload.get("pages")+ if schema_version == MIDDLE_JSON_SCHEMA_VERSION:+ return raw_pages if isinstance(raw_pages, list) else []++ if schema_version == "1.0":+ pass+ elif schema_version is None:+ raw_pages = batch_payload.get("pdf_info")+ else:+ raw_pages = None+ if not isinstance(raw_pages, list) or any(not isinstance(page, dict) for page in raw_pages):raise ValueError("stale Middle JSON cache requires source reparse")- raw_pages = batch_payload.get("pages", [])- return raw_pages if isinstance(raw_pages, list) else []++ from ...backend.postprocess.legacy_schema_adapter import legacy_page_to_model_list+ from ...backend.postprocess.pages import model_json_to_pages+ from ...parser.base import (+ _legacy_effort,+ _legacy_file_suffix,+ _legacy_page_index_map,+ _legacy_parse_mode,+ )+ from ...types import ModelJson+ from ...version import __version__ as current_mineru_version++ source_version = batch_payload.get("_version_name", batch_payload.get("mineru_version"))+ mineru_version = (+ source_version.strip() if isinstance(source_version, str) and source_version.strip() else current_mineru_version+ )+ model_json = ModelJson(+ pages=[legacy_page_to_model_list(page) for page in raw_pages],+ page_index_map=_legacy_page_index_map(raw_pages),+ file_suffix=_legacy_file_suffix(batch_payload),+ effort=_legacy_effort(batch_payload),+ parse_mode=_legacy_parse_mode(batch_payload),+ mineru_version=mineru_version,+ )+ return [page.to_dict() for page in model_json_to_pages(model_json)]class Compaction:diff --git a/mineru/parser/base.py b/mineru/parser/base.pyindex c91bb8ff..37515c66 100644--- a/mineru/parser/base.py+++ b/mineru/parser/base.py@@ -6,11 +6,11 @@ from abc import ABC, abstractmethodfrom copy import deepcopyfrom dataclasses import dataclassfrom pathlib import Path-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Literal, castfrom ..render import render_markdown, render_structured_contentfrom ..render.contracts import ImageRenderer, RenderMode-from ..types import MiddleJson, ModelJson, PageInfo+from ..types import FILE_SUFFIXES, FileSuffix, MiddleJson, ModelJson, PageInfofrom ..utils.image_payload import ImagePayloadCachefrom .writer import DataWriter@@ -18,6 +18,10 @@ if TYPE_CHECKING:from ..model.flash.pdf.document import PDFDocumentMIDDLE_JSON_SCHEMA_VERSION: str = "3.0"+_LEGACY_SCHEMA_VERSION: str = "1.0"+_LEGACY_DEFAULT_FILE_SUFFIX: FileSuffix = "pdf"+_LEGACY_DEFAULT_EFFORT: Literal["flash", "medium", "high", "xhigh"] = "medium"+_LEGACY_DEFAULT_PARSE_MODE: Literal["txt", "ocr"] = "txt"_PDF_RETAINED_PAGE_INDICES_KEY = "_pdf_retained_page_indices"_PDF_BROKEN_PAGE_INDICES_KEY = "_pdf_broken_page_indices"_TO_DICT_EXCLUDED_KEYS: frozenset[str] = frozenset(@@ -37,6 +41,62 @@ def _parse_optional_int_list(value: Any) -> list[int] | None:return parsed+def _legacy_raw_pages(payload: dict[str, Any]) -> list[dict[str, Any]] | None:+ """按 envelope 识别 3.4.5 原始 pdf_info 或后续 1.0 pages 包装。++ 3.4.5 release tag 内部仍报告 3.4.4,因此不能把 ``_version_name`` 作为+ 唯一判据。+ """+ schema_version = payload.get("schema_version")+ raw_pages = payload.get("pdf_info") if schema_version is None else None+ if raw_pages is None and schema_version == _LEGACY_SCHEMA_VERSION:+ raw_pages = payload.get("pages")+ if not isinstance(raw_pages, list) or any(not isinstance(page, dict) for page in raw_pages):+ return None+ return raw_pages+++def _legacy_page_index_map(raw_pages: list[dict[str, Any]]) -> list[int]:+ """从旧 page_idx 恢复抽页映射;连续零起始页面仍表示整本文档。"""+ page_indices: list[int] = []+ for fallback_index, page in enumerate(raw_pages):+ page_idx = page.get("page_idx", fallback_index)+ if isinstance(page_idx, bool) or not isinstance(page_idx, int) or page_idx < 0:+ raise ValueError("legacy Middle JSON page_idx values must be non-negative integers")+ page_indices.append(page_idx)+ if len(page_indices) != len(set(page_indices)) or any(+ current <= previous for previous, current in zip(page_indices, page_indices[1:])+ ):+ raise ValueError("legacy Middle JSON page_idx values must be unique and strictly increasing")+ return [] if page_indices == list(range(len(raw_pages))) else page_indices+++def _legacy_file_suffix(payload: dict[str, Any]) -> FileSuffix:+ """读取旧 payload 可选后缀;缺失时沿用历史 PDF 默认值。"""+ value = payload.get("file_suffix")+ if isinstance(value, str) and value in FILE_SUFFIXES:+ return cast(FileSuffix, value)+ return _LEGACY_DEFAULT_FILE_SUFFIX+++def _legacy_effort(payload: dict[str, Any]) -> Literal["flash", "medium", "high", "xhigh"]:+ """把 3.4.5 的分析强度映射到当前严格枚举。"""+ value = payload.get("_effort", payload.get("effort"))+ if value in {"flash", "medium", "high", "xhigh"}:+ return cast(Literal["flash", "medium", "high", "xhigh"], value)+ return _LEGACY_DEFAULT_EFFORT+++def _legacy_parse_mode(payload: dict[str, Any]) -> Literal["txt", "ocr"]:+ """优先读取显式 parse_mode,否则按 3.4.5 的 _ocr_enable 推断。"""+ value = payload.get("parse_mode")+ if value in {"txt", "ocr"}:+ return cast(Literal["txt", "ocr"], value)+ if payload.get("_ocr_enable") is True:+ return "ocr"+ return _LEGACY_DEFAULT_PARSE_MODE++@dataclassclass ParseResult:"""The parsed result of a document.@@ -73,12 +133,15 @@ class ParseResult:retained_page_indices = _parse_optional_int_list(d.get(_PDF_RETAINED_PAGE_INDICES_KEY))broken_page_indices = _parse_optional_int_list(d.get(_PDF_BROKEN_PAGE_INDICES_KEY))- if schema_version != MIDDLE_JSON_SCHEMA_VERSION:+ if schema_version == MIDDLE_JSON_SCHEMA_VERSION:+ middle_json = ParseResult._build_middle_json_from_v3(d)+ elif (raw_pages := _legacy_raw_pages(d)) is not None:+ middle_json = ParseResult._build_middle_json_from_legacy(d, raw_pages)+ else:raise ValueError(f"Unsupported Middle JSON schema_version={schema_version!r}; "f"expected {MIDDLE_JSON_SCHEMA_VERSION!r}. Reparse the source document.")- middle_json = ParseResult._build_middle_json_from_v3(d)return ParseResult(middle_json=middle_json,@@ -92,6 +155,34 @@ class ParseResult:payload = {k: v for k, v in d.items() if k not in _TO_DICT_EXCLUDED_KEYS}return MiddleJson.model_validate(payload)+ @staticmethod+ def _build_middle_json_from_legacy(d: dict[str, Any], raw_pages: list[dict[str, Any]]) -> MiddleJson:+ """把 3.4.5 页面回推为 raw ModelJson,再走当前统一后处理生成 3.0。"""+ from ..backend.postprocess.legacy_schema_adapter import legacy_page_to_model_list+ from ..backend.postprocess.pages import model_json_to_pages+ from ..version import __version__ as current_mineru_version++ source_version = d.get("_version_name", d.get("mineru_version"))+ mineru_version = (+ source_version.strip() if isinstance(source_version, str) and source_version.strip() else current_mineru_version+ )+ model_json = ModelJson(+ pages=[legacy_page_to_model_list(page) for page in raw_pages],+ page_index_map=_legacy_page_index_map(raw_pages),+ file_suffix=_legacy_file_suffix(d),+ effort=_legacy_effort(d),+ parse_mode=_legacy_parse_mode(d),+ mineru_version=mineru_version,+ )+ return MiddleJson(+ pages=model_json_to_pages(model_json),+ is_full_document=model_json.is_full_document,+ file_suffix=model_json.file_suffix,+ effort=model_json.effort,+ parse_mode=model_json.parse_mode,+ mineru_version=model_json.mineru_version,+ )+def to_dict(self, *, skip_defaults: bool = True) -> dict[str, Any]:payload: dict[str, Any] = {"schema_version": MIDDLE_JSON_SCHEMA_VERSION}payload.update(self.middle_json.to_dict(skip_defaults=skip_defaults))diff --git a/tests/unittest/test_legacy_schema_adapter.py b/tests/unittest/test_legacy_schema_adapter.pynew file mode 100644index 00000000..7fb22e18--- /dev/null+++ b/tests/unittest/test_legacy_schema_adapter.py@@ -0,0 +1,274 @@+from copy import deepcopy++import pytest++from mineru.backend.postprocess.legacy_schema_adapter import legacy_page_to_model_list+from mineru.backend.postprocess.pages import model_json_to_pages+from mineru.doclib.background.compaction import _normalize_batch_pages+from mineru.types import BlockType, ModelJson+++def _legacy_line(content: str, *, bbox: list[int] | None = None) -> dict:+ """构造 3.4.5 普通文字行。"""+ return {+ "bbox": bbox or [10, 10, 90, 20],+ "spans": [{"type": "text", "content": content}],+ }+++def _current_pages(raw_pages: list[list[dict]]) -> list:+ """把适配后的 raw pages 送入当前严格后处理。"""+ model_json = ModelJson(+ pages=raw_pages,+ page_index_map=[],+ file_suffix="pdf",+ effort="medium",+ parse_mode="txt",+ mineru_version="3.4.5",+ )+ return model_json_to_pages(model_json)+++def test_legacy_adapter_converts_inline_spans_without_mutating_input() -> None:+ """验证文字标签、公式、链接及危险链接降级,并保证输入不变。"""+ page = {+ "page_idx": 0,+ "page_size": [100, 100],+ "preproc_blocks": [+ {+ "type": "text",+ "bbox": [10, 10, 90, 30],+ "lines": [+ {+ "bbox": [10, 10, 90, 30],+ "spans": [+ {+ "type": "text",+ "content": (+ 'plain <text style="bold,italic">styled</text> '+ "<eq>x^2</eq> "+ "<hyperlink><text>safe</text><url>https://example.com</url></hyperlink> "+ "<hyperlink><text>unsafe</text><url>javascript:alert(1)</url></hyperlink>"+ ),+ }+ ],+ }+ ],+ }+ ],+ "discarded_blocks": [],+ }+ original = deepcopy(page)++ raw_page = legacy_page_to_model_list(page)+ content = raw_page[0]["content"]++ assert page == original+ assert content == [+ {"type": "text", "content": "plain ", "styles": []},+ {"type": "text", "content": "styled", "styles": ["bold", "italic"]},+ {"type": "text", "content": " ", "styles": []},+ {"type": "equation_inline", "content": "x^2"},+ {"type": "text", "content": " ", "styles": []},+ {+ "type": "hyperlink",+ "url": "https://example.com",+ "content": [{"type": "text", "content": "safe", "styles": []}],+ },+ {"type": "text", "content": " unsafe", "styles": []},+ ]+ pages = _current_pages([raw_page])+ assert pages[0].blocks[0].type == BlockType.TEXT+++def test_legacy_adapter_preserves_visual_metadata_and_algorithm_spans() -> None:+ """验证视觉父块展平后能由当前后处理恢复表格与算法块。"""+ page = {+ "page_idx": 0,+ "page_size": [100, 100],+ "para_blocks": [+ {+ "type": "table",+ "bbox": [10, 10, 90, 60],+ "cell_merge": [0, 1],+ "blocks": [+ {+ "type": "table_caption",+ "bbox": [10, 10, 90, 20],+ "lines": [_legacy_line("表 1")],+ },+ {+ "type": "table_body",+ "bbox": [10, 20, 90, 60],+ "lines": [+ {+ "bbox": [10, 20, 90, 60],+ "spans": [+ {+ "type": "table",+ "html": "<table><tr><td>x</td></tr></table>",+ "image_path": "images/table.png",+ }+ ],+ }+ ],+ },+ ],+ },+ {+ "type": "code",+ "sub_type": "algorithm",+ "bbox": [10, 70, 90, 90],+ "blocks": [+ {+ "type": "code_body",+ "bbox": [10, 70, 90, 90],+ "lines": [+ {+ "bbox": [10, 70, 90, 90],+ "spans": [+ {"type": "text", "content": "a="},+ {"type": "inline_equation", "content": "x"},+ ],+ }+ ],+ }+ ],+ },+ ],+ "discarded_blocks": [{"type": "header", "bbox": [10, 1, 90, 5], "lines": [_legacy_line("Header")]}],+ }++ pages = _current_pages([legacy_page_to_model_list(page)])+ table, code, header = pages[0].blocks++ assert table.type == BlockType.TABLE+ assert table.cell_merge == [0, 1]+ assert table.content[1].image_path == "images/table.png"+ assert code.type == BlockType.CODE+ assert code.sub_type == "algorithm"+ assert code.content[0].type == BlockType.ALGORITHM_BODY+ assert [span.type for span in code.content[0].content] == ["text", "equation_inline"]+ assert header.type == BlockType.HEADER+++def test_legacy_adapter_normalizes_bbox_and_block_aliases() -> None:+ """验证像素坐标、越界坐标及旧 discriminator 均转换为当前合法值。"""+ page = {+ "page_size": [200, 100],+ "preproc_blocks": [+ {+ "type": "title",+ "level": 1,+ "bbox": [-10, 0, 220, 20],+ "lines": [_legacy_line("Document")],+ },+ {+ "type": "interline_equation",+ "bbox": [0, 30, 100, 50],+ "lines": [+ {+ "bbox": [0, 30, 100, 50],+ "spans": [{"type": "interline_equation", "content": "y=1"}],+ }+ ],+ },+ ],+ "discarded_blocks": [],+ }++ raw_page = legacy_page_to_model_list(page)++ assert raw_page[0]["type"] == "doc_title"+ assert raw_page[0]["bbox"] == (0.0, 0.0, 1.0, 0.2)+ assert raw_page[1]["type"] == "equation"+ assert raw_page[1]["content"] == "y=1"+ _current_pages([raw_page])+++def test_legacy_adapter_recovers_pdf_list_items_from_line_flags() -> None:+ """验证旧 PDF list 的物理行重新生成当前列表文本子块。"""+ page = {+ "page_size": [100, 100],+ "preproc_blocks": [+ {+ "type": "list",+ "bbox": [10, 10, 90, 40],+ "lines": [+ {+ "bbox": [10, 10, 90, 20],+ "is_list_start_line": True,+ "spans": [{"type": "text", "content": "one"}],+ },+ {+ "bbox": [10, 25, 90, 35],+ "is_list_start_line": True,+ "spans": [{"type": "text", "content": "two"}],+ },+ ],+ }+ ],+ "discarded_blocks": [],+ }++ pages = _current_pages([legacy_page_to_model_list(page)])+ list_block = pages[0].blocks[0]++ assert list_block.type == BlockType.LIST+ assert [child.content[0].content for child in list_block.content] == ["one", "two"]+++def test_legacy_adapter_separates_office_blocks_with_synthetic_bbox_groups() -> None:+ """验证无 page_size 时列表不会吸收相邻 Office 正文块。"""+ page = {+ "para_blocks": [+ {"type": "text", "lines": [{"spans": [{"type": "text", "content": "before"}]}]},+ {+ "type": "list",+ "blocks": [+ {"type": "text", "lines": [{"spans": [{"type": "text", "content": "item"}]}]},+ ],+ },+ {"type": "text", "lines": [{"spans": [{"type": "text", "content": "after"}]}]},+ ],+ "discarded_blocks": [],+ }++ pages = _current_pages([legacy_page_to_model_list(page)])++ assert [block.type for block in pages[0].blocks] == [BlockType.TEXT, BlockType.LIST, BlockType.TEXT]+ assert pages[0].blocks[0].content[0].content == "before"+ assert pages[0].blocks[1].content[0].content[0].content == "item"+ assert pages[0].blocks[2].content[0].content == "after"+++def test_doclib_compaction_converts_schema_v1_pages_with_current_adapter() -> None:+ """验证 Doclib 历史调用点重新通过适配器生成 3.0 page 字典。"""+ payload = {+ "schema_version": "1.0",+ "pages": [+ {+ "page_idx": 3,+ "page_size": [100, 100],+ "preproc_blocks": [+ {+ "type": "text",+ "bbox": [10, 10, 90, 20],+ "lines": [_legacy_line("cached")],+ }+ ],+ "discarded_blocks": [],+ }+ ],+ }++ pages = _normalize_batch_pages(payload)++ assert pages[0]["page_idx"] == 3+ assert pages[0]["blocks"][0]["content"] == [{"type": "text", "content": "cached"}]+++def test_doclib_compaction_rejects_unknown_legacy_schema() -> None:+ """验证 2.0 等未支持旧 schema 不会被误当成 3.4.5 页面吞掉。"""+ with pytest.raises(ValueError, match="source reparse"):+ _normalize_batch_pages({"schema_version": "2.0", "pages": [{"page_idx": 0, "blocks": []}]})diff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.pyindex e319b28e..89c2ce1d 100644--- a/tests/unittest/test_parse_result_contract.py+++ b/tests/unittest/test_parse_result_contract.py@@ -129,35 +129,56 @@ def test_parse_result_from_dict_rejects_missing_pages() -> None:ParseResult.from_dict({"schema_version": MIDDLE_JSON_SCHEMA_VERSION})-def test_parse_result_from_json_rejects_legacy_pages() -> None:+def test_parse_result_from_json_converts_mineru_3_4_5_middle_json() -> None:+ """验证 ParseResult 恢复 3.4.5 pdf_info 调用链并生成严格 3.0。"""data = {- "pages": [+ "_backend": "hybrid",+ "_effort": "high",+ "_ocr_enable": True,+ "_version_name": "3.4.4",+ "pdf_info": [{- "page_idx": 0,- "para_blocks": [+ "page_idx": 2,+ "page_size": [100, 100],+ "preproc_blocks": [{"index": 0,"type": "text",- "bbox": [0.0, 0.0, 0.0, 0.0],+ "bbox": [10, 10, 90, 20],"lines": [{- "bbox": [0.0, 0.0, 0.0, 0.0],+ "bbox": [10, 10, 90, 20],"spans": [{"type": "text", "bbox": [0.0, 0.0, 0.0, 0.0], "content": "round trip"}],}],}],+ "discarded_blocks": [],}- ]+ ],}- with pytest.raises(ValueError, match="Reparse the source document"):- ParseResult.from_json(json.dumps(data))+ restored = ParseResult.from_json(json.dumps(data))++ assert restored.pages[0].page_idx == 2+ assert restored.pages[0].blocks[0].content[0].content == "round trip"+ assert restored.middle_json.is_full_document is False+ assert restored.middle_json.effort == "high"+ assert restored.middle_json.parse_mode == "ocr"+ assert restored.middle_json.mineru_version == "3.4.4"+++def test_parse_result_accepts_schema_v1_page_wrapper() -> None:+ """验证旧调用方的 1.0 pages envelope 继续委托同一适配器。"""+ restored = ParseResult.from_dict({"schema_version": "1.0", "pages": []})++ assert restored.pages == []+ assert restored.middle_json.is_full_document is True[email protected]("schema_version", [None, "1.0", "2.0"])[email protected]("schema_version", [None, "2.0"])def test_parse_result_rejects_pre_v3_schema_versions(schema_version: str | None) -> None:- """验证缺失版本与 1.0/2.0 payload 均明确要求重新解析源文件。"""+ """验证无版本 pages 与未支持的 2.0 payload 仍要求重新解析源文件。"""payload: dict[str, object] = {"pages": []}if schema_version is not None:payload["schema_version"] = schema_version