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 index block extraction for Flash native PDFs with support for page number detection and layout validation
myhlolif98e9fd19e4c
diff --git a/mineru/backend/flash/native_pdf/index_blocks.py b/mineru/backend/flash/native_pdf/index_blocks.pynew file mode 100644index 00000000..daa80d6d--- /dev/null+++ b/mineru/backend/flash/native_pdf/index_blocks.py@@ -0,0 +1,266 @@+# Copyright (c) Opendatalab. All rights reserved.++"""识别并构造 Flash 原生 PDF 的目录正文块。"""++from __future__ import annotations++from dataclasses import dataclass+import math+import re+import statistics+++from mineru.types import BBox, BlockType++from .models import _LineItem+from .geometry import (+ _bbox_center_x,+ _bbox_center_y,+ _bbox_overlap_in_smaller,+ _bbox_union_many,+ _rotate_bbox_to_upright,+)+from .line_layout import _line_effective_height+++_INDEX_PAGE_NUMBER_RE = re.compile(+ r"(?<![A-Za-z0-90-9])(?:[0-90-9]+|[ivxlcdmIVXLCDM]+)"+ r"[\s.。.、,,;;::))\]】]*$"+)+_INDEX_MIN_ROWS = 5+_INDEX_MIN_PAGE_NUMBER_RATIO = 0.7+++@dataclass(slots=True)+class _IndexRow:+ """保存目录候选视觉行的成员、局部几何和合并文本。"""++ members: list[_LineItem]+ local_member_bboxes: list[BBox]+ local_bbox: BBox+ content: str+ ends_in_page_number: bool+++def _extract_index_blocks(+ lines: list[_LineItem],+ page_size: tuple[float, float],+ container_bboxes: list[BBox],+) -> tuple[list[dict[str, object]], list[_LineItem]]:+ """用页码行尾和稳定版式识别目录区域,并返回独立 index 块。"""++ claimed_line_ids: set[int] = set()+ blocks: list[dict[str, object]] = []+ for angle in sorted({line.angle for line in lines if line.semantic_type is None}):+ rows = _build_index_rows(lines, page_size, angle)+ if len(rows) < _INDEX_MIN_ROWS:+ continue+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]+ local_containers = [_rotate_bbox_to_upright(bbox, page_size, angle) for bbox in container_bboxes]+ eligible_rows = [+ row+ for row in rows+ if not any(_bbox_overlap_in_smaller(row.local_bbox, container_bbox) >= 0.35 for container_bbox in local_containers)+ ]+ for band in _split_index_bands(eligible_rows):+ candidate = _trim_index_band_edges(band)+ if not _index_band_has_stable_layout(candidate, local_page_width):+ continue+ heading_row = _find_index_heading_row(+ eligible_rows,+ candidate,+ local_page_width,+ )+ if heading_row is not None:+ for line in heading_row.members:+ line.semantic_type = "paragraph_title"+ for row in candidate:+ for line in row.members:+ line.semantic_type = BlockType.INDEX+ claimed_line_ids.add(id(line))+ blocks.append(+ {+ "type": BlockType.INDEX,+ "bbox": _bbox_union_many([line.bbox for row in candidate for line in row.members]),+ "angle": angle,+ "content": "\n".join(row.content for row in candidate),+ }+ )++ remaining_lines = [line for line in lines if id(line) not in claimed_line_ids]+ return blocks, remaining_lines+++def _build_index_rows(+ lines: list[_LineItem],+ page_size: tuple[float, float],+ angle: int,+) -> list[_IndexRow]:+ """按 visual_row_id 复原当前方向的完整视觉行,保留左右分裂成员。"""++ row_groups: dict[tuple[str, int], list[_LineItem]] = {}+ for line in lines:+ if line.angle != angle or line.semantic_type is not None:+ continue+ key = ("visual", line.visual_row_id) if line.visual_row_id is not None else ("source", line.source_index)+ row_groups.setdefault(key, []).append(line)++ rows: list[_IndexRow] = []+ for members in row_groups.values():+ ordered = sorted(+ members,+ key=lambda line: (+ _rotate_bbox_to_upright(line.bbox, page_size, angle)[0],+ line.run_index,+ line.source_index,+ ),+ )+ local_member_bboxes = [_rotate_bbox_to_upright(line.bbox, page_size, angle) for line in ordered]+ local_bbox = _bbox_union_many(local_member_bboxes)+ content = " ".join(part for line in ordered if (part := line.text.strip()))+ if not content:+ continue+ rows.append(+ _IndexRow(+ members=ordered,+ local_member_bboxes=local_member_bboxes,+ local_bbox=local_bbox,+ content=content,+ ends_in_page_number=_index_row_ends_in_page_number(content),+ )+ )+ rows.sort(+ key=lambda row: (+ row.local_bbox[1],+ row.local_bbox[0],+ min(line.source_index for line in row.members),+ )+ )+ return rows+++def _index_row_ends_in_page_number(content: str) -> bool:+ """识别行尾的半角、全角阿拉伯页码或罗马页码。"""++ return _INDEX_PAGE_NUMBER_RE.search(content.rstrip()) is not None+++def _split_index_bands(rows: list[_IndexRow]) -> list[list[_IndexRow]]:+ """按显著纵向断层拆分候选带,同时容纳目录章节之间的加大行距。"""++ if not rows:+ return []+ median_height = statistics.median(max(_line_effective_height(line, row.local_bbox) for line in row.members) for row in rows)+ maximum_pitch = 3.25 * max(0.1, median_height)+ bands: list[list[_IndexRow]] = [[rows[0]]]+ for row in rows[1:]:+ previous = bands[-1][-1]+ if _bbox_center_y(row.local_bbox) - _bbox_center_y(previous.local_bbox) > maximum_pitch:+ bands.append([row])+ else:+ bands[-1].append(row)+ return bands+++def _trim_index_band_edges(rows: list[_IndexRow]) -> list[_IndexRow]:+ """移除候选带两端不带页码的标题或邻接正文,内部少量续行继续保留。"""++ start = 0+ end = len(rows)+ while start < end and not rows[start].ends_in_page_number:+ start += 1+ while end > start and not rows[end - 1].ends_in_page_number:+ end -= 1+ return rows[start:end]+++def _index_band_has_stable_layout(+ rows: list[_IndexRow],+ local_page_width: float,+) -> bool:+ """联合页码比例、右边界、行宽、缩进和行距确认目录候选。"""++ if len(rows) < _INDEX_MIN_ROWS or local_page_width <= 0:+ return False+ page_number_rows = [row for row in rows if row.ends_in_page_number]+ required_page_number_rows = max(+ 4,+ math.ceil(_INDEX_MIN_PAGE_NUMBER_RATIO * len(rows)),+ )+ if len(page_number_rows) < required_page_number_rows:+ return False++ row_heights = [max(0.1, row.local_bbox[3] - row.local_bbox[1]) for row in rows]+ median_height = statistics.median(row_heights)+ median_right = statistics.median(row.local_bbox[2] for row in page_number_rows)+ right_tolerance = max(1.5 * median_height, 0.02 * local_page_width)+ aligned_right_ratio = sum(abs(row.local_bbox[2] - median_right) <= right_tolerance for row in page_number_rows) / len(+ page_number_rows+ )+ if median_right < 0.75 * local_page_width or aligned_right_ratio < 0.7:+ return False++ wide_row_ratio = sum(row.local_bbox[2] - row.local_bbox[0] >= 0.55 * local_page_width for row in rows) / len(rows)+ right_sidecar_count = sum(_index_row_has_right_sidecar(row, local_page_width, median_height) for row in rows)+ if wide_row_ratio < 0.7 and right_sidecar_count < 2:+ return False++ left_body_ratio = sum(row.local_bbox[0] <= 0.3 * local_page_width for row in rows) / len(rows)+ if left_body_ratio < 0.7:+ return False++ pitches = [+ _bbox_center_y(current.local_bbox) - _bbox_center_y(previous.local_bbox) for previous, current in zip(rows, rows[1:])+ ]+ if not pitches or min(pitches) <= 0:+ return False+ median_pitch = statistics.median(pitches)+ regular_pitch_ratio = sum(0.55 * median_pitch <= pitch <= 1.75 * median_pitch for pitch in pitches) / len(pitches)+ return regular_pitch_ratio >= 0.7+++def _find_index_heading_row(+ all_rows: list[_IndexRow],+ candidate: list[_IndexRow],+ local_page_width: float,+) -> _IndexRow | None:+ """用候选带上方的居中、短行和垂直邻接关系保留目录标题。"""++ if not candidate:+ return None+ first_position = next(+ (index for index, row in enumerate(all_rows) if row is candidate[0]),+ None,+ )+ if first_position is None or first_position == 0:+ return None+ heading = all_rows[first_position - 1]+ if heading.ends_in_page_number:+ return None+ candidate_heights = [max(0.1, row.local_bbox[3] - row.local_bbox[1]) for row in candidate]+ median_height = statistics.median(candidate_heights)+ heading_width = heading.local_bbox[2] - heading.local_bbox[0]+ centered = abs(_bbox_center_x(heading.local_bbox) - 0.5 * local_page_width) <= 0.15 * local_page_width+ vertical_pitch = _bbox_center_y(candidate[0].local_bbox) - _bbox_center_y(heading.local_bbox)+ if (+ heading_width > 0.4 * local_page_width+ or not centered+ or not 1.25 * median_height <= vertical_pitch <= 5.0 * median_height+ ):+ return None+ return heading+++def _index_row_has_right_sidecar(+ row: _IndexRow,+ local_page_width: float,+ median_height: float,+) -> bool:+ """检查视觉行末尾是否存在靠近页面右侧的窄页码片段。"""++ if len(row.members) < 2:+ return False+ last_bbox = row.local_member_bboxes[-1]+ return last_bbox[0] >= 0.75 * local_page_width and last_bbox[2] - last_bbox[0] <= max(+ 0.12 * local_page_width, 4.0 * median_height+ )diff --git a/mineru/backend/flash/native_pdf/models.py b/mineru/backend/flash/native_pdf/models.pyindex 536d5910..b84fed7c 100644--- a/mineru/backend/flash/native_pdf/models.py+++ b/mineru/backend/flash/native_pdf/models.py@@ -162,3 +162,12 @@ class _LaneBodyProfile:body_weight: float | Noneregular_gap: floatstyle_support: dict[tuple[str, int], float]+++@dataclass(frozen=True, slots=True)+class _DocumentBodyProfile:+ """保存跨页正文行高、常规字重与反复出现的常规字体。"""++ body_height: float+ body_weight: float | None+ regular_fonts: frozenset[tuple[str, int]]diff --git a/mineru/backend/flash/native_pdf/pipeline.py b/mineru/backend/flash/native_pdf/pipeline.pyindex a10df44c..2e123bf6 100644--- a/mineru/backend/flash/native_pdf/pipeline.py+++ b/mineru/backend/flash/native_pdf/pipeline.py@@ -11,6 +11,7 @@ from mineru.backend.utils.xycut_pp_sorter import sort_entriesfrom mineru.utils.pdf_document import PDFDocument, PDFImageInfo, get_lines_from_charsfrom .models import (+ _DocumentBodyProfile,_LineItem,_PageSource,_PreparedPage,@@ -39,6 +40,7 @@ from .line_merging import (_merge_title_resolved_visual_rows,_restore_dense_split_visual_rows,)+from .index_blocks import _extract_index_blocksfrom .tables import (_detect_table_candidates,_materialize_table_blocks,@@ -61,7 +63,10 @@ from .auxiliary_text import (_classify_repeated_page_marginals,_classify_repeated_visual_headers,)-from .titles import _classify_page_titles+from .titles import (+ _classify_page_titles,+ _infer_document_body_profile,+)from .text_blocks import (_build_text_blocks,_merge_fragmented_header_blocks,@@ -77,6 +82,7 @@ _TEXT_SEMANTIC_TYPES = {"page_number","page_footnote","aside_text",+ "index",}@@ -182,8 +188,13 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]_classify_repeated_visual_headers(prepared_pages)_classify_repeated_page_marginals(prepared_pages)+ document_body_profile = _infer_document_body_profile(prepared_pages)return [- _finalize_prepared_page(prepared, page_index)+ _finalize_prepared_page(+ prepared,+ page_index,+ document_body_profile=document_body_profile,+ )for page_index, prepared in enumerate(prepared_pages)]@@ -292,6 +303,8 @@ def _compact_prepared_lines(def _finalize_prepared_page(prepared: _PreparedPage,page_index: int,+ *,+ document_body_profile: _DocumentBodyProfile | None = None,) -> list[dict[str, Any]]:"""按预分类语义、公式、标题、正文的优先级完成单页文本并排序。"""@@ -307,11 +320,18 @@ def _finalize_prepared_page(prepared.page_size,prepared.table_bboxes,)+ container_bboxes = [block["bbox"] for block in prepared.fixed_blocks]+ index_blocks, remaining_lines = _extract_index_blocks(+ remaining_lines,+ prepared.page_size,+ container_bboxes,+ )_classify_page_titles(remaining_lines,prepared.page_size,page_index=page_index,- container_bboxes=[block["bbox"] for block in prepared.fixed_blocks],+ container_bboxes=container_bboxes,+ document_body_profile=document_body_profile,)remaining_lines = _merge_title_resolved_visual_rows(remaining_lines,@@ -338,7 +358,9 @@ def _finalize_prepared_page(],)text_blocks = _merge_fragmented_header_blocks(text_blocks)- absolute_blocks = prepared.fixed_blocks + formula_blocks + text_blocks+ absolute_blocks = (+ prepared.fixed_blocks + formula_blocks + index_blocks + text_blocks+ )sorted_blocks = _sort_blocks_with_visual_row_groups(absolute_blocks, prepared.page_size)return [normalizeddiff --git a/mineru/backend/flash/native_pdf/titles.py b/mineru/backend/flash/native_pdf/titles.pyindex ea0c5083..a029bef1 100644--- a/mineru/backend/flash/native_pdf/titles.py+++ b/mineru/backend/flash/native_pdf/titles.py@@ -11,8 +11,10 @@ from typing import Literalfrom mineru.types import BBoxfrom .models import (+ _DocumentBodyProfile,_LaneBodyProfile,_LineItem,+ _PreparedPage,_TextLane,)from .geometry import (@@ -32,12 +34,18 @@ from .line_layout import ()+# PDF FontDescriptor 中 Italic 与 ForceBold 位用于排除非常规字体画像。+_PDF_FONT_ITALIC_FLAG = 1 << 6+_PDF_FONT_FORCE_BOLD_FLAG = 1 << 18++def _classify_page_titles(lines: list[_LineItem],page_size: tuple[float, float],*,page_index: int,container_bboxes: list[BBox],+ document_body_profile: _DocumentBodyProfile | None = None,) -> None:"""只用页面几何与字体排版标注首页文档标题和各页段落标题。"""@@ -80,9 +88,11 @@ def _classify_page_titles(lanes,local_page_height,local_page_width,+ document_body_profile=document_body_profile,)preserve_front_matter_boundaries = _document_title_uses_page_fallback(lanes,+ document_body_profile=document_body_profile,)for lane in lanes:@@ -96,7 +106,134 @@ def _classify_page_titles(preserve_front_matter_boundaries=preserve_front_matter_boundaries,physical_gaps=physical_gaps,grid_title_suppressions=grid_title_suppressions,+ document_body_profile=document_body_profile,+ )+++def _infer_document_body_profile(+ prepared_pages: list[_PreparedPage],+) -> _DocumentBodyProfile | None:+ """按跨页覆盖和累计行宽推断全文正文行高及常规字体集合。"""++ samples: list[+ tuple[+ float,+ int,+ float,+ tuple[str, int] | None,+ float | None,+ ]+ ] = []+ for page_index, prepared in enumerate(prepared_pages):+ for line in prepared.remaining_lines:+ if line.semantic_type is not None:+ continue+ local_bbox = _rotate_bbox_to_upright(+ line.bbox,+ prepared.page_size,+ line.angle,+ )+ local_page_width = (+ prepared.page_size[1]+ if line.angle in {90, 270}+ else prepared.page_size[0])+ height = _line_effective_height(line, local_bbox)+ normalized_width = max(0.0, local_bbox[2] - local_bbox[0]) / max(+ 0.1,+ local_page_width,+ )+ if height <= 0 or normalized_width <= 0:+ continue+ samples.append(+ (+ height,+ page_index,+ normalized_width,+ line.font_signature if line.font_coverage >= 0.75 else None,+ line.dominant_font_weight,+ )+ )+ if not samples:+ return None++ height_clusters: list[list[tuple[float, int, float]]] = []+ for height, page_index, normalized_width, _font, _weight in sorted(+ samples,+ key=lambda item: item[0],+ ):+ target = next(+ (+ cluster+ for cluster in height_clusters+ if abs(height - statistics.median(item[0] for item in cluster))+ <= 0.1 * statistics.median(item[0] for item in cluster)+ ),+ None,+ )+ if target is None:+ height_clusters.append([(height, page_index, normalized_width)])+ else:+ target.append((height, page_index, normalized_width))+ body_cluster = max(+ height_clusters,+ key=lambda cluster: (+ len({item[1] for item in cluster}),+ sum(item[2] for item in cluster),+ ),+ )+ body_height = statistics.median(item[0] for item in body_cluster)++ body_weights = [+ weight+ for height, _page_index, _width, _font, weight in samples+ if weight is not None and 0.9 <= height / body_height <= 1.1+ ]+ body_weight = statistics.median(body_weights) if body_weights else None++ font_pages: dict[tuple[str, int], set[int]] = {}+ font_widths: dict[tuple[str, int], float] = {}+ font_weights: dict[tuple[str, int], list[float]] = {}+ for _height, page_index, width, font, weight in samples:+ if font is None:+ continue+ font_pages.setdefault(font, set()).add(page_index)+ font_widths[font] = font_widths.get(font, 0.0) + width+ if weight is not None:+ font_weights.setdefault(font, []).append(weight)++ regular_fonts = frozenset(+ font+ for font, pages in font_pages.items()+ if len(pages) >= 3+ and font_widths.get(font, 0.0) >= 2.0+ and font_widths.get(font, 0.0) >= 0.75 * len(pages)+ and _document_font_is_regular(+ font,+ font_weights.get(font, []),+ body_weight,+ )+ )+ return _DocumentBodyProfile(+ body_height=max(0.1, body_height),+ body_weight=body_weight,+ regular_fonts=regular_fonts,+ )+++def _document_font_is_regular(+ font: tuple[str, int],+ weights: list[float],+ body_weight: float | None,+) -> bool:+ """用字体样式位和全文正文基准过滤斜体、粗体等强调字体。"""++ if font[1] & (_PDF_FONT_ITALIC_FLAG | _PDF_FONT_FORCE_BOLD_FLAG):+ return False+ if not weights or body_weight is None:+ return True+ median_weight = statistics.median(weights)+ return median_weight < max(body_weight + 100.0, 1.15 * body_weight)def _build_physical_title_gap_map(@@ -282,17 +419,25 @@ def _classify_document_title(lanes: list[_TextLane],local_page_height: float,local_page_width: float,+ *,+ document_body_profile: _DocumentBodyProfile | None = None,) -> float | None:"""从首页上部选取显著大字号锚点,并用同版式邻行扩展多行文档标题。"""candidates: list[tuple[float, _TextLane, int, tuple[_LineItem, BBox]]] = []lane_profiles = [(lane, _infer_lane_body_profile(lane)) for lane in lanes]column_body_heights = [profile.body_height for lane, profile in lane_profiles if not lane.is_span]- document_body_height = (- statistics.median(column_body_heights)- if column_body_heights- else min((profile.body_height for _lane, profile in lane_profiles), default=1.0)- )+ if document_body_profile is not None:+ document_body_height = document_body_profile.body_height+ else:+ document_body_height = (+ statistics.median(column_body_heights)+ if column_body_heights+ else min(+ (profile.body_height for _lane, profile in lane_profiles),+ default=1.0,+ )+ )for lane, profile in lane_profiles:lane_width = max(0.1, lane.right - lane.left)available = [item for item in lane.lines if item[0].semantic_type is None]@@ -390,7 +535,11 @@ def _document_title_fonts_compatible(return uncertain_dominant_font and weights_compatible-def _document_title_uses_page_fallback(lanes: list[_TextLane]) -> bool:+def _document_title_uses_page_fallback(+ lanes: list[_TextLane],+ *,+ document_body_profile: _DocumentBodyProfile | None = None,+) -> bool:"""判断首页标题是否依赖跨栏 1.30 倍全文正文行高兜底。"""title_heights = [@@ -406,7 +555,11 @@ def _document_title_uses_page_fallback(lanes: list[_TextLane]) -> bool:]if not title_heights or not column_body_heights:return False- document_body_height = statistics.median(column_body_heights)+ document_body_height = (+ document_body_profile.body_height+ if document_body_profile is not None+ else statistics.median(column_body_heights)+ )return any(1.3 <= title_height / max(0.1, document_body_height) < 1.4for title_height in title_heights@@ -423,6 +576,7 @@ def _classify_paragraph_titles_in_lane(preserve_front_matter_boundaries: bool,physical_gaps: dict[int, tuple[float | None, float | None]],grid_title_suppressions: set[int],+ document_body_profile: _DocumentBodyProfile | None,) -> None:"""以字号、样式、留白、对齐、栏宽和容器邻接判定段落标题。"""@@ -448,22 +602,46 @@ def _classify_paragraph_titles_in_lane()if inside_front_matter and not preserve_front_matter_boundaries:continue+ if (+ document_title_bottom is not None+ and document_title_bottom <= 0.6 * local_page_height+ and _bbox_center_y(bbox) >= 0.84 * local_page_height+ ):+ # 首页底部短行通常是版本、日期等封面元数据,不属于正文标题层级。+ continueif _line_near_visual_container(bbox, container_bboxes, profile.body_height):continueline_height = _line_effective_height(line, bbox)- height_ratio = line_height / profile.body_height+ recurrent_regular_font = _line_uses_document_regular_font(+ line,+ document_body_profile,+ )+ document_regular_body_candidate = (+ recurrent_regular_font+ and document_body_profile is not None+ and line_height >= 0.9 * document_body_profile.body_height+ )+ reference_body_height = profile.body_height+ if document_regular_body_candidate and document_body_profile is not None:+ reference_body_height = max(+ reference_body_height,+ document_body_profile.body_height,+ )+ height_ratio = line_height / reference_body_heightwidth_ratio = (bbox[2] - bbox[0]) / lane_widthcentered = abs(_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) <= 0.12 * lane_widthleft_aligned = abs(bbox[0] - lane.left) <= 0.65 * profile.body_heightstyle_differs = (- profile.body_font is not None+ not recurrent_regular_font+ and profile.body_font is not Noneand line.font_signature is not Noneand line.font_coverage >= 0.75and line.font_signature != profile.body_font)low_coverage_style_differs = (- profile.body_font is not None+ not recurrent_regular_font+ and profile.body_font is not Noneand line.font_signature is not Noneand 0.5 <= line.font_coverage < 0.75and line.font_signature != profile.body_font@@ -586,7 +764,12 @@ def _classify_paragraph_titles_in_lane(or style_differsor compact_local_transitionor weight_emphasized- or (centered and width_ratio <= 0.7 and gap_above >= 0.35 and gap_below >= 0.2)+ or (+ centered+ and width_ratio <= 0.7+ and gap_above >= 0.35+ and gap_below >= 0.2+ ))if (score >= 4.0@@ -620,6 +803,20 @@ def _classify_paragraph_titles_in_lane()+def _line_uses_document_regular_font(+ line: _LineItem,+ document_body_profile: _DocumentBodyProfile | None,+) -> bool:+ """判断当前行是否使用跨页反复出现且未加粗的常规字体。"""++ return (+ document_body_profile is not None+ and line.font_signature is not None+ and line.font_coverage >= 0.5+ and line.font_signature in document_body_profile.regular_fonts+ )++def _protect_front_matter_title_types(lane: _TextLane,profile: _LaneBodyProfile,diff --git a/tests/unittest/test_flash_pdf_document_profile.py b/tests/unittest/test_flash_pdf_document_profile.pynew file mode 100644index 00000000..f58a2299--- /dev/null+++ b/tests/unittest/test_flash_pdf_document_profile.py@@ -0,0 +1,320 @@+from __future__ import annotations++from mineru.backend.flash.native_pdf import titles++from _flash_pdf_test_utils import _prepared_text_page, _text_line+++def test_document_body_profile_prefers_cross_page_body_and_regular_fonts() -> None:+ """验证全文画像优先跨页正文行高,并排除反复出现的明显粗体字体。"""++ body_font = ("BodyRegular", 0)+ mono_font = ("MonoRegular", 0)+ italic_font = ("BodyItalic", 1 << 6)+ bold_font = ("HeadingBold", 1)+ pages = []+ for page_index in range(4):+ lines = [+ _text_line(+ "body",+ (0.0, 10.0, 80.0, 20.0),+ page_index * 10,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ )+ ]+ if page_index < 3:+ lines.extend(+ [+ _text_line(+ "mono",+ (0.0, 30.0, 80.0, 38.0),+ page_index * 10 + 1,+ effective_height=8.0,+ font_signature=mono_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ _text_line(+ "bold",+ (0.0, 50.0, 80.0, 60.0),+ page_index * 10 + 2,+ effective_height=10.0,+ font_signature=bold_font,+ font_coverage=1.0,+ dominant_font_weight=800.0,+ ),+ _text_line(+ "italic",+ (0.0, 70.0, 80.0, 78.0),+ page_index * 10 + 3,+ effective_height=8.0,+ font_signature=italic_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ ]+ )+ pages.append(_prepared_text_page(*lines))++ profile = titles._infer_document_body_profile(pages)++ assert profile is not None+ assert profile.body_height == 10.0+ assert profile.body_weight == 400.0+ assert profile.regular_fonts == frozenset({body_font, mono_font})+++def test_sparse_repeated_font_is_not_document_regular_style() -> None:+ """验证只在多页短标题中反复出现的字体不会被并入全文常规字体。"""++ body_font = ("BodyRegular", 0)+ sparse_font = ("SparseHeading", 1)+ pages = [+ _prepared_text_page(+ _text_line(+ "body",+ (0.0, 10.0, 100.0, 20.0),+ page_index * 2,+ font_signature=body_font,+ font_coverage=1.0,+ dominant_font_weight=0.0,+ ),+ _text_line(+ "short",+ (0.0, 40.0, 50.0, 50.0),+ page_index * 2 + 1,+ font_signature=sparse_font,+ font_coverage=1.0,+ dominant_font_weight=0.0,+ ),+ )+ for page_index in range(5)+ ]++ profile = titles._infer_document_body_profile(pages)++ assert profile is not None+ assert body_font in profile.regular_fonts+ assert sparse_font not in profile.regular_fonts+++def test_document_regular_font_suppresses_code_page_false_title() -> None:+ """验证代码页中的全文常规字体说明保持正文,粗体步骤标签仍识别为标题。"""++ mono_font = ("MonoRegular", 0)+ regular_font = ("BodyRegular", 0)+ bold_font = ("HeadingBold", 1)+ lines = [+ _text_line(+ "code one",+ (0.0, 5.0, 100.0, 13.0),+ 0,+ effective_height=8.0,+ font_signature=mono_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ _text_line(+ "code two",+ (0.0, 15.0, 100.0, 23.0),+ 1,+ effective_height=8.0,+ font_signature=mono_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ _text_line(+ "ordinary instruction",+ (0.0, 40.0, 45.0, 50.0),+ 2,+ effective_height=10.0,+ font_signature=regular_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ _text_line(+ "code three",+ (0.0, 62.0, 100.0, 70.0),+ 3,+ effective_height=8.0,+ font_signature=mono_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ _text_line(+ "code four",+ (0.0, 72.0, 100.0, 80.0),+ 4,+ effective_height=8.0,+ font_signature=mono_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ _text_line(+ "bold step",+ (0.0, 100.0, 35.0, 110.0),+ 5,+ effective_height=10.0,+ font_signature=bold_font,+ font_coverage=1.0,+ dominant_font_weight=800.0,+ ),+ _text_line(+ "code five",+ (0.0, 122.0, 100.0, 130.0),+ 6,+ effective_height=8.0,+ font_signature=mono_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ ]+ profile = titles._DocumentBodyProfile(+ body_height=10.0,+ body_weight=400.0,+ regular_fonts=frozenset({mono_font, regular_font}),+ )++ titles._classify_page_titles(+ lines,+ (100.0, 150.0),+ page_index=1,+ container_bboxes=[],+ document_body_profile=profile,+ )++ assert lines[2].semantic_type is None+ assert lines[5].semantic_type == "paragraph_title"+++def test_smaller_recurrent_regular_font_does_not_gain_title_style_signal() -> None:+ """验证较小的跨页常规代码字体即使留白较大,也不会仅凭字体切换升为标题。"""++ body_font = ("BodyRegular", 0)+ mono_font = ("MonoRegular", 0)+ lines = [+ _text_line(+ "body one",+ (0.0, 5.0, 100.0, 15.0),+ 0,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ _text_line(+ "body two",+ (0.0, 17.0, 100.0, 27.0),+ 1,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ _text_line(+ "small regular command",+ (2.0, 45.0, 98.0, 53.0),+ 2,+ effective_height=8.0,+ font_signature=mono_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ _text_line(+ "body three",+ (0.0, 70.0, 100.0, 80.0),+ 3,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ _text_line(+ "body four",+ (0.0, 82.0, 100.0, 92.0),+ 4,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ ]+ profile = titles._DocumentBodyProfile(+ body_height=10.0,+ body_weight=400.0,+ regular_fonts=frozenset({body_font, mono_font}),+ )++ titles._classify_page_titles(+ lines,+ (100.0, 120.0),+ page_index=1,+ container_bboxes=[],+ document_body_profile=profile,+ )++ assert lines[2].semantic_type is None+++def test_document_profile_finds_cover_title_without_promoting_bottom_metadata() -> None:+ """验证全文正文基准可识别纯封面标题,底部版本元数据仍保持普通文本。"""++ title_font = ("TitleBold", 1)+ metadata_font = ("MetadataBold", 1)+ lines = [+ _text_line(+ "cover title one",+ (15.0, 55.0, 85.0, 80.0),+ 0,+ effective_height=25.0,+ font_signature=title_font,+ font_coverage=1.0,+ dominant_font_weight=800.0,+ ),+ _text_line(+ "cover title two",+ (25.0, 85.0, 75.0, 110.0),+ 1,+ effective_height=25.0,+ font_signature=title_font,+ font_coverage=1.0,+ dominant_font_weight=800.0,+ ),+ _text_line(+ "version metadata",+ (35.0, 168.0, 65.0, 178.0),+ 2,+ effective_height=10.0,+ font_signature=metadata_font,+ font_coverage=1.0,+ dominant_font_weight=800.0,+ ),+ _text_line(+ "date metadata",+ (30.0, 180.0, 70.0, 190.0),+ 3,+ effective_height=10.0,+ font_signature=metadata_font,+ font_coverage=1.0,+ dominant_font_weight=800.0,+ ),+ ]+ profile = titles._DocumentBodyProfile(10.0, 400.0, frozenset())++ titles._classify_page_titles(+ lines,+ (100.0, 200.0),+ page_index=0,+ container_bboxes=[],+ document_body_profile=profile,+ )++ assert [line.semantic_type for line in lines] == [+ "doc_title",+ "doc_title",+ None,+ None,+ ]diff --git a/tests/unittest/test_flash_pdf_index_blocks.py b/tests/unittest/test_flash_pdf_index_blocks.pynew file mode 100644index 00000000..a23f5d57--- /dev/null+++ b/tests/unittest/test_flash_pdf_index_blocks.py@@ -0,0 +1,137 @@+from __future__ import annotations++import pytest++from mineru.backend.flash.native_pdf import index_blocks++from _flash_pdf_test_utils import _text_line+++def _directory_lines(+ numeric_rows: set[int],+ *,+ row_count: int = 10,+) -> list[index_blocks._LineItem]:+ """构造带居中标题、宽目录条目和右侧页码片段的视觉行。"""++ lines = [+ _text_line(+ "centered heading",+ (40.0, 5.0, 60.0, 15.0),+ 100,+ visual_row_id=100,+ )+ ]+ for row_index in range(row_count):+ top = 30.0 + 12.0 * row_index+ lines.extend(+ [+ _text_line(+ f"entry {row_index} . . . .",+ (10.0, top, 80.0, top + 10.0),+ row_index * 2,+ visual_row_id=row_index,+ run_index=0,+ split_from_row=True,+ ),+ _text_line(+ str(row_index + 1) if row_index in numeric_rows else "continuation",+ (92.0, top, 96.0, top + 10.0),+ row_index * 2 + 1,+ visual_row_id=row_index,+ run_index=1,+ split_from_row=True,+ ),+ ]+ )+ return lines+++ "content",+ [+ "entry 12",+ "entry 12",+ "entry xiv",+ "entry IV。",+ "entry 9 )",+ ],+)+def test_index_page_number_suffix_supports_expected_forms(content: str) -> None:+ """验证目录行尾支持半角、全角、罗马页码及有限尾随标点。"""++ assert index_blocks._index_row_ends_in_page_number(content)++[email protected]("content", ["entry", "version A12x", "word LIVE"])+def test_index_page_number_suffix_rejects_non_page_number_tail(content: str) -> None:+ """验证普通词尾和字母数字混合标识不会被当作目录页码。"""++ assert not index_blocks._index_row_ends_in_page_number(content)+++def test_index_block_merges_split_rows_and_preserves_heading() -> None:+ """验证目录正文合成一个换行块,居中目录标题保持段落标题。"""++ lines = _directory_lines(set(range(6)), row_count=6)++ blocks, remaining = index_blocks._extract_index_blocks(+ lines,+ (100.0, 130.0),+ [],+ )++ assert len(blocks) == 1+ assert blocks[0]["type"] == "index"+ assert blocks[0]["content"] == "\n".join(f"entry {row_index} . . . . {row_index + 1}" for row_index in range(6))+ assert not str(blocks[0]["content"]).endswith("\n")+ assert [line.text for line in remaining] == ["centered heading"]+ assert remaining[0].semantic_type == "paragraph_title"+ assert all(line.semantic_type == "index" for line in lines if line is not remaining[0])+++ ("numeric_rows", "expected_block_count"),+ [+ ({0, 1, 2, 4, 6, 8, 9}, 1),+ ({0, 1, 2, 4, 6, 9}, 0),+ ],+)+def test_index_block_requires_seventy_percent_numeric_rows(+ numeric_rows: set[int],+ expected_block_count: int,+) -> None:+ """验证目录候选在 70% 页码行尾阈值处命中,低于阈值则拒绝。"""++ lines = _directory_lines(numeric_rows)++ blocks, _remaining = index_blocks._extract_index_blocks(+ lines,+ (100.0, 160.0),+ [],+ )++ assert len(blocks) == expected_block_count+++def test_numeric_lines_without_directory_width_or_sidecars_are_rejected() -> None:+ """验证仅有大量数字行尾而缺少宽行及页码侧栏时不会误判目录。"""++ lines = [+ _text_line(+ f"value {row_index}",+ (50.0, 10.0 + 12.0 * row_index, 90.0, 20.0 + 12.0 * row_index),+ row_index,+ visual_row_id=row_index,+ )+ for row_index in range(8)+ ]++ blocks, remaining = index_blocks._extract_index_blocks(+ lines,+ (100.0, 120.0),+ [],+ )++ assert blocks == []+ assert remaining == linesdiff --git a/tests/unittest/test_flash_pdf_pipeline.py b/tests/unittest/test_flash_pdf_pipeline.pyindex bb7a91da..3ff9f770 100644--- a/tests/unittest/test_flash_pdf_pipeline.py+++ b/tests/unittest/test_flash_pdf_pipeline.py@@ -11,6 +11,7 @@ from mineru.backend.flash.native_pdf import (formulas,geometry,graphics,+ index_blocks,line_layout,line_merging,models,@@ -89,6 +90,7 @@ def test_flash_extractor_has_no_local_ocr_runtime_logic() -> None:formulas,geometry,graphics,+ index_blocks,line_layout,line_merging,models,@@ -132,6 +134,7 @@ def test_native_pdf_domain_modules_do_not_import_each_other() -> None:auxiliary_text,formulas,graphics,+ index_blocks,tables,text_blocks,titles,@@ -157,6 +160,7 @@ def test_native_pdf_domain_modules_do_not_import_each_other() -> None:"page_number","page_footnote","aside_text",+ "index","equation",],)diff --git a/tests/unittest/test_flash_pdf_titles.py b/tests/unittest/test_flash_pdf_titles.pyindex 99da102b..fade9955 100644--- a/tests/unittest/test_flash_pdf_titles.py+++ b/tests/unittest/test_flash_pdf_titles.py@@ -761,6 +761,8 @@ def test_paragraph_title_detector_does_not_read_line_text() -> None:inspect.getsource(function)for function in (titles._classify_page_titles,+ titles._infer_document_body_profile,+ titles._document_font_is_regular,titles._build_physical_title_gap_map,titles._find_repeated_grid_title_suppressions,titles._find_container_visual_row_title_suppressions,@@ -769,6 +771,7 @@ def test_paragraph_title_detector_does_not_read_line_text() -> None:titles._document_title_fonts_compatible,titles._document_title_uses_page_fallback,titles._classify_paragraph_titles_in_lane,+ titles._line_uses_document_regular_font,titles._visual_row_has_body_style_sibling,titles._is_near_full_mixed_inline_row,titles._continues_local_body_row,