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: enhance document geometry analysis with layout and style risk detection
myhloli91eaf879da3a
diff --git a/CLAUDE.md b/CLAUDE.mdindex 66d36d5c..337393ac 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -198,6 +198,7 @@ schema 2.0 输出不再有 `_backend`/`_version_name`/`pdf_info`/`_ocr_enable`/`- `RenderFormat.MARKDOWN` → `render_markdown`- `RenderFormat.HTML` → `render_html`+- `RenderFormat.LATEX` → `render_latex`- `RenderFormat.DOCX` → `render_docx`- `RenderFormat.EPUB` → `render_epub`- `RenderFormat.STRUCTURED_CONTENT` → `render_structured_content`@@ -205,7 +206,7 @@ schema 2.0 输出不再有 `_backend`/`_version_name`/`pdf_info`/`_ocr_enable`/`- `RenderFormat.CONTENT_LIST_V2` → `render_content_list_v2`- `RenderFormat.PDF` → `render_pdf`-`render/_internal/` 下按目标格式分目录组织共享逻辑(`common/`/`markdown/`/`html/`/`docx/`/`epub/`/`pdf/`/`content_list/`/`structured_content/`),顶层同名模块只是惰性公共门面。InlineSpan 的规范化、连接、裁剪和可见文本操作归 `backend/postprocess/inline.py`,renderer 按 Span discriminator 分派,并只能单向依赖该模块和 `backend/postprocess/table_merge`。不再有 `pipeline_union_make`/`vlm_union_make`/`office_union_make` 三套逻辑;Content List V1/V2 是由严格 MiddleJson 派生的正式兼容输出,不恢复旧 backend 并行实现。EPUB、PDF 与两套 Content List 只扩展低层 `mineru.render` 公共面,不自动扩展 ParseResult、CLI、API Server 或 doclib 输出合同。+`render/_internal/` 下按目标格式分目录组织共享逻辑(`common/`/`markdown/`/`html/`/`latex/`/`docx/`/`epub/`/`pdf/`/`content_list/`/`structured_content/`),顶层同名模块只是惰性公共门面。InlineSpan 的规范化、连接、裁剪和可见文本操作归 `backend/postprocess/inline.py`,renderer 按 Span discriminator 分派,并只能单向依赖该模块和 `backend/postprocess/table_merge`。不再有 `pipeline_union_make`/`vlm_union_make`/`office_union_make` 三套逻辑;Content List V1/V2 是由严格 MiddleJson 派生的正式兼容输出,不恢复旧 backend 并行实现。LaTeX、EPUB、PDF 与两套 Content List 只扩展低层 `mineru.render` 公共面,不自动扩展 ParseResult、CLI、API Server 或 doclib 输出合同。### 5.1 目录职责diff --git a/mineru/model/flash/office/docx/docx_converter.py b/mineru/model/flash/office/docx/docx_converter.pyindex 7a6bcb8f..5d4359cd 100644--- a/mineru/model/flash/office/docx/docx_converter.py+++ b/mineru/model/flash/office/docx/docx_converter.py@@ -1706,6 +1706,56 @@ class DocxConverter:return (target or None), Falsereturn None, False+ @classmethod+ def _complex_field_instructions(+ cls,+ paragraph_element: BaseOxmlElement,+ ) -> list[str]:+ """按字段边界与嵌套顺序合并段落中被拆分的复杂字段指令。"""++ word_namespace = cls._BLIP_NAMESPACES["w"]+ field_char_tag = f"{{{word_namespace}}}fldChar"+ instruction_tag = f"{{{word_namespace}}}instrText"+ field_type_attr = f"{{{word_namespace}}}fldCharType"+ field_stack: list[_DocxComplexFieldFrame] = []+ instructions: list[str] = []++ def append_instruction(frame: _DocxComplexFieldFrame) -> None:+ """把一个字段已累计的非空指令追加到输出。"""++ instruction = "".join(frame.instruction_parts).strip()+ if instruction:+ instructions.append(instruction)++ for element in paragraph_element.iter():+ if element.tag == field_char_tag:+ field_type = element.get(field_type_attr)+ if field_type == "begin":+ field_stack.append(_DocxComplexFieldFrame())+ elif field_type == "separate" and field_stack:+ frame = field_stack[-1]+ if frame.phase == "instr":+ append_instruction(frame)+ frame.phase = "result"+ elif field_type == "end" and field_stack:+ frame = field_stack.pop()+ if frame.phase == "instr":+ append_instruction(frame)+ continue+ if element.tag != instruction_tag:+ continue+ text = element.text or ""+ if field_stack and field_stack[-1].phase == "instr":+ field_stack[-1].instruction_parts.append(text)+ elif text.strip():+ # 兼容缺少 fldChar 包裹、但过去可被逐节点解析的非规范指令。+ instructions.append(text.strip())++ for frame in field_stack:+ if frame.phase == "instr":+ append_instruction(frame)+ return instructions+@staticmethoddef _python_docx_hyperlink_target(hyperlink: Hyperlink) -> _ParagraphHyperlink:"""把 python-docx Hyperlink 的地址或 fragment 转换为行内目标。"""@@ -2970,11 +3020,10 @@ class DocxConverter:return anchors[0]field_anchors: list[str] = []- for instruction in paragraph_element.findall(- ".//w:instrText",- namespaces=DocxConverter._BLIP_NAMESPACES,+ for instruction in self._complex_field_instructions(+ paragraph_element,):- target, is_internal = self._complex_field_hyperlink_target(instruction.text or "")+ target, is_internal = self._complex_field_hyperlink_target(instruction)anchor = target.removeprefix("#") if target and is_internal else ""if anchor:field_anchors.append(anchor)diff --git a/mineru/model/flash/pdf/char_geometry.py b/mineru/model/flash/pdf/char_geometry.pyindex fb5f4c80..cdb038e7 100644--- a/mineru/model/flash/pdf/char_geometry.py+++ b/mineru/model/flash/pdf/char_geometry.py@@ -11,7 +11,7 @@ import unicodedatafrom collections import Counter, defaultdictfrom dataclasses import dataclass, fieldfrom functools import lru_cache-from typing import Any, Literal, TypeAlias+from typing import Any, Literal, Sequence, TypeAliasfrom ....types import BBoxfrom .document import PDFPageTextGeometry@@ -153,6 +153,20 @@ class DocumentGeometryPlan:}+@dataclass(frozen=True, slots=True)+class _DocumentGeometryRisk:+ """区分需要完整字符几何的布局风险与仅需字号校准的样式风险。"""++ layout: bool = False+ style: bool = False++ @property+ def any(self) -> bool:+ """返回当前文档是否需要进入完整字符样本收集。"""++ return self.layout or self.style++@dataclass(slots=True)class _CharSample:"""保存分析阶段使用的局部字符样本。"""@@ -427,18 +441,44 @@ def _source_bbox(return side_bbox+def _style_line_is_inflated(+ source_height: float,+ font_sizes: Sequence[float],+ tight_heights: Sequence[float],+) -> bool:+ """按统一阈值判断一行 loose 高度是否显著偏离字号与 tight 字形。"""++ if not tight_heights:+ return False+ style_scale = max(+ statistics.median(font_sizes) if font_sizes else 0.0,+ _quantile(tight_heights, 0.75),+ )+ if style_scale < STYLE_INFLATION_MIN_SCALE:+ return False+ tight_height = max(0.1, _quantile(tight_heights, 0.75))+ return (+ source_height > STYLE_INFLATION_LOOSE_FONT_RATIO * style_scale+ and source_height > STYLE_INFLATION_LOOSE_TIGHT_RATIO * tight_height+ )++def _document_requires_full_geometry(lines_by_page: list[list[_LineItem]],geometries: list[PDFPageTextGeometry],page_sizes: list[tuple[float, float]],-) -> bool:- """流式否决健康文档,避免为 identity 路径保留整本字符样本对象。"""+) -> _DocumentGeometryRisk:+ """流式识别布局与样式风险,避免健康文档保留整本字符样本。"""x_ratios: dict[RunKey, list[float]] = defaultdict(list)x_overlaps: dict[RunKey, int] = defaultdict(int)y_ratios: list[float] = []y_extreme_runs: Counter[RunKey] = Counter()- for lines, geometry, page_size in zip(lines_by_page, geometries, page_sizes, strict=True):+ style_line_counts: Counter[RunKey] = Counter()+ style_inflated_lines: dict[RunKey, set[LineKey]] = defaultdict(set)+ for page_index, (lines, geometry, page_size) in enumerate(+ zip(lines_by_page, geometries, page_sizes, strict=True),+ ):for line in lines:entries: list[tuple[int, str, BBox, BBox, tuple[float, float], RunKey, float]] = []for position, char in enumerate(line.chars):@@ -463,7 +503,7 @@ def _document_requires_full_geometry(font_size,))- if len(entries) < Y_MIN_ANCHOR_COUNT:+ if not entries:continueheight_q75 = _quantile([entry[3][3] - entry[3][1] for entry in entries], 0.75)anchors = [entry for entry in entries if entry[3][3] - entry[3][1] >= ANCHOR_MIN_TIGHT_HEIGHT_RATIO * height_q75]@@ -483,6 +523,25 @@ def _document_requires_full_geometry(if current[2][2] - following[3][0] >= 0.05 * max(following_width, 0.1):x_overlaps[current[5]] += 1+ anchors_by_run: dict[RunKey, list[tuple[int, str, BBox, BBox, tuple[float, float], RunKey, float]]] = defaultdict(+ list+ )+ for entry in anchors:+ anchors_by_run[entry[5]].append(entry)+ for run_key, run_entries in anchors_by_run.items():+ style_line_counts[run_key] += 1+ if _style_line_is_inflated(+ line.effective_height,+ [entry[6] for entry in run_entries if entry[6] > 0],+ [entry[3][3] - entry[3][1] for entry in run_entries],+ ):+ style_inflated_lines[run_key].add(+ (page_index, line.source_index),+ )++ # 四锚点门槛只约束 Y 分析;短行仍须为文档级 X 统计贡献相邻字符对。+ if len(anchors) < Y_MIN_ANCHOR_COUNT:+ continueif line.angle != 0 or line.formula_candidate_only or line.restored_inline_cluster or line.compact_formula_cluster:continuebaseline_entries = sorted(anchors, key=lambda entry: entry[4][1])@@ -495,7 +554,7 @@ def _document_requires_full_geometry(clusters[-1].append(entry)supported = [cluster for cluster in clusters if len(cluster) >= 3 and len(cluster) / len(anchors) >= 0.20]if len(supported) >= 2:- return True+ return _DocumentGeometryRisk(layout=True)dominant = max(clusters, key=len)if len(dominant) / len(anchors) < Y_DOMINANT_ROW_SHARE:continue@@ -509,6 +568,7 @@ def _document_requires_full_geometry(if ratio >= 3.0:y_extreme_runs[Counter(entry[5] for entry in dominant).most_common(1)[0][0]] += 1+ layout_risk = Falsefor run_key, ratios in x_ratios.items():pair_count = len(ratios)if pair_count < X_RELIABLE_PAIR_MIN:@@ -518,10 +578,26 @@ def _document_requires_full_geometry(and sum(value > X_STRONG_RATIO_THRESHOLD for value in ratios) / pair_count >= X_STRONG_RATIO_SHAREand x_overlaps[run_key] / pair_count >= X_STRONG_NEXT_TIGHT_OVERLAP_SHARE):- return True- return bool(y_ratios) and (- _quantile(y_ratios, 0.95) >= Y_DOCUMENT_RISK_P95_RATIO- or any(count >= Y_MIN_REPEATED_LINES for count in y_extreme_runs.values())+ layout_risk = True+ break+ layout_risk = (+ layout_risk+ or bool(y_ratios)+ and (+ _quantile(y_ratios, 0.95) >= Y_DOCUMENT_RISK_P95_RATIO+ or any(count >= Y_MIN_REPEATED_LINES for count in y_extreme_runs.values())+ )+ )+ style_risk = any(+ len(inflated_lines) >= STYLE_INFLATION_MIN_LINE_COUNT+ and len(inflated_lines) / style_line_counts[run_key] >= STYLE_INFLATION_MIN_LINE_SHARE+ and len({page_index for page_index, _source_index in inflated_lines}) >= STYLE_INFLATION_MIN_PAGE_COUNT+ for run_key, inflated_lines in style_inflated_lines.items()+ if style_line_counts[run_key] >= STYLE_INFLATION_MIN_LINE_COUNT+ )+ return _DocumentGeometryRisk(+ layout=layout_risk,+ style=style_risk,)@@ -666,46 +742,21 @@ def _mark_style_inflated_runs(samples_by_line: dict[LineKey, list[_CharSample]] = defaultdict(list)for sample in run.samples:if sample.is_anchor:- samples_by_line[- (sample.page_index, sample.line.source_index)- ].append(sample)+ samples_by_line[(sample.page_index, sample.line.source_index)].append(sample)if len(samples_by_line) < STYLE_INFLATION_MIN_LINE_COUNT:continueinflated_lines: list[LineKey] = []for line_key, line_samples in samples_by_line.items():- font_sizes = [- sample.font_size- for sample in line_samples- if sample.font_size > 0- ]- tight_heights = [- sample.local_tight_bbox[3]- - sample.local_tight_bbox[1]- for sample in line_samples- ]- style_scale = max(- statistics.median(font_sizes)- if font_sizes- else 0.0,- _quantile(tight_heights, 0.75),- )- if style_scale < STYLE_INFLATION_MIN_SCALE:- continue- source_height = line_samples[0].line.effective_height- tight_height = max(0.1, _quantile(tight_heights, 0.75))- if (- source_height- > STYLE_INFLATION_LOOSE_FONT_RATIO * style_scale- and source_height- > STYLE_INFLATION_LOOSE_TIGHT_RATIO * tight_height+ if _style_line_is_inflated(+ line_samples[0].line.effective_height,+ [sample.font_size for sample in line_samples if sample.font_size > 0],+ [sample.local_tight_bbox[3] - sample.local_tight_bbox[1] for sample in line_samples],):inflated_lines.append(line_key)if (len(inflated_lines) >= STYLE_INFLATION_MIN_LINE_COUNT- and len(inflated_lines) / len(samples_by_line)- >= STYLE_INFLATION_MIN_LINE_SHARE- and len({page_index for page_index, _source_index in inflated_lines})- >= STYLE_INFLATION_MIN_PAGE_COUNT+ and len(inflated_lines) / len(samples_by_line) >= STYLE_INFLATION_MIN_LINE_SHARE+ and len({page_index for page_index, _source_index in inflated_lines}) >= STYLE_INFLATION_MIN_PAGE_COUNT):run.style_y_bad = Trueoutput.add(run.key)@@ -1352,12 +1403,19 @@ def build_document_geometry_plan(plan = DocumentGeometryPlan()if not any(geometry.tight_bboxes and geometry.origins for geometry in geometries):return plan- if not _document_requires_full_geometry(lines_by_page, geometries, page_sizes):+ risk = _document_requires_full_geometry(+ lines_by_page,+ geometries,+ page_sizes,+ )+ if not risk.any:for geometry in geometries:geometry.loose_bboxes.clear()return plansamples, by_line = _collect_samples(lines_by_page, geometries, page_sizes)- _record_line_canonical_metrics(plan, by_line)+ if risk.layout:+ # 只有布局风险才记录公开输出候选;仅样式异常时只校准内部字号。+ _record_line_canonical_metrics(plan, by_line)runs = _build_run_stats(samples, by_line)style_inflated_runs = _mark_style_inflated_runs(runs)plan.style_inflated_runs = style_inflated_runs@@ -1366,17 +1424,17 @@ def build_document_geometry_plan()_apply_style_scale_repairs(plan,- style_inflated_runs- if plan.document_style_anomaly- else set(),+ style_inflated_runs if plan.document_style_anomaly else set(),by_line,)- if plan.document_style_anomaly:+ if plan.document_style_anomaly and risk.layout:_restore_stable_legacy_source_bboxes(by_line, page_sizes)runs = _build_run_stats(samples, by_line)for run in runs.values():run.style_y_bad = run.key in style_inflated_runsplan.run_diagnostics = _run_diagnostics(runs)+ if not risk.layout:+ return planx_bad_runs = {run.key for run in runs.values() if run.strong_x_bad or run.sibling_x_bad}if x_bad_runs:_repair_x_chars(plan, runs, by_line, page_sizes)diff --git a/mineru/model/flash/pdf/pipeline.py b/mineru/model/flash/pdf/pipeline.pyindex 38844399..42e6dc83 100644--- a/mineru/model/flash/pdf/pipeline.py+++ b/mineru/model/flash/pdf/pipeline.py@@ -48,6 +48,7 @@ from .native_text import (_get_pdf_drawing_lines,_median_native_glyph_width,_sanitize_pdf_control_text,+ _resplit_native_visual_runs,)from .char_geometry import (DocumentGeometryPlan,@@ -520,17 +521,40 @@ def _prepare_page_source(plan=geometry_plan,allow_y_trim=True,)+ next_source_index = (+ max(+ (line.source_index for line in source.lines),+ default=-1,+ )+ + 1+ )+ if geometry_plan is not None:+ repaired_char_bboxes = {+ char_idx: repair.layout_bbox+ for (repair_page_index, char_idx), repair in geometry_plan.char_repairs.items()+ if repair_page_index == page_index+ }+ unclaimed_lines = _resplit_native_visual_runs(+ unclaimed_lines,+ source.page_size,+ repaired_char_bboxes,+ source_index_start=next_source_index,+ )+ next_source_index = max(+ next_source_index,+ max(+ (line.source_index for line in unclaimed_lines),+ default=-1,+ )+ + 1,+ )remaining_lines = _split_parallel_graphic_rule_rows(unclaimed_lines,source.drawing_lines,[block["bbox"] for block in (form_image_blocks + graphic_blocks + raster_image_blocks)],table_bboxes,source.page_size,- source_index_start=max(- (line.source_index for line in source.lines),- default=-1,- )- + 1,+ source_index_start=next_source_index,)canonical_formula_source_lines = ([diff --git a/mineru/model/flash/pdf/text_blocks.py b/mineru/model/flash/pdf/text_blocks.pyindex a639ed6a..5e4f87bf 100644--- a/mineru/model/flash/pdf/text_blocks.py+++ b/mineru/model/flash/pdf/text_blocks.py@@ -1361,6 +1361,7 @@ def _build_text_blocks()return _merge_paragraph_formula_context_blocks(blocks,+ page_size,)@@ -1653,8 +1654,30 @@ def _merge_inline_math_fragment_text_blocks(return _merge_inline_math_paragraph_continuations(output, page_size)+def _component_local_union_bbox(+ block: dict[str, Any],+) -> BBox | None:+ """合并正文组件持有的正向行框,非法或缺失元数据时返回空。"""++ rows = block.get("_local_line_bboxes")+ if not isinstance(rows, list):+ return None+ bboxes: list[BBox] = []+ for row in rows:+ if not isinstance(row, (list, tuple)) or len(row) != 4:+ continue+ try:+ bbox = tuple(float(value) for value in row)+ except (TypeError, ValueError):+ continue+ if bbox[2] > bbox[0] and bbox[3] > bbox[1]:+ bboxes.append(bbox) # type: ignore[arg-type]+ return _bbox_union_many(bboxes) if bboxes else None++def _merge_paragraph_formula_context_blocks(blocks: list[dict[str, Any]],+ page_size: tuple[float, float],) -> list[dict[str, Any]]:"""把误似行间公式的复杂行内分式与同栏前后正文恢复成一个块。"""@@ -1697,8 +1720,10 @@ def _merge_paragraph_formula_context_blocks(pair_height,):continue- candidate_bbox = candidate["bbox"]- member_bbox = member["bbox"]+ candidate_bbox = _component_local_union_bbox(candidate)+ member_bbox = _component_local_union_bbox(member)+ if candidate_bbox is None or member_bbox is None:+ continuevertical_gap = max(candidate_bbox[1] - member_bbox[3],member_bbox[1] - candidate_bbox[3],@@ -1741,12 +1766,17 @@ def _merge_paragraph_formula_context_blocks(body_rows = [bbox for bbox in local_rows if bbox[2] - bbox[0] >= 0.75 * maximum_width]if len(body_rows) >= 2:# 复杂分式可能比正文左缘多探出少量 glyph;公开框按重复满行边界稳定收口。- merged_bbox = merged["bbox"]- merged["bbox"] = (+ local_merged_bbox = _bbox_union_many(local_rows)+ local_output_bbox = (min(bbox[0] for bbox in body_rows),- merged_bbox[1],+ local_merged_bbox[1],max(bbox[2] for bbox in body_rows),- merged_bbox[3],+ local_merged_bbox[3],+ )+ merged["bbox"] = _rotate_bbox_from_upright(+ local_output_bbox,+ page_size,+ int(merged.get("angle", 0) or 0) % 360,)replacements[replacement_index] = mergedconsumed.update(ordered_group)diff --git a/scripts/review_flash_layout_geometry.py b/scripts/review_flash_layout_geometry.pyindex 1c475f1f..cef56433 100644--- a/scripts/review_flash_layout_geometry.py+++ b/scripts/review_flash_layout_geometry.py@@ -1,4 +1,4 @@-"""生成 Flash 双几何全量回测、扰动不变性和逐页人工审阅产物。"""+"""生成 Flash 双几何全量回测、金标比对和逐页人工审阅产物。"""from __future__ import annotations@@ -6,10 +6,8 @@ import argparseimport hashlibimport jsonimport os-import resourceimport sysimport time-from copy import deepcopyfrom pathlib import Pathfrom typing import Any@@ -20,21 +18,13 @@ if str(SOURCE_ROOT) not in sys.path:import pypdfium2 as pdfium # noqa: E402from PIL import Image, ImageDraw, ImageFont # noqa: E402-from pdftext.schema import Bbox # noqa: E402-from mineru.model.flash.pdf.document import PDFDocument, PDFPageTextGeometry # noqa: E402+from mineru.model.flash.pdf.document import PDFDocument # noqa: E402from mineru.model.flash.pdf.pipeline import _analyze_native_document # noqa: E402DEFAULT_OUTPUT = SOURCE_ROOT / "output" / "pdf" / "flash_layout_geometry_review"TRACKED_GOLD_MANIFEST = SOURCE_ROOT / "tests" / "fixtures" / "flash_layout_geometry_manifest.json"-PERTURBATION_NAMES = (- "x_advance",- "y_symmetric",- "y_asymmetric",- "latin_only",- "punctuation",-)_PDF_FIXTURE_XOR_KEY = b"MinerU flash layout fixture"_IGNORED_FINGERPRINT_KEYS = {"bbox",@@ -95,91 +85,6 @@ def _corpus_paths(manifest: dict[str, Any], source_root: Path) -> list[Path]:return paths-def _stable_factor(font_name: str) -> float:- """由字体名确定性生成 loose bbox 扰动倍率。"""-- digest = hashlib.sha256(font_name.encode("utf-8", errors="replace")).digest()[0]- return (1.75, 2.5, 4.0, 6.0)[digest % 4]---def _perturb_bbox(- char: dict[str, Any],- origin: tuple[float, float] | None,- variant: str,-) -> None:- """按指定变体改变 loose bbox,保留 tight 与 origin。"""-- raw_bbox = char.get("bbox")- if raw_bbox is None or origin is None:- return- x0, y0, x1, y1 = [float(value) for value in raw_bbox]- text = str(char.get("char") or "")- font_name = str((char.get("font") or {}).get("name") or "")- if variant == "latin_only" and not any(value.isascii() and value.isalnum() for value in text):- return- if variant == "punctuation" and not any(not value.isalnum() and not value.isspace() for value in text):- return-- baseline = float(origin[1])- ascent = max(0.1, baseline - y0)- descent = max(0.1, y1 - baseline)- factor = _stable_factor(font_name)- if variant == "x_advance":- new_x1 = x0 + max(0.1, x1 - x0) * max(1.75, factor)- char["bbox"] = Bbox([x0, y0, new_x1, y1])- return- if variant == "y_asymmetric":- new_y0 = baseline - ascent * factor- new_y1 = baseline + descent * (0.5 if factor > 1 else 3.0)- elif variant == "punctuation":- new_y0 = baseline + 1.5 * max(ascent, descent)- new_y1 = new_y0 + max(0.5, 0.25 * (ascent + descent))- else:- new_y0 = baseline - ascent * factor- new_y1 = baseline + descent * factor- char["bbox"] = Bbox([x0, min(new_y0, new_y1), x1, max(new_y0, new_y1)])---class _PerturbedPDFDocument:- """代理 PDFDocument,并对读取出的 loose 字符框应用确定性扰动。"""-- def __init__(self, document: PDFDocument, variant: str) -> None:- """保存真实文档和当前 loose 扰动名称。"""-- self._document = document- self._variant = variant-- def __getattr__(self, name: str) -> Any:- """把未覆盖的方法和属性转发给真实 PDFDocument。"""-- return getattr(self._document, name)-- def get_page_chars_with_geometry(self, page_idx: int) -> PDFPageTextGeometry:- """返回 tight/origin 不变、loose bbox 已扰动的页面字符几何。"""-- geometry = self._document.get_page_chars_with_geometry(page_idx)- chars = deepcopy(geometry.chars)- loose_bboxes = dict(geometry.loose_bboxes)- for char in chars:- char_idx = char.get("char_idx")- origin = geometry.origins.get(char_idx) if isinstance(char_idx, int) else None- if isinstance(char_idx, int):- raw_bbox = loose_bboxes.get(char_idx) or char.get("bbox")- probe = {- "bbox": Bbox([float(value) for value in raw_bbox]),- "char": char.get("char"),- "font": char.get("font"),- }- _perturb_bbox(probe, origin, self._variant)- loose_bboxes[char_idx] = tuple(float(value) for value in probe["bbox"])- return PDFPageTextGeometry(- chars=chars,- tight_bboxes=geometry.tight_bboxes,- origins=geometry.origins,- loose_bboxes=loose_bboxes,- )--def _canonical_value(value: Any) -> Any:"""移除允许变化的几何与大载荷,保留语义标签、层级和可见内容。"""@@ -363,44 +268,23 @@ def _build_contact_sheets(images: list[Path], output_dir: Path) -> list[Path]:def _run_document(path: Path,*,- perturb: bool,render: bool,output_dir: Path,) -> dict[str, Any]:- """解析一份语料并返回正常、扰动、overlay 和金标页面信息。"""+ """解析一份语料并返回耗时、overlay 和金标页面信息。"""stored_bytes = path.read_bytes()pdf_bytes = read_pdf_fixture(path)pdf_sha = _sha256_bytes(stored_bytes)geometry_diagnostics: list[dict[str, Any]] = []started = time.perf_counter()- rss_before = resource.getrusage(resource.RUSAGE_SELF).ru_maxrsswith PDFDocument(pdf_bytes) as document:mode = document.classify()pages = _analyze_native_document(document, geometry_diagnostics=geometry_diagnostics)elapsed = time.perf_counter() - started- rss_after = resource.getrusage(resource.RUSAGE_SELF).ru_maxrssgeometry = geometry_diagnostics[0] if geometry_diagnostics else {}fingerprints = [_page_fingerprint(page) for page in pages]bbox_fingerprints = [_page_bbox_fingerprint(page) for page in pages]- perturbation_diffs: dict[str, list[int]] = {}- perturbation_bbox_diffs: dict[str, list[int]] = {}- if perturb and mode == "txt":- for variant in PERTURBATION_NAMES:- with PDFDocument(pdf_bytes) as document:- variant_pages = _analyze_native_document(_PerturbedPDFDocument(document, variant))- variant_fingerprints = [_page_fingerprint(page) for page in variant_pages]- variant_bbox_fingerprints = [_page_bbox_fingerprint(page) for page in variant_pages]- perturbation_diffs[variant] = [- index- for index, (normal, changed) in enumerate(zip(fingerprints, variant_fingerprints, strict=True))- if normal != changed- ]- perturbation_bbox_diffs[variant] = [- index- for index, (normal, changed) in enumerate(zip(bbox_fingerprints, variant_bbox_fingerprints, strict=True))- if normal != changed- ]output_dir.mkdir(parents=True, exist_ok=True)(output_dir / "geometry.json").write_text(@@ -427,10 +311,7 @@ def _run_document("parse_mode": mode,"page_fingerprints": fingerprints,"bbox_fingerprints": bbox_fingerprints,- "perturbation_diffs": perturbation_diffs,- "perturbation_bbox_diffs": perturbation_bbox_diffs,"elapsed_seconds": elapsed,- "peak_rss_delta": max(0, rss_after - rss_before),"geometry_summary": {"repaired_chars": len(geometry.get("char_repairs", [])),"repaired_lines": sum(line.get("state") != "healthy" for line in geometry.get("line_repairs", [])),@@ -459,13 +340,12 @@ def _run_document(def _parse_args() -> argparse.Namespace:- """解析全量回测输出、扰动和渲染开关。"""+ """解析全量回测输出、筛选和渲染开关。"""parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--source-root", type=Path, default=SOURCE_ROOT)parser.add_argument("--manifest", type=Path, default=TRACKED_GOLD_MANIFEST)parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)- parser.add_argument("--perturb-loose", action="store_true")parser.add_argument("--no-render", action="store_true")parser.add_argument("--skip-performance-gate", action="store_true")parser.add_argument("--include", action="append", default=[], help="仅运行指定 PDF 文件名,可重复传入")@@ -503,7 +383,6 @@ def main() -> int:print(f"[{index}/{len(corpus_paths)}] {path.name}", flush=True)document = _run_document(path,- perturb=args.perturb_loose,render=not args.no_render,output_dir=output_dir / path.stem,)@@ -512,26 +391,6 @@ def main() -> int:page["approved"] = Truedocuments.append(document)- perturbation_failures = [- {- "file": document["file"],- "variant": variant,- "pages": pages,- }- for document in documents- for variant, pages in document["perturbation_diffs"].items()- if pages- ]- perturbation_bbox_failures = [- {- "file": document["file"],- "variant": variant,- "pages": pages,- }- for document in documents- for variant, pages in document["perturbation_bbox_diffs"].items()- if pages- ]gold_mismatches: list[dict[str, Any]] = []tracked_by_file = {Path(str(document["path"])).name: document for document in tracked_gold.get("documents", [])}for document in documents:@@ -571,26 +430,19 @@ def main() -> int:for document in documents:expected = tracked_by_file.get(document["file"], {})max_elapsed = expected.get("max_elapsed_seconds")- max_rss = expected.get("max_peak_rss_delta")if isinstance(max_elapsed, (int, float)) and document["elapsed_seconds"] > float(max_elapsed):performance_failures.append({"file": document["file"], "metric": "elapsed_seconds"})- if isinstance(max_rss, (int, float)) and document["peak_rss_delta"] > float(max_rss):- performance_failures.append({"file": document["file"], "metric": "peak_rss_delta"})manifest = {"source_root": str(source_root),"source_count": len(documents),"page_count": sum(document["pages"] for document in documents),"txt_page_count": sum(document["pages"] for document in documents if document["parse_mode"] == "txt"),- "perturbation_enabled": args.perturb_loose,- "perturbations": list(PERTURBATION_NAMES),- "perturbation_failures": perturbation_failures,- "perturbation_bbox_failures": perturbation_bbox_failures,"performance_failures": performance_failures,"gold_mismatches": gold_mismatches,"documents": [{key: value for key, value in document.items() if key != "gold_pages"} for document in documents],}gold = {- "contract": "Flash semantic labels and grouping ignore loose bbox coordinates",+ "contract": "Flash semantic labels, grouping, and bboxes match the approved corpus","baseline_git_sha": tracked_gold.get("baseline_git_sha"),"source_count": len(documents),"page_count": manifest["page_count"],@@ -618,21 +470,18 @@ def main() -> int:f"- Documents: {manifest['source_count']}",f"- Pages: {manifest['page_count']}",f"- TXT pages: {manifest['txt_page_count']}",- f"- Perturbation enabled: {manifest['perturbation_enabled']}",- f"- Perturbation failures: {len(perturbation_failures)}",- f"- Perturbation bbox failures: {len(perturbation_bbox_failures)}",f"- Performance failures: {len(performance_failures)}",f"- Gold mismatches: {len(gold_mismatches)}",f"- All pages approved: {gold['all_approved']}","",]for document in documents:- changed = sum(bool(pages) for pages in document["perturbation_diffs"].values())review_lines.append(- f"- {document['file']}: {document['pages']} pages, {document['parse_mode']}, failed variants={changed}"+ f"- {document['file']}: {document['pages']} pages, {document['parse_mode']}, "+ f"elapsed={document['elapsed_seconds']:.3f}s")(output_dir / "review.md").write_text("\n".join(review_lines) + "\n", encoding="utf-8")- return 1 if perturbation_failures or perturbation_bbox_failures or gold_mismatches or performance_failures else 0+ return 1 if gold_mismatches or performance_failures else 0if __name__ == "__main__":diff --git a/tests/fixtures/flash_layout_geometry_manifest.json b/tests/fixtures/flash_layout_geometry_manifest.jsonindex b0597ffe..494f2018 100644--- a/tests/fixtures/flash_layout_geometry_manifest.json+++ b/tests/fixtures/flash_layout_geometry_manifest.json@@ -16209,8 +16209,6 @@"p95_change_ratio": 0.0261,"baseline_total_seconds": 17.466309,"current_total_seconds": 17.340156,- "total_change_ratio": -0.0072,- "baseline_demo4_peak_rss_bytes": 191119360,- "current_demo4_peak_rss_bytes": 190971904+ "total_change_ratio": -0.0072}}diff --git a/tests/unittest/test_docx_complex_fields.py b/tests/unittest/test_docx_complex_fields.pyindex 86721c68..8f788621 100644--- a/tests/unittest/test_docx_complex_fields.py+++ b/tests/unittest/test_docx_complex_fields.py@@ -57,6 +57,7 @@ def _append_toc_complex_field(page_number: str,anchor: str,include_outer_toc: bool,+ split_hyperlink_instruction: bool = False,) -> None:"""构造 WPS 常见的 TOC、HYPERLINK 与 PAGEREF 嵌套复杂域。"""if include_outer_toc:@@ -65,7 +66,11 @@ def _append_toc_complex_field(_append_field_char(paragraph, "separate")_append_field_char(paragraph, "begin")- _append_instruction(paragraph, f' HYPERLINK \\l "{anchor}" ')+ if split_hyperlink_instruction:+ _append_instruction(paragraph, " HYPER")+ _append_instruction(paragraph, f'LINK \\l "{anchor}" ')+ else:+ _append_instruction(paragraph, f' HYPERLINK \\l "{anchor}" ')_append_field_char(paragraph, "separate")_append_result_text(paragraph, title)_append_result_tab(paragraph)@@ -104,6 +109,7 @@ def _build_complex_toc_docx() -> bytes:page_number="1",anchor="_TocTarget",include_outer_toc=True,+ split_hyperlink_instruction=True,)second = document.add_paragraph(style=toc_style)_append_toc_complex_field(@@ -123,7 +129,7 @@ def _build_complex_toc_docx() -> bytes:def test_nested_complex_toc_fields_preserve_titles_and_strict_index_targets() -> None:- """验证嵌套复杂域不会只剩页码,并按真实正文目标收敛目录 anchor。"""+ """验证拆分且嵌套的复杂域不会只剩页码,并按真实正文目标收敛目录 anchor。"""file_bytes = _build_complex_toc_docx()model_pages = DocxModel().predict(BytesIO(file_bytes))raw_index = next(block for page in model_pages for block in page if block["type"] == "index")diff --git a/tests/unittest/test_flash_pdf_char_geometry.py b/tests/unittest/test_flash_pdf_char_geometry.pyindex 357afd49..afa51df0 100644--- a/tests/unittest/test_flash_pdf_char_geometry.py+++ b/tests/unittest/test_flash_pdf_char_geometry.py@@ -220,6 +220,116 @@ def test_strong_x_run_repairs_advance_and_contains_tight_bbox() -> None:assert plan.line_repairs[(0, 0)].state == "repair_x"+def test_short_rows_accumulate_enough_pairs_for_strong_x_repair() -> None:+ """验证大量三字符短行仍可累计文档级 X 异常证据。"""++ lines = []+ geometries = []+ for line_index in range(15):+ line, geometry = _line_fixture(+ source_index=line_index,+ baseline=10.0 + 5.0 * line_index,+ count=3,+ loose_width=12.0,+ start_char_idx=10 * line_index,+ )+ lines.append(line)+ geometries.append(geometry)++ plan = build_document_geometry_plan(+ [lines],+ [_merge_geometries(*geometries)],+ [(400.0, 100.0)],+ )++ assert any(run["reliable_pair_count"] == 30 and run["strong_x_bad"] for run in plan.run_diagnostics)+ assert plan.char_repairs+ assert all(plan.line_repairs[(0, line_index)].state == "repair_x" for line_index in range(15))+++def test_style_only_prefilter_calibrates_scale_without_rewriting_output_geometry() -> None:+ """验证温和跨页高度异常只校准字号,不顺带启用公开 bbox 重写。"""++ lines_by_page = []+ geometries = []+ original_bboxes = []+ for page_index in range(2):+ page_lines = []+ page_geometries = []+ for line_index in range(3):+ baseline = 20.0 + 20.0 * line_index+ line, geometry = _line_fixture(+ source_index=line_index,+ baseline=baseline,+ count=6,+ font_size=7.0,+ loose_top=baseline - 11.3,+ loose_bottom=baseline + 2.0,+ start_char_idx=page_index * 100 + line_index * 10,+ )+ page_lines.append(line)+ page_geometries.append(geometry)+ original_bboxes.append(line.bbox)+ lines_by_page.append(page_lines)+ geometries.append(_merge_geometries(*page_geometries))++ plan = build_document_geometry_plan(+ lines_by_page,+ geometries,+ [(200.0, 100.0)] * 2,+ )+ for page_index, lines in enumerate(lines_by_page):+ apply_line_geometry_repairs(+ lines,+ page_index=page_index,+ plan=plan,+ allow_y_trim=True,+ )++ assert plan.document_style_anomaly+ assert plan.line_style_scales+ assert plan.line_ink_bboxes == {}+ assert plan.line_baselines == {}+ assert plan.line_repairs == {}+ assert [line.bbox for lines in lines_by_page for line in lines] == original_bboxes+ assert all(line.em_height == 7.0 for lines in lines_by_page for line in lines)+++def test_style_prefilter_keeps_subthreshold_document_on_identity_path() -> None:+ """验证未超过 style inflation 阈值的跨页行保持完全 identity。"""++ lines_by_page = []+ geometries = []+ for page_index in range(2):+ page_lines = []+ page_geometries = []+ for line_index in range(3):+ baseline = 20.0 + 20.0 * line_index+ line, geometry = _line_fixture(+ source_index=line_index,+ baseline=baseline,+ count=6,+ font_size=7.0,+ loose_top=baseline - 10.5,+ loose_bottom=baseline + 2.0,+ start_char_idx=page_index * 100 + line_index * 10,+ )+ page_lines.append(line)+ page_geometries.append(geometry)+ lines_by_page.append(page_lines)+ geometries.append(_merge_geometries(*page_geometries))++ plan = build_document_geometry_plan(+ lines_by_page,+ geometries,+ [(200.0, 100.0)] * 2,+ )++ assert not plan.document_style_anomaly+ assert plan.line_style_scales == {}+ assert plan.run_diagnostics == []++def test_canonical_line_metrics_propagate_without_y_bbox_rewrite() -> None:"""验证只发生 X 修复的行仍获得 tight 字形并集和 dominant origin 基线。"""diff --git a/tests/unittest/test_flash_pdf_pipeline.py b/tests/unittest/test_flash_pdf_pipeline.pyindex 003a829f..0094dff0 100644--- a/tests/unittest/test_flash_pdf_pipeline.py+++ b/tests/unittest/test_flash_pdf_pipeline.py@@ -8,6 +8,7 @@ import pytestfrom mineru.model.flash import PdfModelfrom mineru.model.flash.pdf import (auxiliary_text,+ char_geometry,formulas,geometry,graphics,@@ -133,6 +134,94 @@ def test_prepare_page_uses_only_table_body_bbox_and_keeps_annotations_fixed(]+def test_prepare_page_resplits_repaired_cross_column_row_before_text_classification(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证生产页面准备会按修复字符框重切跨栏粗行并分配唯一来源序号。"""++ positions = (0.0, 6.0, 12.0, 18.0, 62.0, 68.0, 74.0, 80.0)+ chars = [+ {+ "char": character,+ "bbox": (position, 10.0, position + 20.0, 20.0),+ "font": {+ "name": "ABCDEF+Body",+ "flags": 0,+ "weight": 400,+ "size": 10.0,+ },+ "char_idx": index,+ }+ for index, (character, position) in enumerate(+ zip("ABCDEFGH", positions, strict=True),+ )+ ]+ line = models._LineItem(+ text="ABCDEFGH",+ bbox=(0.0, 10.0, 100.0, 20.0),+ angle=0,+ source_index=5,+ chars=chars, # type: ignore[arg-type]+ visual_row_id=3,+ effective_height=10.0,+ em_height=10.0,+ )+ plan = char_geometry.DocumentGeometryPlan(+ char_repairs={+ (0, index): char_geometry.CharLayoutGeometry(+ source_bbox=tuple(float(value) for value in char["bbox"]), # type: ignore[arg-type]+ tight_bbox=(position, 10.0, position + 5.0, 20.0),+ origin=(position, 20.0),+ layout_bbox=(position, 10.0, position + 5.0, 20.0),+ ink_bbox=(position, 10.0, position + 5.0, 20.0),+ baseline=20.0,+ advance=6.0,+ em_height=10.0,+ x_state="abnormal",+ y_state="healthy",+ confidence=1.0,+ )+ for index, (char, position) in enumerate(+ zip(chars, positions, strict=True),+ )+ },+ )+ source = models._PageSource(+ page_size=(100.0, 100.0),+ lines=[line],+ chars=chars, # type: ignore[arg-type]+ drawing_lines=[],+ )+ observed_next_indices: list[int] = []++ def record_graphic_split_start(+ lines: list[models._LineItem],+ *_args: object,+ source_index_start: int,+ ) -> list[models._LineItem]:+ """记录跨栏重切后传给后续 graphic split 的下一来源序号。"""++ observed_next_indices.append(source_index_start)+ return lines++ monkeypatch.setattr(+ pipeline,+ "_split_parallel_graphic_rule_rows",+ record_graphic_split_start,+ )++ prepared = pipeline._prepare_page_source(+ source,+ geometry_plan=plan,+ page_index=0,+ )++ assert [member.text for member in prepared.remaining_lines] == ["ABCD", "EFGH"]+ assert [member.source_index for member in prepared.remaining_lines] == [5, 6]+ assert all(member.split_from_row for member in prepared.remaining_lines)+ assert observed_next_indices == [7]++def test_table_detection_excludes_confirmed_masthead_separator() -> None:"""验证页首通栏分隔线不与下方真表格边界组成巨型候选。"""diff --git a/tests/unittest/test_flash_pdf_text_blocks.py b/tests/unittest/test_flash_pdf_text_blocks.pyindex a02e7bd8..a2bb04c9 100644--- a/tests/unittest/test_flash_pdf_text_blocks.py+++ b/tests/unittest/test_flash_pdf_text_blocks.py@@ -5,6 +5,7 @@ from dataclasses import replaceimport pytestfrom mineru.model.flash.pdf import (+ geometry,line_layout,line_merging,models,@@ -174,6 +175,7 @@ def test_paragraph_formula_context_merges_dense_same_lane_text() -> None:merged = text_blocks._merge_paragraph_formula_context_blocks(blocks,+ (220.0, 100.0),)assert [item["content"] for item in merged] == [@@ -182,6 +184,84 @@ def test_paragraph_formula_context_merges_dense_same_lane_text() -> None:][email protected]("angle", [90, 270])+def test_rotated_paragraph_formula_context_uses_upright_gap(+ angle: int,+) -> None:+ """验证旋转公式上下文只合并正向坐标中真正相邻的同栏正文。"""++ page_size = (200.0, 200.0)++ def block(+ content: str,+ local_bbox: tuple[float, float, float, float],+ *,+ formula_context: bool = False,+ ) -> dict[str, object]:+ """构造页面框与正向行框分离的旋转文本块。"""++ return {+ "type": "text",+ "bbox": geometry._rotate_bbox_from_upright(+ local_bbox,+ page_size,+ angle,+ ),+ "angle": angle,+ "content": content,+ "_local_line_bboxes": [local_bbox],+ "_line_heights": [10.0],+ "_font_signatures": {("Body", 0)},+ "_lane_interval": (0.0, 80.0),+ "_lane_is_span": False,+ "_hard_break_before": False,+ "_paragraph_formula_context": formula_context,+ }++ adjacent = text_blocks._merge_paragraph_formula_context_blocks(+ [+ block("formula", (0.0, 0.0, 80.0, 10.0), formula_context=True),+ block("adjacent body", (0.0, 11.0, 80.0, 21.0)),+ ],+ page_size,+ )+ distant = text_blocks._merge_paragraph_formula_context_blocks(+ [+ block("formula", (0.0, 0.0, 80.0, 10.0), formula_context=True),+ block("distant body", (0.0, 100.0, 80.0, 110.0)),+ ],+ page_size,+ )+ missing_geometry_seed = block(+ "formula",+ (0.0, 0.0, 80.0, 10.0),+ formula_context=True,+ )+ missing_geometry_seed.pop("_local_line_bboxes")+ missing_geometry = text_blocks._merge_paragraph_formula_context_blocks(+ [+ missing_geometry_seed,+ block("adjacent body", (0.0, 11.0, 80.0, 21.0)),+ ],+ page_size,+ )++ assert [item["content"] for item in adjacent] == ["formula adjacent body"]+ assert adjacent[0]["bbox"] == geometry._rotate_bbox_from_upright(+ (0.0, 0.0, 80.0, 21.0),+ page_size,+ angle,+ )+ assert [item["content"] for item in distant] == [+ "formula",+ "distant body",+ ]+ assert [item["content"] for item in missing_geometry] == [+ "formula",+ "adjacent body",+ ]++def test_full_width_span_text_merges_without_terminal_punctuation_dependency() -> None:"""验证同栏满宽 span 正文可跨句号连续回并,并沿用英文断词恢复。"""