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 internal structure for Flash native PDF extraction with data models and processing pipeline
myhloli9f0c59eba8f9
diff --git a/mineru/backend/flash/__init__.py b/mineru/backend/flash/__init__.pyindex ac2ac734..48048444 100644--- a/mineru/backend/flash/__init__.py+++ b/mineru/backend/flash/__init__.py@@ -1 +1,3 @@-# Flash tier: CPU-only lightweight PDF text extraction.\ No newline at end of file+# Copyright (c) Opendatalab. All rights reserved.++# Flash tier: CPU-only lightweight PDF text extraction.diff --git a/mineru/backend/flash/native_pdf/__init__.py b/mineru/backend/flash/native_pdf/__init__.pynew file mode 100644index 00000000..0fbfb83e--- /dev/null+++ b/mineru/backend/flash/native_pdf/__init__.py@@ -0,0 +1,3 @@+# Copyright (c) Opendatalab. All rights reserved.++"""Flash 原生 PDF 提取的内部实现包。"""diff --git a/mineru/backend/flash/native_pdf/auxiliary_text.py b/mineru/backend/flash/native_pdf/auxiliary_text.pynew file mode 100644index 00000000..21d95ac6--- /dev/null+++ b/mineru/backend/flash/native_pdf/auxiliary_text.py@@ -0,0 +1,529 @@+# Copyright (c) Opendatalab. All rights reserved.++"""分类页眉、页脚、页码、侧栏和页脚注。"""++from __future__ import annotations++import re+import statistics+import unicodedata+from difflib import SequenceMatcher+from typing import Literal+++from mineru.types import BBox++from .models import (+ _AxisLine,+ _LineItem,+ _LocalAxisLine,+ _MarginalCandidate,+ _PreparedPage,+ _TextLane,+)+from .geometry import (+ _bbox_axis_overlap_ratio,+ _bbox_center_x,+ _bbox_center_y,+ _bbox_intersects,+ _expand_bbox,+ _horizontal_bbox_gap,+ _rotate_bbox_to_upright,+ _transform_axis_lines,+)+from .line_layout import (+ _effective_text_row_gap,+ _infer_text_lanes,+ _line_effective_height,+)+_PAGE_NUMBER_RE = re.compile(+ r"^\s*(?:page\s*)?[\-\u2013\u2014\u00b7\u2022]*\s*(?:\u7b2c\s*)?"+ r"(?P<value>\d{1,4}|[ivxlcdm]+|[\u3007\u96f6\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u4e24]+)"+ r"(?:\s*(?:/|of|\u5171)\s*(?:\d{1,4}|[ivxlcdm]+|[\u3007\u96f6\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u4e24]+))?"+ r"\s*(?:\u9875)?\s*[\-\u2013\u2014\u00b7\u2022]*\s*$",+ re.IGNORECASE,+)+++def _classify_page_auxiliary_text(prepared: _PreparedPage) -> None:+ """在容器认领后仅按空间关系标注侧栏文字和页脚注。"""++ _classify_aside_text(prepared.remaining_lines, prepared.page_size)+ prepared.page_footnote_groups = _classify_page_footnotes(+ prepared.remaining_lines,+ prepared.table_bboxes,+ prepared.drawing_lines,+ prepared.page_size,+ )+++def _classify_aside_text(+ lines: list[_LineItem],+ page_size: tuple[float, float],+) -> None:+ """在横排正文占绝对多数时,以边缘带和物理尺寸识别垂直侧栏。"""++ available = [line for line in lines if line.semantic_type is None]+ upright_lines = [line for line in available if line.angle == 0]+ if len(upright_lines) < 4:+ return++ support_by_angle = _geometric_text_support_by_angle(available, page_size)+ total_support = sum(support_by_angle.values())+ if total_support <= 0 or support_by_angle.get(0, 0.0) / total_support < 0.8:+ return++ page_width, page_height = page_size+ if page_width <= 0 or page_height <= 0:+ return+ # 侧栏必须完整位于 12% 边缘带,且兼具不超过 8% 的窄宽和至少 15% 的物理高度。+ aside_source_indices = {+ line.source_index+ for line in available+ if line.angle in {90, 270}+ and line.bbox[2] - line.bbox[0] <= 0.08 * page_width+ and line.bbox[3] - line.bbox[1] >= 0.15 * page_height+ and (+ line.bbox[2] <= 0.12 * page_width+ or line.bbox[0] >= 0.88 * page_width+ )+ }+ for line in available:+ if line.source_index in aside_source_indices:+ line.semantic_type = "aside_text"+++def _geometric_text_support_by_angle(+ lines: list[_LineItem],+ page_size: tuple[float, float],+) -> dict[int, float]:+ """按局部行宽乘有效行高累计各文字方向的纯几何支持度。"""++ support_by_angle: dict[int, float] = {}+ for line in lines:+ local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, line.angle)+ local_width = max(0.1, local_bbox[2] - local_bbox[0])+ support_by_angle[line.angle] = support_by_angle.get(line.angle, 0.0) + (+ local_width * _line_effective_height(line, local_bbox)+ )+ return support_by_angle+++def _classify_page_footnotes(+ lines: list[_LineItem],+ table_bboxes: list[BBox],+ drawing_lines: list[_AxisLine],+ page_size: tuple[float, float],+) -> list[set[int]]:+ """识别主方向页脚注,并按触发分隔线返回来源编号分组。"""++ available = [line for line in lines if line.semantic_type is None]+ if not available or not drawing_lines:+ return []+ support_by_angle = _geometric_text_support_by_angle(available, page_size)+ if not support_by_angle:+ return []+ dominant_angle = max(+ sorted(support_by_angle),+ key=lambda angle: support_by_angle[angle],+ )+ line_geometry = [+ (line, _rotate_bbox_to_upright(line.bbox, page_size, dominant_angle))+ for line in available+ if line.angle == dominant_angle+ ]+ if not line_geometry:+ return []++ local_page_size = (+ (page_size[1], page_size[0])+ if dominant_angle in {90, 270}+ else page_size+ )+ local_page_width, local_page_height = local_page_size+ if local_page_width <= 0 or local_page_height <= 0:+ return []+ effective_heights = [+ _line_effective_height(line, bbox)+ for line, bbox in line_geometry+ ]+ median_height = statistics.median(effective_heights) if effective_heights else 1.0+ lanes = _infer_text_lanes(line_geometry, local_page_width, median_height)+ local_axis_lines = _transform_axis_lines(+ drawing_lines,+ page_size,+ dominant_angle,+ )++ candidate_groups: list[set[int]] = []+ for axis_line in local_axis_lines:+ if axis_line.orientation != "horizontal":+ continue+ # 分隔线中心必须进入页面下方 30%,上方的正文分隔线不参与脚注判定。+ rule_center_y = _bbox_center_y(axis_line.bbox)+ if rule_center_y < 0.7 * local_page_height:+ continue+ # 表格边界会产生断裂横线;除框内线段外,也排除与其同高且近邻的框外线段。+ if _rule_belongs_to_confirmed_table(+ axis_line,+ local_axis_lines,+ table_bboxes,+ local_page_width,+ ):+ continue+ rule_source_indices: set[int] = set()+ for lane in lanes:+ rule_source_indices.update(+ _footnote_lane_members(+ lane,+ axis_line.bbox,+ local_page_size,+ )+ )+ if rule_source_indices:+ candidate_groups.append(rule_source_indices)++ page_footnote_groups = _merge_overlapping_source_groups(candidate_groups)+ footnote_source_indices = set().union(*page_footnote_groups) if page_footnote_groups else set()+ for line in available:+ if line.source_index in footnote_source_indices:+ line.semantic_type = "page_footnote"+ return page_footnote_groups+++def _rule_belongs_to_confirmed_table(+ candidate: _LocalAxisLine,+ local_axis_lines: list[_LocalAxisLine],+ table_bboxes: list[BBox],+ local_page_width: float,+) -> bool:+ """把表格框内横线及其同高近邻断裂段一并排除,避免框外残段触发脚注。"""++ if not table_bboxes:+ return False+ maximum_segment_gap = 0.04 * local_page_width+ for table_line in local_axis_lines:+ if table_line.orientation != "horizontal":+ continue+ table_margin = max(0.5, table_line.width)+ if not any(+ _bbox_intersects(+ _expand_bbox(table_line.original_bbox, table_margin),+ table_bbox,+ )+ for table_bbox in table_bboxes+ ):+ continue+ center_tolerance = max(1.0, candidate.width, table_line.width)+ if abs(_bbox_center_y(candidate.bbox) - _bbox_center_y(table_line.bbox)) > center_tolerance:+ continue+ if _horizontal_bbox_gap(candidate.bbox, table_line.bbox) <= maximum_segment_gap:+ return True+ return False+++def _merge_overlapping_source_groups(groups: list[set[int]]) -> list[set[int]]:+ """合并共享来源行的分隔线候选组,消除重复绘图线造成的重复分组。"""++ merged: list[set[int]] = []+ for group in groups:+ combined = set(group)+ index = 0+ while index < len(merged):+ if combined & merged[index]:+ combined.update(merged.pop(index))+ index = 0+ continue+ index += 1+ merged.append(combined)+ return sorted(merged, key=lambda group: min(group))+++def _footnote_lane_members(+ lane: _TextLane,+ rule_bbox: BBox,+ local_page_size: tuple[float, float],+) -> set[int]:+ """验证横线与单个栏带的对齐关系,并返回其下连续脚注行的来源编号。"""++ lane_lines = [item for item in lane.lines if item[0].semantic_type is None]+ if not lane_lines:+ return set()+ lane_lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))+ local_page_width, local_page_height = local_page_size+ lane_width = max(0.1, lane.right - lane.left)+ lane_heights = [_line_effective_height(line, bbox) for line, bbox in lane_lines]+ median_height = statistics.median(lane_heights) if lane_heights else 1.0+ rule_width = max(0.0, rule_bbox[2] - rule_bbox[0])+ # 同时限制绝对短线、相对长线和左缘偏移,排除图标、公式线及跨栏正文分隔线。+ if rule_width < max(4.0 * median_height, 0.04 * local_page_width):+ return set()+ if rule_width > 0.65 * lane_width:+ return set()+ if abs(rule_bbox[0] - lane.left) > max(2.0 * median_height, 0.04 * lane_width):+ return set()++ # 首行采用较宽的 3.5% 页高窗口;命中后仅按紧凑的连续净空向下扩展。+ first_gap_limit = max(3.0 * median_height, 0.035 * local_page_height)+ first_index: int | None = None+ for index, (_line, bbox) in enumerate(lane_lines):+ rule_gap = bbox[1] - rule_bbox[3]+ if rule_gap < -0.5 * median_height:+ continue+ if rule_gap <= first_gap_limit:+ first_index = index+ break+ if first_index is None:+ return set()++ continuation_gap_limit = max(1.25 * median_height, 0.01 * local_page_height)+ members = [lane_lines[first_index]]+ for current in lane_lines[first_index + 1 :]:+ if _effective_text_row_gap(members[-1], current) > continuation_gap_limit:+ break+ members.append(current)+ return {line.source_index for line, _bbox in members}+++def _classify_repeated_page_marginals(pages: list[_PreparedPage]) -> None:+ """仅用相邻或同奇偶页的重复证据标注页码、页眉和页脚。"""++ if len(pages) < 2:+ return+ candidates = [+ candidate+ for page_index, page in enumerate(pages)+ for line in page.remaining_lines+ if (candidate := _build_marginal_candidate(page_index, line, page.page_size)) is not None+ ]++ for left_index, left in enumerate(candidates):+ left_value = _parse_page_number_value(left.line.text)+ if left_value is None:+ continue+ for right in candidates[left_index + 1 :]:+ page_delta = right.page_index - left.page_index+ if page_delta > 2:+ break+ right_value = _parse_page_number_value(right.line.text)+ if (+ page_delta > 0+ and right_value is not None+ and right_value - left_value == page_delta+ and _page_number_candidates_match(left, right)+ ):+ left.line.semantic_type = "page_number"+ right.line.semantic_type = "page_number"++ for left_index, left in enumerate(candidates):+ if left.line.semantic_type == "page_number":+ continue+ for right in candidates[left_index + 1 :]:+ page_delta = right.page_index - left.page_index+ if page_delta > 2:+ break+ if (+ page_delta > 0+ and left.region != "side"+ and right.region != "side"+ and right.line.semantic_type != "page_number"+ and _marginal_geometry_matches(left, right)+ and _marginal_text_matches(left.line.text, right.line.text)+ ):+ left.line.semantic_type = left.region+ right.line.semantic_type = right.region+++def _build_marginal_candidate(+ page_index: int,+ line: _LineItem,+ page_size: tuple[float, float],+) -> _MarginalCandidate | None:+ """把页面上下百分之十五内的常规小行转换成跨页比较候选。"""++ if line.semantic_type is not None:+ return None+ local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, line.angle)+ local_page_size = (page_size[1], page_size[0]) if line.angle in {90, 270} else page_size+ local_page_width, local_page_height = local_page_size+ if local_page_width <= 0 or local_page_height <= 0:+ return None+ normalized_center_y = _bbox_center_y(local_bbox) / local_page_height+ normalized_center_x = _bbox_center_x(local_bbox) / local_page_width+ if normalized_center_y <= 0.15:+ region: Literal["header", "footer", "side"] = "header"+ elif normalized_center_y >= 0.85:+ region = "footer"+ elif (+ normalized_center_y <= 0.18+ or normalized_center_y >= 0.82+ or (+ (normalized_center_x <= 0.15 or normalized_center_x >= 0.85)+ and (normalized_center_y <= 0.3 or normalized_center_y >= 0.7)+ )+ ):+ # 仅页码递增逻辑会消费 side;稳定文本不会被侧栏位置猜成页眉页脚。+ region = "side"+ else:+ return None+ if _line_effective_height(line, local_bbox) > 0.06 * local_page_height:+ return None+ return _MarginalCandidate(+ page_index=page_index,+ line=line,+ local_bbox=local_bbox,+ local_page_size=local_page_size,+ region=region,+ )+++def _page_number_candidates_match(+ first: _MarginalCandidate,+ second: _MarginalCandidate,+) -> bool:+ """校验连续页码的同边缘几何,横竖版切换时允许边缘位置随版面改变。"""++ if _marginal_geometry_matches(first, second):+ return True+ first_landscape = first.local_page_size[0] > first.local_page_size[1]+ second_landscape = second.local_page_size[0] > second.local_page_size[1]+ if first_landscape == second_landscape or first.line.angle != second.line.angle:+ return False+ first_height = _line_effective_height(first.line, first.local_bbox) / first.local_page_size[1]+ second_height = _line_effective_height(second.line, second.local_bbox) / second.local_page_size[1]+ return min(first_height, second_height) > 0 and max(first_height, second_height) / min(+ first_height,+ second_height,+ ) <= 1.5+++def _marginal_geometry_matches(+ first: _MarginalCandidate,+ second: _MarginalCandidate,+) -> bool:+ """比较边缘候选的方向、纵向带、字号以及同侧或镜像横向位置。"""++ if first.region != second.region or first.line.angle != second.line.angle:+ return False+ first_width, first_height = first.local_page_size+ second_width, second_height = second.local_page_size+ first_y = _bbox_center_y(first.local_bbox) / first_height+ second_y = _bbox_center_y(second.local_bbox) / second_height+ if abs(first_y - second_y) > 0.025:+ return False+ first_line_height = _line_effective_height(first.line, first.local_bbox) / first_height+ second_line_height = _line_effective_height(second.line, second.local_bbox) / second_height+ if min(first_line_height, second_line_height) <= 0 or max(first_line_height, second_line_height) / min(+ first_line_height,+ second_line_height,+ ) > 1.35:+ return False+ if (+ first.line.font_signature is not None+ and second.line.font_signature is not None+ and first.line.font_coverage >= 0.75+ and second.line.font_coverage >= 0.75+ and first.line.font_signature != second.line.font_signature+ ):+ return False++ first_normalized_bbox = (+ first.local_bbox[0] / first_width,+ first.local_bbox[1] / first_height,+ first.local_bbox[2] / first_width,+ first.local_bbox[3] / first_height,+ )+ second_normalized_bbox = (+ second.local_bbox[0] / second_width,+ second.local_bbox[1] / second_height,+ second.local_bbox[2] / second_width,+ second.local_bbox[3] / second_height,+ )+ same_side = (+ _bbox_axis_overlap_ratio(first_normalized_bbox, second_normalized_bbox, axis="x") >= 0.4+ or abs(_bbox_center_x(first_normalized_bbox) - _bbox_center_x(second_normalized_bbox)) <= 0.08+ )+ mirrored = abs(+ _bbox_center_x(first_normalized_bbox) + _bbox_center_x(second_normalized_bbox) - 1.0+ ) <= 0.12+ return same_side or mirrored+++def _parse_page_number_value(text: str) -> int | None:+ """解析整行阿拉伯、罗马或中文页码;混有稳定正文的行不作为纯页码。"""++ normalized = unicodedata.normalize("NFKC", str(text or ""))+ match = _PAGE_NUMBER_RE.fullmatch(normalized)+ if match is None:+ return None+ value = match.group("value")+ if value.isdecimal():+ return int(value)+ if re.fullmatch(r"[ivxlcdm]+", value, re.IGNORECASE):+ return _roman_number_to_int(value)+ return _chinese_page_number_to_int(value)+++def _roman_number_to_int(value: str) -> int | None:+ """把页码中的规范罗马数字转换成整数,非法组合返回空。"""++ roman_values = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}+ normalized = value.upper()+ total = 0+ previous = 0+ for char in reversed(normalized):+ current = roman_values.get(char)+ if current is None:+ return None+ total += -current if current < previous else current+ previous = max(previous, current)+ if total <= 0 or total > 4999:+ return None+ return total+++def _chinese_page_number_to_int(value: str) -> int | None:+ """把常见百位以内中文页码转换成整数,供跨页递增校验使用。"""++ digits = {"〇": 0, "零": 0, "一": 1, "二": 2, "两": 2, "三": 3, "四": 4, "五": 5, "六": 6, "七": 7, "八": 8, "九": 9}+ if all(char in digits for char in value):+ try:+ return int("".join(str(digits[char]) for char in value))+ except ValueError:+ return None+ total = 0+ current_digit = 0+ for char in value:+ if char in digits:+ current_digit = digits[char]+ elif char == "十":+ total += (current_digit or 1) * 10+ current_digit = 0+ elif char == "百":+ total += (current_digit or 1) * 100+ current_digit = 0+ else:+ return None+ return total + current_digit if total + current_digit > 0 else None+++def _marginal_text_matches(first_text: str, second_text: str) -> bool:+ """在屏蔽变化数字后比较边缘稳定文本,短文本只接受完全一致。"""++ first = _normalize_marginal_text(first_text)+ second = _normalize_marginal_text(second_text)+ if not first or not second:+ return False+ if first == second:+ return True+ if min(len(first), len(second)) < 8:+ return False+ return SequenceMatcher(a=first, b=second, autojunk=False).ratio() >= 0.92+++def _normalize_marginal_text(text: str) -> str:+ """统一边缘重复文本的宽窄字符、大小写、空白和可变数字。"""++ normalized = unicodedata.normalize("NFKC", str(text or "")).casefold()+ normalized = re.sub(r"\d+", "#", normalized)+ return re.sub(r"\s+", "", normalized).strip()diff --git a/mineru/backend/flash/native_pdf/formulas.py b/mineru/backend/flash/native_pdf/formulas.pynew file mode 100644index 00000000..9f2b46e8--- /dev/null+++ b/mineru/backend/flash/native_pdf/formulas.py@@ -0,0 +1,576 @@+# Copyright (c) Opendatalab. All rights reserved.++"""按空间关系检测并物化原生 PDF 公式块。"""++from __future__ import annotations++import re+import statistics+from dataclasses import replace+from typing import Any+++from mineru.types import BBox++from .models import (+ _FormulaAnchor,+ _LineItem,+ _TextLane,+)+from .geometry import (+ _bbox_axis_overlap_ratio,+ _bbox_center_x,+ _bbox_center_y,+ _bbox_union,+ _bbox_union_many,+ _rotate_bbox_to_upright,+)+from .native_text import _sanitize_pdf_control_text+from .line_layout import (+ _connection_crosses_table,+ _infer_text_lanes,+ _line_effective_height,+)+from .line_merging import _join_formula_visual_row+++_FORMULA_NUMBER_SUFFIX_RE = re.compile(+ r"^(?P<prefix>.*?)(?P<marker>[((﹙][^()()﹙﹚\r\n]+[))﹚])\s*$"+)+++def _build_formula_like_blocks(+ lines: list[_LineItem],+ table_bboxes: list[BBox],+ page_size: tuple[float, float],+) -> tuple[list[dict[str, Any]], list[_LineItem]]:+ """仅依据栏带、右侧短锚点和空间连通关系聚合公式状区域。"""++ blocks: list[dict[str, Any]] = []+ claimed_source_indices: set[int] = set()+ for angle in sorted({line.angle for line in lines}):+ angle_geometry = [+ (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))+ for line in lines+ if line.angle == angle+ ]+ if len(angle_geometry) < 2:+ continue+ effective_heights = [_line_effective_height(line, bbox) for line, bbox in angle_geometry]+ median_height = statistics.median(effective_heights) if effective_heights else 1.0+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]+ lanes = _infer_text_lanes(angle_geometry, local_page_width, median_height)+ for lane in lanes:+ if lane.is_span or len(lane.lines) < 2:+ continue+ lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))+ dominant_body_font = _infer_formula_body_font(lane, median_height)+ anchors = _find_formula_spatial_anchors(+ lane,+ median_height,+ dominant_body_font,+ )+ if not anchors:+ continue+ anchor_centers = [_bbox_center_y(anchor.bbox) for anchor in anchors]+ lane_top = min(bbox[1] for _line, bbox in lane.lines)+ lane_bottom = max(bbox[3] for _line, bbox in lane.lines)+ for anchor_index, anchor in enumerate(anchors):+ anchor_line = anchor.line+ if anchor_line.source_index in claimed_source_indices:+ continue+ band_top = lane_top+ band_bottom = lane_bottom+ if anchor_index > 0:+ band_top = max(+ band_top,+ (anchor_centers[anchor_index - 1] + anchor_centers[anchor_index]) / 2.0,+ )+ if anchor_index + 1 < len(anchors):+ band_bottom = min(+ band_bottom,+ (anchor_centers[anchor_index] + anchor_centers[anchor_index + 1]) / 2.0,+ )+ members = _grow_formula_spatial_component(+ lane,+ anchor,+ band_top,+ band_bottom,+ claimed_source_indices,+ table_bboxes,+ dominant_body_font,+ median_height,+ )+ if len(members) < 2:+ continue+ if len(members) == 2 and _bbox_axis_overlap_ratio(+ members[0][1],+ members[1][1],+ axis="y",+ ) < 0.2:+ continue+ block = _formula_members_to_block(+ members,+ page_size,+ angle,+ anchor_source_index=anchor_line.source_index,+ )+ if block is None:+ continue+ blocks.append(block)+ claimed_source_indices.update(line.source_index for line, _bbox in members)++ remaining_lines = [line for line in lines if line.source_index not in claimed_source_indices]+ return blocks, remaining_lines+++def _find_formula_spatial_anchors(+ lane: _TextLane,+ median_height: float,+ dominant_body_font: tuple[str, int] | None = None,+) -> list[_FormulaAnchor]:+ """查找栏带右缘短块或带编号后缀的非正文字体公式锚点。"""++ lane_width = max(0.1, lane.right - lane.left)+ body_interval = _formula_lane_body_interval(lane, median_height)+ if body_interval is None:+ return []+ body_top, body_bottom = body_interval+ anchors: list[_FormulaAnchor] = []+ for line, bbox in lane.lines:+ line_height = _line_effective_height(line, bbox)+ line_width = bbox[2] - bbox[0]+ is_short_right_anchor = line_width <= max(4.0 * line_height, 0.12 * lane_width)+ has_formula_number_suffix = _split_trailing_formula_number(line.text) is not None+ is_wide_numbered_anchor = (+ has_formula_number_suffix+ and line_width <= 0.75 * lane_width+ and dominant_body_font is not None+ and (+ line.font_signature != dominant_body_font+ or line.font_coverage < 0.75+ )+ )+ if not is_short_right_anchor and not is_wide_numbered_anchor:+ continue+ same_row_fragments = [+ other_line+ for other_line, _other_bbox in lane.lines+ if line.visual_row_id is not None+ and other_line.visual_row_id == line.visual_row_id+ and (line.split_from_row or other_line.split_from_row)+ ]+ if len(same_row_fragments) >= 3 and not any(+ other_line.font_coverage < 0.75+ or (+ dominant_body_font is not None+ and other_line.font_signature != dominant_body_font+ )+ for other_line in same_row_fragments+ if other_line.source_index != line.source_index+ ):+ # 一条粗行被多个大空格拆成密集词组时更像普通排版行,不能把末词当作公式编号锚点。+ continue+ if abs(lane.right - bbox[2]) > max(3.0, 0.02 * lane_width):+ continue+ center_y = _bbox_center_y(bbox)+ detached_below_body = body_bottom < center_y <= body_bottom + 6.0 * median_height+ if not body_top <= center_y <= body_bottom and not detached_below_body:+ continue+ has_left_peer = any(+ other_line.source_index != line.source_index+ and other_bbox[2] - other_bbox[0] <= 0.75 * lane_width+ and _bbox_center_x(other_bbox) < bbox[0]+ and (+ _formula_detached_seed_vertical_match(+ bbox,+ line_height,+ other_bbox,+ _line_effective_height(other_line, other_bbox),+ )+ if detached_below_body+ else _formula_seed_vertical_match(+ bbox,+ line_height,+ other_bbox,+ _line_effective_height(other_line, other_bbox),+ )+ )+ for other_line, other_bbox in lane.lines+ )+ if has_left_peer:+ anchors.append(+ _FormulaAnchor(+ line=line,+ bbox=bbox,+ detached_below_body=detached_below_body,+ )+ )+ return _deduplicate_formula_anchors(anchors, median_height)+++def _infer_formula_body_font(+ lane: _TextLane,+ median_height: float,+) -> tuple[str, int] | None:+ """从栏内常规宽正文行推断 dominant font,供公式扩张排除正文前缀。"""++ lane_width = max(0.1, lane.right - lane.left)+ font_counts: dict[tuple[str, int], int] = {}+ for line, bbox in lane.lines:+ line_height = _line_effective_height(line, bbox)+ if bbox[2] - bbox[0] < 0.35 * lane_width:+ continue+ if not 0.8 * median_height <= line_height <= 1.25 * median_height:+ continue+ if line.font_signature is None or line.font_coverage < 0.75:+ continue+ font_counts[line.font_signature] = font_counts.get(line.font_signature, 0) + 1+ if not font_counts:+ return None+ return max(font_counts.items(), key=lambda item: (item[1], item[0]))[0]+++def _formula_lane_body_interval(+ lane: _TextLane,+ median_height: float,+) -> tuple[float, float] | None:+ """用连续出现的常规宽行确定栏带正文纵向范围,排除孤立页眉。"""++ lane_width = max(0.1, lane.right - lane.left)+ body_lines = sorted(+ (+ item+ for item in lane.lines+ if item[1][2] - item[1][0]+ >= max(4.0 * _line_effective_height(*item), 0.35 * lane_width)+ ),+ key=lambda item: (item[1][1], item[1][0]),+ )+ if len(body_lines) < 3:+ return None+ dense_lines: list[tuple[_LineItem, BBox]] = []+ for index, item in enumerate(body_lines):+ has_close_previous = index > 0 and item[1][1] - body_lines[index - 1][1][3] <= 1.5 * median_height+ has_close_next = (+ index + 1 < len(body_lines)+ and body_lines[index + 1][1][1] - item[1][3] <= 1.5 * median_height+ )+ if has_close_previous or has_close_next:+ dense_lines.append(item)+ if len(dense_lines) < 3:+ return None+ return (+ min(bbox[1] for _line, bbox in dense_lines),+ max(bbox[3] for _line, bbox in dense_lines),+ )+++def _deduplicate_formula_anchors(+ anchors: list[_FormulaAnchor],+ median_height: float,+) -> list[_FormulaAnchor]:+ """同一高度出现多个右缘短块时只保留最靠右的空间锚点。"""++ if not anchors:+ return []+ output: list[_FormulaAnchor] = []+ tolerance = max(1.5, 0.35 * median_height)+ for anchor in sorted(anchors, key=lambda item: (_bbox_center_y(item.bbox), -item.bbox[2])):+ if output and abs(_bbox_center_y(anchor.bbox) - _bbox_center_y(output[-1].bbox)) <= tolerance:+ if (anchor.bbox[2], -anchor.bbox[0]) > (output[-1].bbox[2], -output[-1].bbox[0]):+ output[-1] = anchor+ continue+ output.append(anchor)+ return output+++def _grow_formula_spatial_component(+ lane: _TextLane,+ anchor: _FormulaAnchor,+ band_top: float,+ band_bottom: float,+ claimed_source_indices: set[int],+ table_bboxes: list[BBox],+ dominant_body_font: tuple[str, int] | None,+ median_height: float,+) -> list[tuple[_LineItem, BBox]]:+ """从右缘锚点的左侧首批成员出发,按二维邻接扩展公式分量。"""++ anchor_line, anchor_bbox = anchor.line, anchor.bbox+ anchor_geometry = (anchor_line, anchor_bbox)+ lane_width = max(0.1, lane.right - lane.left)+ candidates = [+ item+ for item in lane.lines+ if item[0].source_index not in claimed_source_indices+ and item[1][2] - item[1][0] <= 0.8 * lane_width+ and band_top <= _bbox_center_y(item[1]) <= band_bottom+ and not _is_formula_body_barrier(+ item,+ lane,+ dominant_body_font,+ median_height,+ )+ and not _is_formula_body_prefix(+ item,+ lane,+ anchor_geometry,+ dominant_body_font,+ median_height,+ )+ ]+ seeds = [+ item+ for item in candidates+ if item[0].source_index != anchor_line.source_index+ and _bbox_center_x(item[1]) < anchor_bbox[0]+ and (+ _formula_detached_seed_vertical_match(+ anchor_bbox,+ _line_effective_height(anchor_line, anchor_bbox),+ item[1],+ _line_effective_height(*item),+ )+ if anchor.detached_below_body+ else _formula_seed_vertical_match(+ anchor_bbox,+ _line_effective_height(anchor_line, anchor_bbox),+ item[1],+ _line_effective_height(*item),+ )+ )+ and not _connection_crosses_table(anchor_line.bbox, item[0].bbox, table_bboxes)+ ]+ if not seeds:+ return []++ members = [anchor_geometry, *seeds]+ member_sources = {line.source_index for line, _bbox in members}+ changed = True+ while changed:+ changed = False+ for candidate in candidates:+ candidate_line, candidate_bbox = candidate+ if candidate_line.source_index in member_sources:+ continue+ if any(+ _formula_lines_are_connected(+ member_line,+ member_bbox,+ candidate_line,+ candidate_bbox,+ table_bboxes,+ )+ for member_line, member_bbox in members+ ):+ members.append(candidate)+ member_sources.add(candidate_line.source_index)+ changed = True+ return members+++def _is_formula_body_barrier(+ candidate: tuple[_LineItem, BBox],+ lane: _TextLane,+ dominant_body_font: tuple[str, int] | None,+ median_height: float,+) -> bool:+ """识别近满栏、高置信正文行,阻止公式连通分量跨越正文边界。"""++ if dominant_body_font is None:+ return False+ line, bbox = candidate+ lane_width = max(0.1, lane.right - lane.left)+ line_height = _line_effective_height(line, bbox)+ return (+ line.font_signature == dominant_body_font+ and bbox[2] - bbox[0] >= 0.85 * lane_width+ and 0.8 * median_height <= line_height <= 1.25 * median_height+ )+++def _is_formula_body_prefix(+ candidate: tuple[_LineItem, BBox],+ lane: _TextLane,+ anchor: tuple[_LineItem, BBox],+ dominant_body_font: tuple[str, int] | None,+ median_height: float,+) -> bool:+ """识别锚点上方左对齐的常规正文行,防止公式空间扩张越界认领。"""++ if dominant_body_font is None:+ return False+ line, bbox = candidate+ anchor_line, anchor_bbox = anchor+ line_height = _line_effective_height(line, bbox)+ anchor_height = _line_effective_height(anchor_line, anchor_bbox)+ if _bbox_center_y(bbox) > _bbox_center_y(anchor_bbox) - 0.2 * max(line_height, anchor_height):+ return False+ if abs(bbox[0] - lane.left) > max(3.0, 0.75 * median_height):+ return False+ return (+ line.font_signature == dominant_body_font+ and line.font_coverage >= 0.75+ and 0.8 * median_height <= line_height <= 1.25 * median_height+ )+++def _formula_detached_seed_vertical_match(+ anchor_bbox: BBox,+ anchor_height: float,+ candidate_bbox: BBox,+ candidate_height: float,+) -> bool:+ """放宽正文密集区下方锚点的同高匹配,以接纳多行分段公式底部。"""++ has_vertical_overlap = min(anchor_bbox[3], candidate_bbox[3]) > max(anchor_bbox[1], candidate_bbox[1])+ center_difference = abs(_bbox_center_y(anchor_bbox) - _bbox_center_y(candidate_bbox))+ return has_vertical_overlap or center_difference <= max(anchor_height, candidate_height)+++def _formula_seed_vertical_match(+ anchor_bbox: BBox,+ anchor_height: float,+ candidate_bbox: BBox,+ candidate_height: float,+) -> bool:+ """判断左侧短行是否与右缘锚点处在同一公式高度带。"""++ overlap_ratio = _bbox_axis_overlap_ratio(anchor_bbox, candidate_bbox, axis="y")+ center_difference = abs(_bbox_center_y(anchor_bbox) - _bbox_center_y(candidate_bbox))+ return overlap_ratio >= 0.3 or center_difference <= 0.6 * max(anchor_height, candidate_height)+++def _formula_lines_are_connected(+ first_line: _LineItem,+ first_bbox: BBox,+ second_line: _LineItem,+ second_bbox: BBox,+ table_bboxes: list[BBox],+) -> bool:+ """按垂直接近和水平覆盖判断两个公式成员是否空间连通。"""++ if first_line.angle != second_line.angle:+ return False+ if _connection_crosses_table(first_line.bbox, second_line.bbox, table_bboxes):+ return False+ first_height = _line_effective_height(first_line, first_bbox)+ second_height = _line_effective_height(second_line, second_bbox)+ pair_height = max(first_height, second_height)+ vertical_overlap = _bbox_axis_overlap_ratio(first_bbox, second_bbox, axis="y")+ vertical_gap = max(first_bbox[1] - second_bbox[3], second_bbox[1] - first_bbox[3], 0.0)+ if vertical_overlap < 0.2 and vertical_gap > 0.6 * pair_height:+ return False+ horizontal_overlap = _bbox_axis_overlap_ratio(first_bbox, second_bbox, axis="x")+ horizontal_gap = max(first_bbox[0] - second_bbox[2], second_bbox[0] - first_bbox[2], 0.0)+ return horizontal_overlap > 0.0 or horizontal_gap <= 1.5 * pair_height+++def _is_detached_formula_sidecar(+ anchor: tuple[_LineItem, BBox],+ members: list[tuple[_LineItem, BBox]],+ median_height: float,+) -> bool:+ """仅依据 bbox 判断右侧锚点是否为与公式主体分离的窄幅 sidecar。"""++ anchor_line, anchor_bbox = anchor+ body_bboxes = [+ bbox+ for line, bbox in members+ if line.source_index != anchor_line.source_index+ ]+ if not body_bboxes:+ return False++ body_bbox = _bbox_union_many(body_bboxes)+ component_bbox = _bbox_union(body_bbox, anchor_bbox)+ effective_height = max(0.1, median_height)+ anchor_width = max(0.0, anchor_bbox[2] - anchor_bbox[0])+ component_width = max(0.1, component_bbox[2] - component_bbox[0])+ horizontal_gap = anchor_bbox[0] - body_bbox[2]+ right_tolerance = max(0.5, 0.1 * effective_height)+ minimum_gap = max(2.5 * effective_height, 0.08 * component_width)++ return (+ anchor_bbox[0] >= body_bbox[2]+ and anchor_bbox[2] >= component_bbox[2] - right_tolerance+ and anchor_width <= 2.0 * effective_height+ and horizontal_gap > minimum_gap+ )+++def _split_trailing_formula_number(text: str) -> tuple[str, str] | None:+ """拆出右缘文本末尾的圆括号公式序号,并保留序号前的标点或正文。"""++ match = _FORMULA_NUMBER_SUFFIX_RE.fullmatch(str(text or "").strip())+ if match is None:+ return None+ return match.group("prefix").rstrip(), match.group("marker").strip()+++def _formula_members_to_block(+ members: list[tuple[_LineItem, BBox]],+ page_size: tuple[float, float],+ angle: int,+ *,+ anchor_source_index: int,+) -> dict[str, Any] | None:+ """把公式空间分量按视觉行聚类,并将非末视觉行的离散右侧 sidecar 后置。"""++ heights = [_line_effective_height(line, bbox) for line, bbox in members]+ median_height = statistics.median(heights) if heights else 1.0+ row_tolerance = max(1.5, 0.35 * median_height)+ rows: list[list[tuple[_LineItem, BBox]]] = []+ for member in sorted(members, key=lambda item: (_bbox_center_y(item[1]), item[1][0], item[0].source_index)):+ if not rows:+ rows.append([member])+ continue+ row_center = statistics.median(_bbox_center_y(bbox) for _line, bbox in rows[-1])+ if abs(_bbox_center_y(member[1]) - row_center) <= row_tolerance:+ rows[-1].append(member)+ else:+ rows.append([member])++ trailing_sidecar_content: str | None = None+ # 右侧 sidecar 按视觉 y 常落在分式中部;仅在其后仍有公式行时转为逻辑末行。+ for row_index, row in enumerate(rows[:-1]):+ anchor_member = next(+ (member for member in row if member[0].source_index == anchor_source_index),+ None,+ )+ if anchor_member is None:+ continue+ formula_number_parts = _split_trailing_formula_number(anchor_member[0].text)+ if formula_number_parts is not None:+ prefix, marker = formula_number_parts+ rows[row_index] = [+ (+ (replace(member[0], text=prefix), member[1])+ if member[0].source_index == anchor_source_index and prefix+ else member+ )+ for member in row+ if member[0].source_index != anchor_source_index or prefix+ ]+ trailing_sidecar_content = marker+ elif _is_detached_formula_sidecar(anchor_member, members, median_height):+ rows[row_index] = [+ member for member in row if member[0].source_index != anchor_source_index+ ]+ trailing_sidecar_content = anchor_member[0].text.strip()+ break++ row_contents = [_join_formula_visual_row(row, page_size) for row in rows if row]+ if trailing_sidecar_content is not None:+ row_contents.append(trailing_sidecar_content)+ content = _sanitize_pdf_control_text("\n".join(filter(None, row_contents)), preserve_newlines=True)+ if not content.strip():+ return None+ return {+ "type": "equation",+ "bbox": _bbox_union_many([line.bbox for line, _bbox in members]),+ "angle": angle,+ "content": content,+ }+diff --git a/mineru/backend/flash/native_pdf/geometry.py b/mineru/backend/flash/native_pdf/geometry.pynew file mode 100644index 00000000..4432029c--- /dev/null+++ b/mineru/backend/flash/native_pdf/geometry.py@@ -0,0 +1,252 @@+# Copyright (c) Opendatalab. All rights reserved.++"""Flash 原生 PDF 提取使用的纯几何工具。"""++from __future__ import annotations++import math+from typing import Any, Literal, Sequence+++from mineru.types import BBox++from .models import (+ _AxisLine,+ _LocalAxisLine,+)+def _horizontal_bbox_gap(first_bbox: BBox, second_bbox: BBox) -> float:+ """返回两个局部 bbox 在 x 轴上的无方向净空,重叠时为零。"""++ return max(first_bbox[0] - second_bbox[2], second_bbox[0] - first_bbox[2], 0.0)+++def _transform_axis_lines(+ lines: list[_AxisLine],+ page_size: tuple[float, float],+ angle: int,+) -> list[_LocalAxisLine]:+ """将原页面横竖线转入当前文本方向的局部坐标。"""++ output: list[_LocalAxisLine] = []+ for line in lines:+ local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, angle)+ orientation: Literal["horizontal", "vertical"] = (+ "horizontal" if local_bbox[2] - local_bbox[0] >= local_bbox[3] - local_bbox[1] else "vertical"+ )+ output.append(+ _LocalAxisLine(+ bbox=local_bbox,+ original_bbox=line.bbox,+ orientation=orientation,+ width=line.width,+ )+ )+ return output+++def _bbox_overlap_in_first(first: BBox, second: BBox) -> float:+ """计算交集面积占第一个 bbox 面积的比例。"""++ width = max(0.0, min(first[2], second[2]) - max(first[0], second[0]))+ height = max(0.0, min(first[3], second[3]) - max(first[1], second[1]))+ first_area = _bbox_area(first)+ return width * height / first_area if first_area > 0 else 0.0+++def _bbox_area(bbox: BBox) -> float:+ """返回合法 bbox 的非负面积。"""++ return max(0.0, bbox[2] - bbox[0]) * max(0.0, bbox[3] - bbox[1])+++def _normalize_bbox_to_thousandths(+ bbox: BBox,+ page_size: tuple[float, float],+) -> list[float]:+ """将绝对 bbox 转成千分位刻度,并保证舍入后的宽高至少各占一个刻度。"""++ page_width, page_height = page_size+ ticks = [+ max(0, min(1000, int(round(bbox[0] / page_width * 1000)))),+ max(0, min(1000, int(round(bbox[1] / page_height * 1000)))),+ max(0, min(1000, int(round(bbox[2] / page_width * 1000)))),+ max(0, min(1000, int(round(bbox[3] / page_height * 1000)))),+ ]+ if ticks[2] <= ticks[0]:+ if ticks[0] < 1000:+ ticks[2] = ticks[0] + 1+ else:+ ticks[0] = max(0, ticks[2] - 1)+ if ticks[3] <= ticks[1]:+ if ticks[1] < 1000:+ ticks[3] = ticks[1] + 1+ else:+ ticks[1] = max(0, ticks[3] - 1)+ return [tick / 1000 for tick in ticks]+++def _rotate_bbox_to_upright(+ bbox: BBox,+ page_size: tuple[float, float],+ angle: int,+) -> BBox:+ """将页面 bbox 转到当前文本方向的正向局部坐标。"""++ page_width, page_height = page_size+ x0, y0, x1, y1 = bbox+ if angle == 270:+ return (page_height - y1, x0, page_height - y0, x1)+ if angle == 90:+ return (y0, page_width - x1, y1, page_width - x0)+ if angle == 180:+ return (page_width - x1, page_height - y1, page_width - x0, page_height - y0)+ return bbox+++def _rotate_bbox_from_upright(+ bbox: BBox,+ page_size: tuple[float, float],+ angle: int,+) -> BBox:+ """将正向局部 bbox 逆变换回 PDF 页面坐标。"""++ page_width, page_height = page_size+ x0, y0, x1, y1 = bbox+ if angle == 270:+ return (y0, page_height - x1, y1, page_height - x0)+ if angle == 90:+ return (page_width - y1, x0, page_width - y0, x1)+ if angle == 180:+ return (page_width - x1, page_height - y1, page_width - x0, page_height - y0)+ return bbox+++def _coerce_bbox(value: Any) -> BBox | None:+ """将任意四元 bbox 规范成非退化浮点坐标。"""++ try:+ x0, y0, x1, y1 = [float(item) for item in value]+ except (TypeError, ValueError):+ return None+ left, right = sorted((x0, x1))+ top, bottom = sorted((y0, y1))+ if not all(math.isfinite(item) for item in (left, top, right, bottom)):+ return None+ if right <= left or bottom <= top:+ return None+ return (left, top, right, bottom)+++def _clip_bbox(+ bbox: BBox | None,+ page_size: tuple[float, float],+) -> BBox | None:+ """将 bbox 裁剪到页面范围,退化框返回 None。"""++ if bbox is None:+ return None+ page_width, page_height = page_size+ return _coerce_bbox(+ (+ max(0.0, min(page_width, bbox[0])),+ max(0.0, min(page_height, bbox[1])),+ max(0.0, min(page_width, bbox[2])),+ max(0.0, min(page_height, bbox[3])),+ )+ )+++def _bbox_union(first: BBox, second: BBox) -> BBox:+ """返回两个 bbox 的外接并集框。"""++ return (+ min(first[0], second[0]),+ min(first[1], second[1]),+ max(first[2], second[2]),+ max(first[3], second[3]),+ )+++def _bbox_union_many(bboxes: Sequence[BBox]) -> BBox:+ """返回非空 bbox 序列的外接并集框。"""++ if not bboxes:+ raise ValueError("bbox sequence must not be empty")+ result = bboxes[0]+ for bbox in bboxes[1:]:+ result = _bbox_union(result, bbox)+ return result+++def _expand_bbox(bbox: BBox, margin: float) -> BBox:+ """向四周扩展 bbox,仅供几何容差判定使用。"""++ return (+ bbox[0] - margin,+ bbox[1] - margin,+ bbox[2] + margin,+ bbox[3] + margin,+ )+++def _bbox_center_x(bbox: BBox) -> float:+ """返回 bbox 的水平中心。"""++ return (bbox[0] + bbox[2]) / 2.0+++def _bbox_center_y(bbox: BBox) -> float:+ """返回 bbox 的垂直中心。"""++ return (bbox[1] + bbox[3]) / 2.0+++def _bbox_intersects(first: BBox, second: BBox) -> bool:+ """检查两个 bbox 是否存在正面积交叠。"""++ return min(first[2], second[2]) > max(first[0], second[0]) and min(first[3], second[3]) > max(first[1], second[1])+++def _bbox_distance(first: BBox, second: BBox) -> float:+ """返回两个 bbox 的欧氏净空距离,交叠或相接时为零。"""++ horizontal_gap = max(first[0] - second[2], second[0] - first[2], 0.0)+ vertical_gap = max(first[1] - second[3], second[1] - first[3], 0.0)+ return math.hypot(horizontal_gap, vertical_gap)+++def _bbox_overlap_in_smaller(first: BBox, second: BBox) -> float:+ """计算交集面积占较小 bbox 面积的比例。"""++ width = max(0.0, min(first[2], second[2]) - max(first[0], second[0]))+ height = max(0.0, min(first[3], second[3]) - max(first[1], second[1]))+ intersection = width * height+ first_area = (first[2] - first[0]) * (first[3] - first[1])+ second_area = (second[2] - second[0]) * (second[3] - second[1])+ smaller_area = min(first_area, second_area)+ return intersection / smaller_area if smaller_area > 0 else 0.0+++def _bbox_axis_overlap_ratio(+ first: BBox,+ second: BBox,+ *,+ axis: Literal["x", "y"],+) -> float:+ """计算指定轴上的交叠长度占较短轴长的比例。"""++ if axis == "x":+ first_start, first_end = first[0], first[2]+ second_start, second_end = second[0], second[2]+ else:+ first_start, first_end = first[1], first[3]+ second_start, second_end = second[1], second[3]+ overlap = max(0.0, min(first_end, second_end) - max(first_start, second_start))+ shorter = min(first_end - first_start, second_end - second_start)+ return overlap / shorter if shorter > 0 else 0.0+++def _point_in_bbox(point: tuple[float, float], bbox: BBox) -> bool:+ """检查点是否位于 bbox 内部或边界上。"""++ return bbox[0] <= point[0] <= bbox[2] and bbox[1] <= point[1] <= bbox[3]diff --git a/mineru/backend/flash/native_pdf/graphics.py b/mineru/backend/flash/native_pdf/graphics.pynew file mode 100644index 00000000..6ea0577d--- /dev/null+++ b/mineru/backend/flash/native_pdf/graphics.py@@ -0,0 +1,513 @@+# Copyright (c) Opendatalab. All rights reserved.++"""检测 Form、矢量图形和栅格图片并认领内部文本。"""++from __future__ import annotations++import math+import statistics+from typing import Any+++from mineru.types import BBox++from .models import (+ _AxisLine,+ _GraphicCandidate,+ _LineItem,+ _PageSource,+ _TextLane,+)+from .geometry import (+ _bbox_area,+ _bbox_axis_overlap_ratio,+ _bbox_center_x,+ _bbox_center_y,+ _bbox_distance,+ _bbox_overlap_in_first,+ _bbox_overlap_in_smaller,+ _bbox_union,+ _bbox_union_many,+ _clip_bbox,+ _coerce_bbox,+ _point_in_bbox,+ _rotate_bbox_to_upright,+)+from .native_text import _sanitize_pdf_control_text+from .line_layout import (+ _infer_text_lanes,+ _line_effective_height,+)+from .line_merging import _join_formula_visual_row+++_MIN_RASTER_IMAGE_PAGE_AREA_RATIO = 0.005+++_MIN_FORM_IMAGE_PAGE_AREA_RATIO = 0.01+++_MAX_FORM_IMAGE_PAGE_AREA_RATIO = 0.8+++_IMAGE_CONTAINER_OVERLAP_THRESHOLD = 0.5+++def _form_supersedes_nested_bbox(form_bbox: BBox, nested_bbox: BBox) -> bool:+ """判断 Form 是否应整体吞并其内部面积明显更小的候选容器。"""++ form_area = _bbox_area(form_bbox)+ nested_area = _bbox_area(nested_bbox)+ return (+ form_area > 0+ and nested_area < 0.5 * form_area+ and _bbox_overlap_in_first(nested_bbox, form_bbox) >= 0.9+ )+++def _select_form_image_bboxes(source: _PageSource) -> list[BBox]:+ """按页面占比、行高和内部视觉证据筛选矢量 Form 图片候选。"""++ page_area = max(0.0, source.page_size[0]) * max(0.0, source.page_size[1])+ if page_area <= 0 or not source.form_bboxes:+ return []+ effective_heights = [+ _line_effective_height(line, line.bbox)+ for line in source.lines+ if line.angle == 0+ ]+ median_height = statistics.median(effective_heights) if effective_heights else 1.0+ output: list[BBox] = []+ for raw_bbox in source.form_bboxes:+ bbox = _clip_bbox(_coerce_bbox(raw_bbox), source.page_size)+ if bbox is None:+ continue+ width = bbox[2] - bbox[0]+ height = bbox[3] - bbox[1]+ area_ratio = _bbox_area(bbox) / page_area+ if not (+ _MIN_FORM_IMAGE_PAGE_AREA_RATIO <= area_ratio <= _MAX_FORM_IMAGE_PAGE_AREA_RATIO+ and width >= 4.0 * median_height+ and height >= 4.0 * median_height+ ):+ continue++ member_rows = {+ line.visual_row_id if line.visual_row_id is not None else line.source_index+ for line in source.lines+ if _bbox_overlap_in_first(line.bbox, bbox) >= 0.9+ }+ internal_drawing_count = sum(+ _bbox_overlap_in_first(drawing_line.bbox, bbox) >= 0.9+ for drawing_line in source.drawing_lines+ )+ if len(member_rows) < 2 and internal_drawing_count < 4:+ continue+ output.append(bbox)+ return sorted(output, key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]))+++def _build_form_image_blocks(+ source: _PageSource,+ form_bboxes: list[BBox],+ claimed_line_indices: set[int],+) -> tuple[list[dict[str, Any]], set[int]]:+ """把 Form 及其完整内含文本输出为 image,并保持 source_index 唯一认领。"""++ if not form_bboxes:+ return [], set()+ members_by_candidate: list[list[_LineItem]] = [[] for _ in form_bboxes]+ claimed: set[int] = set()+ for line in source.lines:+ if line.source_index in claimed_line_indices:+ continue+ matching_indices = [+ candidate_index+ for candidate_index, bbox in enumerate(form_bboxes)+ if _bbox_overlap_in_first(line.bbox, bbox) >= 0.9+ ]+ if not matching_indices:+ continue+ candidate_index = min(+ matching_indices,+ key=lambda index: (_bbox_area(form_bboxes[index]), index),+ )+ members_by_candidate[candidate_index].append(line)+ claimed.add(line.source_index)++ blocks = [+ {+ "type": "image",+ "bbox": bbox,+ "angle": 0,+ "content": _image_members_to_content(members, source.page_size),+ }+ for bbox, members in zip(form_bboxes, members_by_candidate, strict=True)+ ]+ blocks.sort(key=lambda block: (block["bbox"][1], block["bbox"][0]))+ return blocks, claimed+++def _build_graphic_like_blocks(+ source: _PageSource,+ table_bboxes: list[BBox],+ claimed_line_indices: set[int],+) -> tuple[list[dict[str, Any]], set[int]]:+ """在表格认领后把紧凑绘图组件及其短标签聚成内部图形文本块。"""++ lines = [line for line in source.lines if line.source_index not in claimed_line_indices]+ if len(lines) < 2 or len(source.drawing_lines) < 4:+ return [], set()++ effective_heights = [+ max(+ 0.1,+ line.effective_height+ or min(+ max(0.1, line.bbox[2] - line.bbox[0]),+ max(0.1, line.bbox[3] - line.bbox[1]),+ ),+ )+ for line in lines+ ]+ median_height = statistics.median(effective_heights)+ lanes = _infer_graphic_text_lanes(lines, source.page_size, median_height)+ candidates = _detect_graphic_candidates(+ source.drawing_lines,+ source.page_size,+ median_height,+ lanes,+ table_bboxes,+ )+ if not candidates:+ return [], set()++ row_groups: dict[tuple[int, int, int, int], list[_LineItem]] = {}+ for line in lines:+ lane_index = _graphic_lane_index(line.bbox, lanes)+ if line.visual_row_id is None:+ row_kind, row_identity = 1, line.source_index+ else:+ row_kind, row_identity = 0, line.visual_row_id+ row_groups.setdefault(+ (line.angle, row_kind, row_identity, lane_index),+ [],+ ).append(line)++ for row_lines in row_groups.values():+ row_lane_index = _graphic_lane_index(row_lines[0].bbox, lanes)+ matches: list[tuple[int, float, int]] = []+ for candidate_index, candidate in enumerate(candidates):+ if candidate.lane_index != row_lane_index:+ continue+ member_flags = [+ _is_graphic_label_member(line, candidate.core_bbox, median_height)+ for line in row_lines+ ]+ # 同一 pdftext 视觉行必须整体归属或整体保留,避免只吞掉 caption 的短碎片。+ if not all(member_flags):+ continue+ inside_count = sum(+ _point_in_bbox(+ (_bbox_center_x(line.bbox), _bbox_center_y(line.bbox)),+ candidate.core_bbox,+ )+ for line in row_lines+ )+ mean_distance = statistics.fmean(+ _bbox_distance(line.bbox, candidate.core_bbox) for line in row_lines+ )+ matches.append((-inside_count, mean_distance, candidate_index))+ if not matches:+ continue+ candidate_index = min(matches)[2]+ candidates[candidate_index].line_indices.update(line.source_index for line in row_lines)++ blocks: list[dict[str, Any]] = []+ claimed: set[int] = set()+ lines_by_index = {line.source_index: line for line in lines}+ for candidate in candidates:+ members = [+ lines_by_index[source_index]+ for source_index in sorted(candidate.line_indices)+ if source_index in lines_by_index+ ]+ if len(members) < 2:+ continue+ block = _graphic_members_to_block(candidate, members, source.page_size)+ if block is None:+ continue+ blocks.append(block)+ claimed.update(line.source_index for line in members)++ blocks.sort(key=lambda block: (block["bbox"][1], block["bbox"][0]))+ return blocks, claimed+++def _infer_graphic_text_lanes(+ lines: list[_LineItem],+ page_size: tuple[float, float],+ median_height: float,+) -> list[_TextLane]:+ """用横排正文推断页内栏带,供不同角度的图形标签共享栏归属。"""++ line_geometry = [(line, line.bbox) for line in lines if line.angle == 0]+ if not line_geometry:+ return [_TextLane(left=0.0, right=page_size[0])]+ angle_heights = [_line_effective_height(line, bbox) for line, bbox in line_geometry]+ angle_median_height = statistics.median(angle_heights) if angle_heights else median_height+ lanes = [+ lane+ for lane in _infer_text_lanes(+ line_geometry,+ page_size[0],+ angle_median_height,+ )+ if not lane.is_span+ ]+ return lanes or [_TextLane(left=0.0, right=page_size[0])]+++def _graphic_lane_index(bbox: BBox, lanes: list[_TextLane]) -> int:+ """按中心点、水平覆盖和距离为 bbox 选择唯一栏带。"""++ center_x = _bbox_center_x(bbox)+ best_index = 0+ best_score = (-1, -1.0, -math.inf)+ for lane_index, lane in enumerate(lanes):+ inside = int(lane.left <= center_x <= lane.right)+ overlap = max(0.0, min(bbox[2], lane.right) - max(bbox[0], lane.left))+ if inside:+ distance = 0.0+ else:+ distance = min(abs(center_x - lane.left), abs(center_x - lane.right))+ score = (inside, overlap, -distance)+ if score > best_score:+ best_score = score+ best_index = lane_index+ return best_index+++def _detect_graphic_candidates(+ drawing_lines: list[_AxisLine],+ page_size: tuple[float, float],+ median_height: float,+ lanes: list[_TextLane],+ table_bboxes: list[BBox],+) -> list[_GraphicCandidate]:+ """从非表格绘图线连通分量中筛选尺寸受限的图形容器。"""++ tolerance = max(2.0, 0.75 * median_height)+ candidates: list[_GraphicCandidate] = []+ for component in _connected_drawing_line_components(drawing_lines, tolerance):+ horizontal_count = sum(line.orientation == "horizontal" for line in component)+ vertical_count = len(component) - horizontal_count+ core_bbox = _bbox_union_many([line.bbox for line in component])+ width = core_bbox[2] - core_bbox[0]+ height = core_bbox[3] - core_bbox[1]+ if (+ len(component) < 4+ or horizontal_count < 2+ or vertical_count < 2+ or width < 4.0 * median_height+ or height < 3.0 * median_height+ or width > 0.5 * page_size[0]+ or height > 0.5 * page_size[1]+ ):+ continue+ if any(_bbox_overlap_in_smaller(core_bbox, table_bbox) >= 0.5 for table_bbox in table_bboxes):+ continue+ candidates.append(+ _GraphicCandidate(+ core_bbox=core_bbox,+ lane_index=_graphic_lane_index(core_bbox, lanes),+ )+ )+ return candidates+++def _connected_drawing_line_components(+ drawing_lines: list[_AxisLine],+ tolerance: float,+) -> list[list[_AxisLine]]:+ """按 bbox 间距连接相邻绘图线,并返回互不重叠的连通分量。"""++ parents = list(range(len(drawing_lines)))++ def find(index: int) -> int:+ """查找绘图线连通分量的根节点。"""++ while parents[index] != index:+ parents[index] = parents[parents[index]]+ index = parents[index]+ return index++ def union(first_index: int, second_index: int) -> None:+ """合并两个距离满足条件的绘图线分量。"""++ first_root = find(first_index)+ second_root = find(second_index)+ if first_root != second_root:+ parents[second_root] = first_root++ for first_index, first in enumerate(drawing_lines):+ for second_index in range(first_index + 1, len(drawing_lines)):+ if _bbox_distance(first.bbox, drawing_lines[second_index].bbox) <= tolerance:+ union(first_index, second_index)++ components: dict[int, list[_AxisLine]] = {}+ for line_index, line in enumerate(drawing_lines):+ components.setdefault(find(line_index), []).append(line)+ return list(components.values())+++def _is_graphic_label_member(+ line: _LineItem,+ core_bbox: BBox,+ median_height: float,+) -> bool:+ """判断短文本是否位于图形核心内部或对应轴向的邻近标签区。"""++ center = (_bbox_center_x(line.bbox), _bbox_center_y(line.bbox))+ if _point_in_bbox(center, core_bbox):+ return True++ line_height = max(+ 0.1,+ line.effective_height+ or min(+ max(0.1, line.bbox[2] - line.bbox[0]),+ max(0.1, line.bbox[3] - line.bbox[1]),+ ),+ )+ if line.angle in {90, 270}:+ primary_length = line.bbox[3] - line.bbox[1]+ core_primary_length = core_bbox[3] - core_bbox[1]+ else:+ primary_length = line.bbox[2] - line.bbox[0]+ core_primary_length = core_bbox[2] - core_bbox[0]+ if primary_length > min(5.0 * line_height, 0.5 * core_primary_length):+ return False++ horizontal_gap = max(core_bbox[0] - line.bbox[2], line.bbox[0] - core_bbox[2], 0.0)+ vertical_gap = max(core_bbox[1] - line.bbox[3], line.bbox[1] - core_bbox[3], 0.0)+ if _bbox_axis_overlap_ratio(line.bbox, core_bbox, axis="x") >= 0.15:+ return vertical_gap <= 2.5 * median_height+ if _bbox_axis_overlap_ratio(line.bbox, core_bbox, axis="y") >= 0.15:+ horizontal_limit = max(2.5 * median_height, 0.2 * (core_bbox[2] - core_bbox[0]))+ return horizontal_gap <= horizontal_limit+ return False+++def _image_members_to_content(+ members: list[_LineItem],+ page_size: tuple[float, float],+) -> str:+ """按视觉行和页内位置生成图片内部文本,保留不同视觉行之间的换行。"""++ row_groups: dict[tuple[int, int, int], list[_LineItem]] = {}+ for line in members:+ if line.visual_row_id is None:+ row_kind, row_identity = 1, line.source_index+ else:+ row_kind, row_identity = 0, line.visual_row_id+ row_groups.setdefault((line.angle, row_kind, row_identity), []).append(line)++ rows: list[tuple[BBox, str]] = []+ for row_lines in row_groups.values():+ row_bbox = _bbox_union_many([line.bbox for line in row_lines])+ angle = row_lines[0].angle+ local_geometry = [+ (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))+ for line in row_lines+ ]+ content = _join_formula_visual_row(local_geometry, page_size)+ if content:+ rows.append((row_bbox, content))+ rows.sort(key=lambda item: (item[0][1], item[0][0]))+ return _sanitize_pdf_control_text(+ "\n".join(row_content for _row_bbox, row_content in rows),+ preserve_newlines=True,+ ).strip()+++def _graphic_members_to_block(+ candidate: _GraphicCandidate,+ members: list[_LineItem],+ page_size: tuple[float, float],+) -> dict[str, Any] | None:+ """生成含内部文本的矢量图 image block,并合并绘图核心与标签 bbox。"""++ content = _image_members_to_content(members, page_size)+ if not content:+ return None+ return {+ "type": "image",+ "bbox": _bbox_union(candidate.core_bbox, _bbox_union_many([line.bbox for line in members])),+ "angle": 0,+ "content": content,+ }+++def _build_raster_image_blocks(+ source: _PageSource,+ container_blocks: list[dict[str, Any]],+ claimed_line_indices: set[int],+) -> tuple[list[dict[str, Any]], set[int]]:+ """过滤点阵图、避让高优先级容器,并唯一认领图片内部的原生文本。"""++ page_area = max(0.0, source.page_size[0]) * max(0.0, source.page_size[1])+ if page_area <= 0:+ return [], set()++ container_bboxes = [+ bbox+ for block in container_blocks+ if (bbox := _coerce_bbox(block.get("bbox"))) is not None+ ]+ candidate_bboxes: list[BBox] = []+ for raw_bbox in source.image_bboxes:+ bbox = _clip_bbox(_coerce_bbox(raw_bbox), source.page_size)+ if bbox is None or _bbox_area(bbox) / page_area < _MIN_RASTER_IMAGE_PAGE_AREA_RATIO:+ continue+ if any(+ _bbox_overlap_in_smaller(bbox, container_bbox) >= _IMAGE_CONTAINER_OVERLAP_THRESHOLD+ for container_bbox in container_bboxes+ ):+ continue+ candidate_bboxes.append(bbox)+ if not candidate_bboxes:+ return [], set()++ members_by_candidate: list[list[_LineItem]] = [[] for _ in candidate_bboxes]+ claimed: set[int] = set()+ for line in source.lines:+ if line.source_index in claimed_line_indices:+ continue+ center = (_bbox_center_x(line.bbox), _bbox_center_y(line.bbox))+ matching_indices = [+ candidate_index+ for candidate_index, bbox in enumerate(candidate_bboxes)+ if _point_in_bbox(center, bbox)+ ]+ if not matching_indices:+ continue+ # 重叠点阵图共享内部文本时归属最小容器,避免 content 重复。+ candidate_index = min(+ matching_indices,+ key=lambda index: (_bbox_area(candidate_bboxes[index]), index),+ )+ members_by_candidate[candidate_index].append(line)+ claimed.add(line.source_index)++ blocks = [+ {+ "type": "image",+ "bbox": bbox,+ "angle": 0,+ "content": _image_members_to_content(members, source.page_size),+ }+ for bbox, members in zip(candidate_bboxes, members_by_candidate, strict=True)+ ]+ blocks.sort(key=lambda block: (block["bbox"][1], block["bbox"][0]))+ return blocks, claimeddiff --git a/mineru/backend/flash/native_pdf/line_layout.py b/mineru/backend/flash/native_pdf/line_layout.pynew file mode 100644index 00000000..9846b6f5--- /dev/null+++ b/mineru/backend/flash/native_pdf/line_layout.py@@ -0,0 +1,482 @@+# Copyright (c) Opendatalab. All rights reserved.++"""提供文本栏带、行距和行连接的共享布局判定。"""++from __future__ import annotations++import math+import re+import statistics+++from mineru.backend.utils.char_utils import is_hyphen_at_line_end+from mineru.types import BBox++from .models import (+ _LineItem,+ _LocalAxisLine,+ _TextLane,+)+from .geometry import (+ _bbox_axis_overlap_ratio,+ _bbox_center_x,+ _bbox_center_y,+ _bbox_intersects,+ _coerce_bbox,+)+++def _title_fonts_compatible(first: _LineItem, second: _LineItem) -> bool:+ """检查标题字体和字重是否兼容;低字体覆盖率时仍保留可靠字重证据。"""++ font_conflicts = (+ first.font_signature is not None+ and second.font_signature is not None+ and first.font_coverage >= 0.75+ and second.font_coverage >= 0.75+ and first.font_signature != second.font_signature+ )+ weight_conflicts = (+ first.dominant_font_weight is not None+ and second.dominant_font_weight is not None+ and abs(first.dominant_font_weight - second.dominant_font_weight) >= 100.0+ and max(first.dominant_font_weight, second.dominant_font_weight)+ >= 1.15 * min(first.dominant_font_weight, second.dominant_font_weight)+ )+ return not (font_conflicts or weight_conflicts)+++def _should_connect_semantic_rows(+ previous: tuple[_LineItem, BBox],+ current: tuple[_LineItem, BBox],+ lane: _TextLane,+ regular_gap: float,+ table_bboxes: list[BBox],+ axis_lines: list[_LocalAxisLine],+) -> bool:+ """只用几何、字体和障碍连接同类型语义行,避免标题内容影响聚合。"""++ previous_line, previous_bbox = previous+ current_line, current_bbox = current+ if previous_line.semantic_type != current_line.semantic_type:+ return False+ if _connection_crosses_table(previous_line.bbox, current_line.bbox, table_bboxes):+ return False+ if _horizontal_rule_separates_rows(previous_bbox, current_bbox, lane, axis_lines):+ return False+ previous_height = _line_effective_height(previous_line, previous_bbox)+ current_height = _line_effective_height(current_line, current_bbox)+ pair_height = max(previous_height, current_height)+ if max(previous_height, current_height) / min(previous_height, current_height) > 1.35:+ return False+ vertical_gap = _effective_text_row_gap(previous, current)+ if not -0.25 * pair_height <= vertical_gap <= max(1.25 * pair_height, regular_gap + 0.75 * pair_height):+ return False+ if (+ previous_line.semantic_type == "paragraph_title"+ and vertical_gap > 0.65 * pair_height+ ):+ return False+ if (+ previous_line.font_signature is not None+ and current_line.font_signature is not None+ and previous_line.font_coverage >= 0.75+ and current_line.font_coverage >= 0.75+ and previous_line.font_signature != current_line.font_signature+ ):+ return False+ lane_width = max(0.1, lane.right - lane.left)+ centered_pair = (+ abs(_bbox_center_x(previous_bbox) - _bbox_center_x(current_bbox)) <= 0.15 * lane_width+ )+ aligned_pair = abs(previous_bbox[0] - current_bbox[0]) <= 0.75 * pair_height+ overlapping_pair = _bbox_axis_overlap_ratio(previous_bbox, current_bbox, axis="x") >= 0.35+ return centered_pair or aligned_pair or overlapping_pair+++def _line_effective_height(line: _LineItem, local_bbox: BBox) -> float:+ """返回字符统计得到的有效行高,缺失时回退到局部 bbox 高度。"""++ return max(0.1, line.effective_height or (local_bbox[3] - local_bbox[1]))+++def _effective_text_row_gap(+ previous: tuple[_LineItem, BBox],+ current: tuple[_LineItem, BBox],+) -> float:+ """按前一行顶边与有效行高计算净空,避免高数学字形拉长 bbox 底边。"""++ previous_line, previous_bbox = previous+ _current_line, current_bbox = current+ return current_bbox[1] - (previous_bbox[1] + _line_effective_height(previous_line, previous_bbox))+++def _infer_text_lanes(+ line_geometry: list[tuple[_LineItem, BBox]],+ local_page_width: float,+ median_height: float,+) -> list[_TextLane]:+ """从重复左右边缘推断稳定栏带,并把跨栏行放入独立 span lane。"""++ anchor_tolerance = max(3.0, 0.75 * median_height)+ regular_lines = [+ item+ for item in line_geometry+ if item[1][2] - item[1][0] >= max(4.0 * _line_effective_height(*item), 0.15 * local_page_width)+ ]+ left_clusters: list[list[tuple[_LineItem, BBox]]] = []+ for item in sorted(regular_lines, key=lambda value: value[1][0]):+ if not left_clusters:+ left_clusters.append([item])+ continue+ cluster_left = statistics.median(member[1][0] for member in left_clusters[-1])+ if abs(item[1][0] - cluster_left) <= anchor_tolerance:+ left_clusters[-1].append(item)+ else:+ left_clusters.append([item])++ supported_intervals = [+ (+ statistics.median(item[1][0] for item in cluster),+ statistics.median(item[1][2] for item in cluster),+ len(cluster),+ )+ for cluster in left_clusters+ if len(cluster) >= 3+ ]+ supported_intervals.sort(key=lambda interval: interval[0])+ filtered_intervals: list[tuple[float, float, int]] = []+ for interval in supported_intervals:+ if not filtered_intervals:+ filtered_intervals.append(interval)+ continue+ previous = filtered_intervals[-1]+ minimum_gutter = max(6.0, 0.75 * median_height)+ if interval[0] - previous[1] >= minimum_gutter:+ filtered_intervals.append(interval)+ elif interval[2] > previous[2]:+ filtered_intervals[-1] = interval++ if not filtered_intervals:+ source = regular_lines or line_geometry+ filtered_intervals = [+ (+ min(item[1][0] for item in source),+ max(item[1][2] for item in source),+ len(source),+ )+ ]++ lanes = [_TextLane(left=left, right=right) for left, right, _support in filtered_intervals]+ span_lines: list[tuple[_LineItem, BBox]] = []+ for item in line_geometry:+ bbox = item[1]+ line_width = max(0.1, bbox[2] - bbox[0])+ scored_lanes = [+ (+ max(0.0, min(bbox[2], lane.right) - max(bbox[0], lane.left)) / line_width,+ lane,+ )+ for lane in lanes+ ]+ coverage_scores = sorted(+ (coverage for coverage, _lane in scored_lanes),+ reverse=True,+ )+ # 同时覆盖两个稳定正文栏的短尾行仍属于跨栏内容,不能按中心点落回单栏。+ if len(coverage_scores) > 1 and coverage_scores[1] >= 0.2:+ span_lines.append(item)+ continue+ best_coverage, best_lane = max(scored_lanes, key=lambda value: value[0])+ if len(lanes) == 1 or (+ best_coverage >= 0.5+ and best_lane.left - anchor_tolerance+ <= _bbox_center_x(bbox)+ <= best_lane.right + anchor_tolerance+ ):+ best_lane.lines.append(item)+ else:+ span_lines.append(item)++ if span_lines:+ lanes.append(+ _TextLane(+ left=min(item[1][0] for item in span_lines),+ right=max(item[1][2] for item in span_lines),+ lines=span_lines,+ is_span=True,+ )+ )+ _reattach_span_lane_continuations(lanes, median_height)+ return lanes+++def _reattach_span_lane_continuations(+ lanes: list[_TextLane],+ median_height: float,+) -> None:+ """把紧随稳定跨栏多行之后的单栏宽短尾行迁回对应 span lane。"""++ regular_lanes = [lane for lane in lanes if not lane.is_span]+ span_lanes = [lane for lane in lanes if lane.is_span]+ if len(regular_lanes) < 2 or not span_lanes:+ return++ for span_lane in span_lanes:+ span_lane.lines.sort(+ key=lambda item: (item[1][1], item[1][0], item[0].source_index)+ )+ if len(span_lane.lines) < 2:+ continue+ previous, last = span_lane.lines[-2:]+ previous_height = _line_effective_height(*previous)+ last_height = _line_effective_height(*last)+ if (+ previous[0].semantic_type != last[0].semantic_type+ or abs(previous[1][0] - last[1][0]) > 0.75 * median_height+ or max(previous_height, last_height) / min(previous_height, last_height) > 1.35+ or not _title_fonts_compatible(previous[0], last[0])+ or not -0.25 * median_height+ <= _effective_text_row_gap(previous, last)+ <= 0.75 * median_height+ ):+ continue++ while True:+ candidates: list[+ tuple[+ float,+ float,+ _TextLane,+ tuple[_LineItem, BBox],+ ]+ ] = []+ for regular_lane in regular_lanes:+ for candidate in regular_lane.lines:+ candidate_line, candidate_bbox = candidate+ if (+ candidate_line.semantic_type != last[0].semantic_type+ or candidate_bbox[1] <= last[1][1]+ ):+ continue+ gap = _effective_text_row_gap(last, candidate)+ candidate_height = _line_effective_height(*candidate)+ if (+ not -0.25 * median_height <= gap <= 0.75 * median_height+ or abs(candidate_bbox[0] - last[1][0]) > 0.75 * median_height+ or max(last_height, candidate_height)+ / min(last_height, candidate_height)+ > 1.35+ or not _title_fonts_compatible(last[0], candidate_line)+ ):+ continue+ has_parallel_peer = any(+ other_line is not candidate_line+ and _bbox_axis_overlap_ratio(+ candidate_bbox,+ other_bbox,+ axis="y",+ )+ >= 0.5+ for lane in regular_lanes+ for other_line, other_bbox in lane.lines+ )+ if has_parallel_peer:+ continue+ candidates.append(+ (+ max(0.0, gap),+ candidate_bbox[1],+ regular_lane,+ candidate,+ )+ )+ if not candidates:+ break+ _gap, _top, regular_lane, candidate = min(+ candidates,+ key=lambda item: (item[0], item[1]),+ )+ regular_lane.lines.remove(candidate)+ span_lane.lines.append(candidate)+ span_lane.left = min(span_lane.left, candidate[1][0])+ span_lane.right = max(span_lane.right, candidate[1][2])+ span_lane.lines.sort(+ key=lambda item: (item[1][1], item[1][0], item[0].source_index)+ )+ last = candidate+ last_height = _line_effective_height(*last)+++def _estimate_lane_gap(lane: _TextLane) -> tuple[float, float]:+ """从栏带内兼容相邻行的较小间隙簇估计常规净空和 MAD。"""++ lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))+ heights = [_line_effective_height(line, bbox) for line, bbox in lane.lines]+ median_height = statistics.median(heights) if heights else 1.0+ gaps: list[float] = []+ for previous, current in zip(lane.lines, lane.lines[1:]):+ previous_line, previous_bbox = previous+ current_line, current_bbox = current+ if previous_line.visual_row_id == current_line.visual_row_id and (+ previous_line.split_from_row or current_line.split_from_row+ ):+ continue+ previous_height = _line_effective_height(previous_line, previous_bbox)+ current_height = _line_effective_height(current_line, current_bbox)+ if max(previous_height, current_height) / min(previous_height, current_height) > 1.35:+ continue+ pair_height = max(previous_height, current_height)+ gap = _effective_text_row_gap(previous, current)+ if gap < -0.25 * pair_height or gap > 2.0 * pair_height:+ continue+ if _bbox_axis_overlap_ratio(previous_bbox, current_bbox, axis="x") < 0.5 and abs(+ previous_bbox[0] - current_bbox[0]+ ) > 1.5 * median_height:+ continue+ # PDF 字符框常在相邻基线间产生极小重叠;按零净空计入常规行距统计。+ gaps.append(max(0.0, gap))++ if not gaps:+ return 0.35 * median_height, 0.0+ sorted_gaps = sorted(gaps)+ lower_count = max(1, math.ceil(len(sorted_gaps) * 0.6))+ lower_gaps = sorted_gaps[:lower_count]+ regular_gap = statistics.median(lower_gaps)+ gap_mad = statistics.median(abs(gap - regular_gap) for gap in lower_gaps)+ return regular_gap, gap_mad+++def _should_connect_text_rows(+ previous: tuple[_LineItem, BBox],+ current: tuple[_LineItem, BBox],+ lane: _TextLane,+ regular_gap: float,+ gap_mad: float,+ table_bboxes: list[BBox],+ axis_lines: list[_LocalAxisLine],+) -> bool:+ """综合局部间距、首行缩进、字体和障碍判断两个相邻视觉行是否同段。"""++ previous_line, previous_bbox = previous+ current_line, current_bbox = current+ previous_height = _line_effective_height(previous_line, previous_bbox)+ current_height = _line_effective_height(current_line, current_bbox)+ pair_height = max(previous_height, current_height)+ lane_width = max(0.1, lane.right - lane.left)+ previous_width = previous_bbox[2] - previous_bbox[0]+ current_width = current_bbox[2] - current_bbox[0]+ vertical_gap = _effective_text_row_gap(previous, current)+ if previous_line.visual_row_id == current_line.visual_row_id and (+ previous_line.split_from_row or current_line.split_from_row+ ):+ return False+ if (+ current_height < 0.88 * previous_height+ and vertical_gap > regular_gap + 0.25 * previous_height+ ):+ return False+ height_ratio = max(previous_height, current_height) / min(previous_height, current_height)+ if height_ratio > 1.35:+ both_fill_lane = previous_width >= 0.8 * lane_width and current_width >= 0.8 * lane_width+ aligned_left_edges = abs(previous_bbox[0] - current_bbox[0]) <= 0.5 * pair_height+ font_style_changed = (+ previous_line.font_signature is not None+ and current_line.font_signature is not None+ and previous_line.font_signature[1] != current_line.font_signature[1]+ )+ # 满栏混合字体可跨字号续接,但显式正体/斜体等样式边界仍保持原分段语义。+ if not both_fill_lane or not aligned_left_edges or font_style_changed:+ return False++ if vertical_gap < -0.25 * pair_height:+ return False+ if _bbox_axis_overlap_ratio(previous_bbox, current_bbox, axis="x") < 0.5 and abs(+ previous_bbox[0] - current_bbox[0]+ ) > 1.5 * pair_height:+ return False+ if _connection_crosses_table(previous_line.bbox, current_line.bbox, table_bboxes):+ return False+ if _horizontal_rule_separates_rows(previous_bbox, current_bbox, lane, axis_lines):+ return False++ gap_limit = max(+ regular_gap + max(0.5 * pair_height, 3.0 * gap_mad),+ 1.1 * pair_height,+ )+ # 排版断词可以跳过缩进、字体和短行规则,但仍须限制在邻近物理行内,+ # 避免页内远距离的 “cross-” 与后续标题被误拼为同一段。+ if is_hyphen_at_line_end(previous_line.text):+ return vertical_gap <= max(gap_limit, 1.8 * pair_height)+ if vertical_gap > gap_limit:+ return False++ terminal_previous = bool(re.search(r"[.!?。!?::;;][\]\)})】》”’'\"]*$", previous_line.text.rstrip()))+ if terminal_previous and vertical_gap > regular_gap + 0.5 * pair_height:+ return False++ # 局部版心可能比整栏推断边界更靠左,缩进需同时参考上一物理行。+ local_lane_left = min(lane.left, previous_bbox[0])+ local_lane_width = max(0.1, lane.right - local_lane_left)+ next_indent = current_bbox[0] - local_lane_left+ previous_fill = max(0.0, previous_bbox[2] - local_lane_left) / local_lane_width+ if next_indent >= max(5.0, 0.65 * pair_height) and (previous_fill <= 0.8 or terminal_previous):+ return False++ abnormal_gap = vertical_gap > regular_gap + 0.25 * pair_height+ if (+ previous_line.font_signature is not None+ and current_line.font_signature is not None+ and previous_line.font_coverage >= 0.75+ and current_line.font_coverage >= 0.75+ and previous_line.font_signature != current_line.font_signature+ and (abnormal_gap or min(previous_width, current_width) <= 0.7 * lane_width)+ ):+ return False+ if abnormal_gap and min(previous_width, current_width) <= 0.65 * lane_width:+ return False+ return True+++def _horizontal_rule_separates_rows(+ previous_bbox: BBox,+ current_bbox: BBox,+ lane: _TextLane,+ axis_lines: list[_LocalAxisLine],+) -> bool:+ """检查两个相邻文本行之间是否存在覆盖当前栏带的长水平规则线。"""++ if current_bbox[1] <= previous_bbox[3]:+ return False+ lane_width = max(0.1, lane.right - lane.left)+ for axis_line in axis_lines:+ if axis_line.orientation != "horizontal":+ continue+ line_y = _bbox_center_y(axis_line.bbox)+ if not previous_bbox[3] <= line_y <= current_bbox[1]:+ continue+ overlap = max(0.0, min(axis_line.bbox[2], lane.right) - max(axis_line.bbox[0], lane.left))+ if overlap / lane_width >= 0.6:+ return True+ return False+++def _connection_crosses_table(+ first_bbox: BBox,+ second_bbox: BBox,+ table_bboxes: list[BBox],+) -> bool:+ """检查两行中心连接区域是否穿过已确认表格。"""++ first_center = (_bbox_center_x(first_bbox), _bbox_center_y(first_bbox))+ second_center = (_bbox_center_x(second_bbox), _bbox_center_y(second_bbox))+ connector = _coerce_bbox(+ (+ min(first_center[0], second_center[0]) - 0.1,+ min(first_center[1], second_center[1]) - 0.1,+ max(first_center[0], second_center[0]) + 0.1,+ max(first_center[1], second_center[1]) + 0.1,+ )+ )+ return connector is not None and any(_bbox_intersects(connector, table_bbox) for table_bbox in table_bboxes)+diff --git a/mineru/backend/flash/native_pdf/line_merging.py b/mineru/backend/flash/native_pdf/line_merging.pynew file mode 100644index 00000000..990ef0d7--- /dev/null+++ b/mineru/backend/flash/native_pdf/line_merging.py@@ -0,0 +1,692 @@+# Copyright (c) Opendatalab. All rights reserved.++"""提供同基线文本和拆分视觉行的几何合并。"""++from __future__ import annotations++import statistics+++from mineru.types import BBox++from .models import _LineItem+from .geometry import (+ _bbox_center_y,+ _bbox_intersects,+ _bbox_union_many,+ _rotate_bbox_to_upright,+)+from .native_text import (+ _fill_native_typography,+ _median_native_glyph_width,+)+from .line_layout import (+ _connection_crosses_table,+ _infer_text_lanes,+ _line_effective_height,+)+++def _merge_same_baseline_text_lines(+ lines: list[_LineItem],+ page_size: tuple[float, float],+ table_bboxes: list[BBox],+) -> list[_LineItem]:+ """在表格认领后合并同基线、同字体且水平邻近的正文 run。"""++ if len(lines) < 2:+ return list(lines)+ local_bboxes = [_rotate_bbox_to_upright(line.bbox, page_size, line.angle) for line in lines]+ parents = list(range(len(lines)))++ def find(index: int) -> int:+ """查找同行合并并查集的根节点。"""++ while parents[index] != index:+ parents[index] = parents[parents[index]]+ index = parents[index]+ return index++ def union(left_index: int, right_index: int) -> None:+ """合并两个满足同行条件的文本 run。"""++ left_root = find(left_index)+ right_root = find(right_index)+ if left_root != right_root:+ parents[right_root] = left_root++ for left_index, left_line in enumerate(lines):+ for right_index in range(left_index + 1, len(lines)):+ right_line = lines[right_index]+ if _can_merge_same_baseline_pair(+ left_line,+ local_bboxes[left_index],+ right_line,+ local_bboxes[right_index],+ table_bboxes,+ ):+ union(left_index, right_index)++ groups: dict[int, list[int]] = {}+ for index in range(len(lines)):+ groups.setdefault(find(index), []).append(index)++ output: list[_LineItem] = []+ for indices in groups.values():+ if len(indices) == 1:+ output.append(lines[indices[0]])+ continue+ indices.sort(key=lambda index: (local_bboxes[index][0], local_bboxes[index][1], lines[index].source_index))+ output.append(_merge_same_baseline_group(indices, lines, local_bboxes, page_size))+ output.sort(+ key=lambda line: (+ line.angle,+ _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[1],+ _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[0],+ line.source_index,+ )+ )+ return output+++def _merge_post_semantic_text_runs(+ lines: list[_LineItem],+ page_size: tuple[float, float],+ table_bboxes: list[BBox],+) -> list[_LineItem]:+ """在容器、公式和标题结束后合并紧贴同基线的普通混合字体 run。"""++ if len(lines) < 2:+ return list(lines)+ local_bboxes = [+ _rotate_bbox_to_upright(line.bbox, page_size, line.angle)+ for line in lines+ ]+ parents = list(range(len(lines)))++ def find(index: int) -> int:+ """查找后处理同行合并分量的根节点。"""++ while parents[index] != index:+ parents[index] = parents[parents[index]]+ index = parents[index]+ return index++ def union(first_index: int, second_index: int) -> None:+ """合并两个后处理同行分量。"""++ first_root = find(first_index)+ second_root = find(second_index)+ if first_root != second_root:+ parents[second_root] = first_root++ for first_index, first_line in enumerate(lines):+ if first_line.semantic_type is not None:+ continue+ first_bbox = local_bboxes[first_index]+ first_height = _line_effective_height(first_line, first_bbox)+ for second_index in range(first_index + 1, len(lines)):+ second_line = lines[second_index]+ if second_line.semantic_type is not None or first_line.angle != second_line.angle:+ continue+ if _connection_crosses_table(+ first_line.bbox,+ second_line.bbox,+ table_bboxes,+ ):+ continue+ second_bbox = local_bboxes[second_index]+ second_height = _line_effective_height(second_line, second_bbox)+ if _post_semantic_same_baseline_geometry(+ first_bbox,+ first_height,+ second_bbox,+ second_height,+ ):+ union(first_index, second_index)++ groups: dict[int, list[int]] = {}+ for index in range(len(lines)):+ groups.setdefault(find(index), []).append(index)+ output: list[_LineItem] = []+ for indices in groups.values():+ if len(indices) == 1:+ output.append(lines[indices[0]])+ continue+ indices.sort(+ key=lambda index: (+ local_bboxes[index][0],+ local_bboxes[index][1],+ lines[index].source_index,+ )+ )+ output.append(+ _merge_same_baseline_group(+ indices,+ lines,+ local_bboxes,+ page_size,+ )+ )+ output.sort(+ key=lambda line: (+ line.angle,+ _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[1],+ _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[0],+ line.source_index,+ )+ )+ return output+++def _post_semantic_same_baseline_geometry(+ first_bbox: BBox,+ first_height: float,+ second_bbox: BBox,+ second_height: float,+) -> bool:+ """放宽上下标字号差异,仅合并水平紧贴且垂直充分交叠的普通 run。"""++ pair_height = max(first_height, second_height)+ if min(first_height, second_height) <= 0 or pair_height / min(+ first_height,+ second_height,+ ) > 1.6:+ return False+ y_overlap = max(+ 0.0,+ min(first_bbox[3], second_bbox[3]) - max(first_bbox[1], second_bbox[1]),+ )+ shorter_bbox_height = max(+ 0.1,+ min(first_bbox[3] - first_bbox[1], second_bbox[3] - second_bbox[1]),+ )+ if y_overlap / shorter_bbox_height < 0.7:+ return False+ left_bbox, right_bbox = sorted((first_bbox, second_bbox), key=lambda bbox: bbox[0])+ horizontal_gap = right_bbox[0] - left_bbox[2]+ return -0.2 * pair_height <= horizontal_gap <= max(2.0, 0.35 * pair_height)+++def _can_merge_same_baseline_pair(+ first: _LineItem,+ first_bbox: BBox,+ second: _LineItem,+ second_bbox: BBox,+ table_bboxes: list[BBox],+) -> bool:+ """判断两个剩余文本 run 是否属于同一条物理基线。"""++ if first.angle != second.angle:+ return False+ if first.semantic_type != second.semantic_type:+ return False+ if first.visual_row_id == second.visual_row_id and (first.split_from_row or second.split_from_row):+ return False+ if _connection_crosses_table(first.bbox, second.bbox, table_bboxes):+ return False+ first_height = _line_effective_height(first, first_bbox)+ second_height = _line_effective_height(second, second_bbox)+ has_compatible_dominant_font = not (+ first.font_signature is None+ or second.font_signature is None+ or first.font_coverage < 0.75+ or second.font_coverage < 0.75+ or first.font_signature != second.font_signature+ )+ if has_compatible_dominant_font and _same_baseline_geometry(+ first_bbox,+ first_height,+ second_bbox,+ second_height,+ ):+ return True+ return _touching_same_baseline_geometry(+ first_bbox,+ first_height,+ second_bbox,+ second_height,+ )+++def _touching_same_baseline_geometry(+ first_bbox: BBox,+ first_height: float,+ second_bbox: BBox,+ second_height: float,+) -> bool:+ """为低字体覆盖率 run 提供严格的紧贴同基线几何兜底。"""++ pair_height = max(first_height, second_height)+ y_overlap = max(0.0, min(first_bbox[3], second_bbox[3]) - max(first_bbox[1], second_bbox[1]))+ smaller_bbox_height = max(+ 0.1,+ min(first_bbox[3] - first_bbox[1], second_bbox[3] - second_bbox[1]),+ )+ if y_overlap / smaller_bbox_height < 0.7:+ return False+ if abs(_bbox_center_y(first_bbox) - _bbox_center_y(second_bbox)) > 0.5 * pair_height:+ return False+ left_bbox, right_bbox = sorted((first_bbox, second_bbox), key=lambda bbox: bbox[0])+ signed_gap = right_bbox[0] - left_bbox[2]+ return -0.15 * pair_height <= signed_gap <= 0.75+++def _same_baseline_geometry(+ first_bbox: BBox,+ first_height: float,+ second_bbox: BBox,+ second_height: float,+ *,+ maximum_gap: float | None = None,+) -> bool:+ """仅依据行高、垂直交叠和水平净空判断两个局部 bbox 是否同基线相邻。"""++ pair_height = max(first_height, second_height)+ if min(first_height, second_height) <= 0 or pair_height / min(first_height, second_height) > 1.35:+ return False+ y_overlap = max(0.0, min(first_bbox[3], second_bbox[3]) - max(first_bbox[1], second_bbox[1]))+ shorter_bbox_height = max(+ 0.1,+ min(first_bbox[3] - first_bbox[1], second_bbox[3] - second_bbox[1]),+ )+ if y_overlap / shorter_bbox_height < 0.7 and abs(first_bbox[3] - second_bbox[3]) > 0.25 * pair_height:+ return False+ left_bbox, right_bbox = sorted((first_bbox, second_bbox), key=lambda bbox: bbox[0])+ signed_gap = right_bbox[0] - left_bbox[2]+ gap_limit = max(3.0, 0.75 * pair_height) if maximum_gap is None else maximum_gap+ return -0.25 * pair_height <= signed_gap <= gap_limit+++def _merge_same_baseline_group(+ indices: list[int],+ lines: list[_LineItem],+ local_bboxes: list[BBox],+ page_size: tuple[float, float],+) -> _LineItem:+ """按局部 x 顺序合并一个同基线分量,并保留全部字符与几何信息。"""++ members = [lines[index] for index in indices]+ content_parts = [members[0].text.strip()]+ for previous_index, current_index in zip(indices, indices[1:]):+ previous_bbox = local_bboxes[previous_index]+ current_bbox = local_bboxes[current_index]+ signed_gap = current_bbox[0] - previous_bbox[2]+ glyph_width = statistics.median(+ [+ width+ for member in (lines[previous_index], lines[current_index])+ if (width := _median_native_glyph_width(member, page_size)) is not None+ ]+ or [1.0]+ )+ separator = "" if signed_gap <= max(0.5, 0.25 * glyph_width) else " "+ content_parts.extend([separator, lines[current_index].text.strip()])++ merged = _LineItem(+ text="".join(content_parts).strip(),+ bbox=_bbox_union_many([member.bbox for member in members]),+ angle=members[0].angle,+ source_index=min(member.source_index for member in members),+ chars=[char for member in members for char in member.chars],+ visual_row_id=min(+ (member.visual_row_id for member in members if member.visual_row_id is not None),+ default=None,+ ),+ run_index=min(member.run_index for member in members),+ effective_height=statistics.median(member.effective_height for member in members),+ font_signature=members[0].font_signature,+ font_coverage=min(member.font_coverage for member in members),+ dominant_font_weight=statistics.median(+ member.dominant_font_weight+ for member in members+ if member.dominant_font_weight is not None+ )+ if any(member.dominant_font_weight is not None for member in members)+ else None,+ median_glyph_width=statistics.median(+ member.median_glyph_width+ for member in members+ if member.median_glyph_width is not None+ )+ if any(member.median_glyph_width is not None for member in members)+ else None,+ split_from_row=any(member.split_from_row for member in members),+ semantic_type=members[0].semantic_type,+ )+ if merged.chars:+ _fill_native_typography(merged, page_size)+ return merged+++def _join_formula_visual_row(+ row: list[tuple[_LineItem, BBox]],+ page_size: tuple[float, float],+) -> str:+ """将一个公式视觉行按局部 x 排序,并按字宽估计几何空格。"""++ ordered = sorted(row, key=lambda item: (item[1][0], item[1][1], item[0].source_index))+ if not ordered:+ return ""+ parts = [ordered[0][0].text.strip()]+ for previous, current in zip(ordered, ordered[1:]):+ previous_line, previous_bbox = previous+ current_line, current_bbox = current+ gap = current_bbox[0] - previous_bbox[2]+ pair_height = max(+ _line_effective_height(previous_line, previous_bbox),+ _line_effective_height(current_line, current_bbox),+ )+ glyph_widths = [+ width+ for line in (previous_line, current_line)+ if (width := _median_native_glyph_width(line, page_size)) is not None+ ]+ glyph_width = statistics.median(glyph_widths) if glyph_widths else max(1.0, 0.5 * pair_height)+ if gap <= max(0.5, 0.2 * pair_height):+ separator = ""+ else:+ separator = " " * max(1, min(8, int(round(gap / glyph_width))))+ parts.extend([separator, current_line.text.strip()])+ return "".join(parts).strip()+++def _restore_dense_split_visual_rows(+ lines: list[_LineItem],+ page_size: tuple[float, float],+ table_bboxes: list[BBox],+) -> list[_LineItem]:+ """在公式认领后恢复同一栏带内被均匀大空格拆开的密集原生视觉行。"""++ if len(lines) < 3:+ return list(lines)+ lane_keys: dict[int, tuple[int, int]] = {}+ for angle in sorted({line.angle for line in lines}):+ line_geometry = [+ (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))+ for line in lines+ if line.angle == angle+ ]+ if not line_geometry:+ continue+ median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in line_geometry)+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]+ lanes = _infer_text_lanes(line_geometry, local_page_width, median_height)+ for lane_index, lane in enumerate(lanes):+ if lane.is_span:+ continue+ for line, _bbox in lane.lines:+ lane_keys[line.source_index] = (angle, lane_index)++ row_groups: dict[tuple[int, int], list[_LineItem]] = {}+ for line in lines:+ if line.visual_row_id is None:+ continue+ row_groups.setdefault((line.angle, line.visual_row_id), []).append(line)++ consumed_source_indices: set[int] = set()+ restored_lines: list[_LineItem] = []+ for members in row_groups.values():+ if not _can_restore_dense_split_visual_row(+ members,+ page_size,+ table_bboxes,+ lane_keys,+ ):+ continue+ restored_lines.append(_merge_dense_split_visual_row(members, page_size))+ consumed_source_indices.update(member.source_index for member in members)++ output = [line for line in lines if line.source_index not in consumed_source_indices]+ output.extend(restored_lines)+ output.sort(+ key=lambda line: (+ line.angle,+ _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[1],+ _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[0],+ line.source_index,+ )+ )+ return output+++def _merge_title_resolved_visual_rows(+ lines: list[_LineItem],+ page_size: tuple[float, float],+) -> list[_LineItem]:+ """在标题判定后合并同行标题或已降级的混合字体正文 run。"""++ row_groups: dict[tuple[int, int], list[_LineItem]] = {}+ for line in lines:+ if line.visual_row_id is None:+ continue+ row_groups.setdefault((line.angle, line.visual_row_id), []).append(line)++ consumed_source_indices: set[int] = set()+ merged_rows: list[_LineItem] = []+ for members in row_groups.values():+ if len(members) < 2 or not all(member.split_from_row for member in members):+ continue+ semantic_types = {member.semantic_type for member in members}+ if len(semantic_types) != 1:+ continue+ semantic_type = next(iter(semantic_types))+ font_signatures = {member.font_signature for member in members}+ dense_same_font_text = _is_dense_same_font_two_run_row(+ members,+ page_size,+ )+ if semantic_type != "paragraph_title" and not (+ semantic_type is None+ and (len(font_signatures) > 1 or dense_same_font_text)+ ):+ continue+ local_geometry = [+ (+ member,+ _rotate_bbox_to_upright(member.bbox, page_size, member.angle),+ )+ for member in members+ ]+ local_geometry.sort(key=lambda item: (item[1][0], item[1][1], item[0].source_index))+ if any(+ not _same_baseline_geometry(+ previous[1],+ _line_effective_height(*previous),+ current[1],+ _line_effective_height(*current),+ maximum_gap=3.0+ * max(+ _line_effective_height(*previous),+ _line_effective_height(*current),+ ),+ )+ for previous, current in zip(local_geometry, local_geometry[1:])+ ):+ continue+ merged_rows.append(_merge_dense_split_visual_row(members, page_size))+ consumed_source_indices.update(member.source_index for member in members)++ output = [+ line for line in lines if line.source_index not in consumed_source_indices+ ]+ output.extend(merged_rows)+ output.sort(+ key=lambda line: (+ line.angle,+ _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[1],+ _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[0],+ line.source_index,+ )+ )+ return output+++def _is_dense_same_font_two_run_row(+ members: list[_LineItem],+ page_size: tuple[float, float],+) -> bool:+ """检查两个普通文本 run 是否为同字体且占用充分的完整视觉行。"""++ if (+ len(members) != 2+ or not all(member.split_from_row for member in members)+ or any(member.semantic_type is not None for member in members)+ or any(member.font_signature is None for member in members)+ or any(member.font_coverage < 0.75 for member in members)+ ):+ return False+ ordered = sorted(members, key=lambda member: member.run_index)+ if [member.run_index for member in ordered] != [0, 1]:+ return False+ if ordered[0].font_signature != ordered[1].font_signature:+ return False++ local_geometry = [+ (+ member,+ _rotate_bbox_to_upright(member.bbox, page_size, member.angle),+ )+ for member in ordered+ ]+ local_geometry.sort(+ key=lambda item: (item[1][0], item[1][1], item[0].source_index)+ )+ first, second = local_geometry+ pair_height = max(+ _line_effective_height(*first),+ _line_effective_height(*second),+ )+ if not _same_baseline_geometry(+ first[1],+ _line_effective_height(*first),+ second[1],+ _line_effective_height(*second),+ maximum_gap=3.0 * pair_height,+ ):+ return False++ union_bbox = _bbox_union_many([bbox for _member, bbox in local_geometry])+ occupied_width = sum(+ bbox[2] - bbox[0] for _member, bbox in local_geometry+ )+ return occupied_width / max(0.1, union_bbox[2] - union_bbox[0]) >= 0.85+++def _can_restore_dense_split_visual_row(+ members: list[_LineItem],+ page_size: tuple[float, float],+ table_bboxes: list[BBox],+ lane_keys: dict[int, tuple[int, int]],+) -> bool:+ """检查 hard-split run 是否构成同栏、同字体且占用充分的完整视觉行。"""++ if len(members) < 3 or not all(member.split_from_row for member in members):+ return False+ if len({member.semantic_type for member in members}) != 1:+ return False+ ordered = sorted(members, key=lambda member: member.run_index)+ if [member.run_index for member in ordered] != list(range(len(ordered))):+ return False+ member_lane_keys = {lane_keys.get(member.source_index) for member in ordered}+ if None in member_lane_keys or len(member_lane_keys) != 1:+ return False+ font_signatures = {member.font_signature for member in ordered}+ if len(font_signatures) != 1:+ return False+ if any(+ _bbox_intersects(member.bbox, table_bbox)+ for member in ordered+ for table_bbox in table_bboxes+ ):+ return False++ local_geometry = [+ (+ member,+ _rotate_bbox_to_upright(member.bbox, page_size, member.angle),+ )+ for member in ordered+ ]+ local_geometry.sort(key=lambda item: (item[1][0], item[1][1], item[0].source_index))+ heights = [_line_effective_height(member, bbox) for member, bbox in local_geometry]+ median_height = statistics.median(heights)+ glyph_widths = [+ width+ for member, _bbox in local_geometry+ if (width := _median_native_glyph_width(member, page_size)) is not None+ ]+ median_glyph_width = statistics.median(glyph_widths) if glyph_widths else 0.0+ gap_limit = max(12.0, 1.75 * median_height, 3.0 * median_glyph_width)+ for previous, current in zip(local_geometry, local_geometry[1:]):+ if not _same_baseline_geometry(+ previous[1],+ _line_effective_height(*previous),+ current[1],+ _line_effective_height(*current),+ maximum_gap=gap_limit,+ ):+ return False++ union_bbox = _bbox_union_many([bbox for _member, bbox in local_geometry])+ occupied_width = sum(bbox[2] - bbox[0] for _member, bbox in local_geometry)+ return occupied_width / max(0.1, union_bbox[2] - union_bbox[0]) >= 0.65+++def _merge_dense_split_visual_row(+ members: list[_LineItem],+ page_size: tuple[float, float],+) -> _LineItem:+ """按局部 x 顺序恢复密集视觉行,正净空使用单空格,重叠片段直接连接。"""++ ordered_geometry = sorted(+ (+ (+ member,+ _rotate_bbox_to_upright(member.bbox, page_size, member.angle),+ )+ for member in members+ ),+ key=lambda item: (item[1][0], item[1][1], item[0].source_index),+ )+ content_parts = [ordered_geometry[0][0].text.strip()]+ for previous, current in zip(ordered_geometry, ordered_geometry[1:]):+ separator = "" if current[1][0] <= previous[1][2] else " "+ content_parts.extend([separator, current[0].text.strip()])++ ordered_members = [member for member, _bbox in ordered_geometry]+ merged = _LineItem(+ text="".join(content_parts).strip(),+ bbox=_bbox_union_many([member.bbox for member in ordered_members]),+ angle=ordered_members[0].angle,+ source_index=min(member.source_index for member in ordered_members),+ chars=[char for member in ordered_members for char in member.chars],+ visual_row_id=ordered_members[0].visual_row_id,+ run_index=0,+ effective_height=statistics.median(+ _line_effective_height(member, bbox)+ for member, bbox in ordered_geometry+ ),+ font_signature=ordered_members[0].font_signature,+ font_coverage=min(member.font_coverage for member in ordered_members),+ dominant_font_weight=statistics.median(+ member.dominant_font_weight+ for member in ordered_members+ if member.dominant_font_weight is not None+ )+ if any(member.dominant_font_weight is not None for member in ordered_members)+ else None,+ median_glyph_width=statistics.median(+ member.median_glyph_width+ for member in ordered_members+ if member.median_glyph_width is not None+ )+ if any(member.median_glyph_width is not None for member in ordered_members)+ else None,+ split_from_row=False,+ semantic_type=ordered_members[0].semantic_type,+ )+ if merged.chars:+ _fill_native_typography(merged, page_size)+ return merged+diff --git a/mineru/backend/flash/native_pdf/models.py b/mineru/backend/flash/native_pdf/models.pynew file mode 100644index 00000000..496cf66c--- /dev/null+++ b/mineru/backend/flash/native_pdf/models.py@@ -0,0 +1,158 @@+# Copyright (c) Opendatalab. All rights reserved.++"""Flash 原生 PDF 提取使用的内部数据模型。"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any, Literal++from pdftext.schema import Char++from mineru.types import BBox+++@dataclass(slots=True)+class _LineItem:+ """保存单个可视文本行及其原始几何信息。"""++ text: str+ bbox: BBox+ angle: int+ source_index: int+ chars: list[Char] = field(default_factory=list)+ visual_row_id: int | None = None+ run_index: int = 0+ effective_height: float = 0.0+ font_signature: tuple[str, int] | None = None+ font_coverage: float = 0.0+ dominant_font_weight: float | None = None+ median_glyph_width: float | None = None+ split_from_row: bool = False+ semantic_type: str | None = None+++@dataclass(slots=True)+class _Fragment:+ """保存表格规则使用的单元文本片段。"""++ text: str+ bbox: BBox+ local_bbox: BBox+ line_index: int+ visual_row_id: int | None = None+++@dataclass(slots=True)+class _VisualRow:+ """保存同一局部水平带内的表格片段。"""++ fragments: list[_Fragment]+ center_y: float+ bbox: BBox+ visual_row_id: int | None = None+++@dataclass(slots=True)+class _AxisLine:+ """保存 PDF 路径中的横竖线。"""++ bbox: BBox+ width: float+ orientation: Literal["horizontal", "vertical"]+++@dataclass(slots=True)+class _LocalAxisLine:+ """保存转入当前文本方向后的横竖线。"""++ bbox: BBox+ original_bbox: BBox+ orientation: Literal["horizontal", "vertical"]+ width: float+++@dataclass(slots=True)+class _TableCandidate:+ """保存已通过三横线与文本分布校验的表格候选。"""++ bbox: BBox+ local_bbox: BBox+ angle: int+ score: float+ core_bbox: BBox | None = None+ line_indices: set[int] = field(default_factory=set)+++@dataclass(slots=True)+class _GraphicCandidate:+ """保存由紧凑绘图线组件形成的图形文本容器候选。"""++ core_bbox: BBox+ lane_index: int+ line_indices: set[int] = field(default_factory=set)+++@dataclass(slots=True)+class _TextLane:+ """保存同一文本方向下的局部栏带与已归属文本行。"""++ left: float+ right: float+ lines: list[tuple[_LineItem, BBox]] = field(default_factory=list)+ is_span: bool = False+++@dataclass(slots=True)+class _FormulaAnchor:+ """保存公式右缘锚点及其是否落在正文密集区下方。"""++ line: _LineItem+ bbox: BBox+ detached_below_body: bool = False+++@dataclass(slots=True)+class _PageSource:+ """保存单页原生文本分析所需的文本、字符、绘图线和视觉容器。"""++ page_size: tuple[float, float]+ lines: list[_LineItem]+ chars: list[Char]+ drawing_lines: list[_AxisLine]+ image_bboxes: list[BBox] = field(default_factory=list)+ form_bboxes: list[BBox] = field(default_factory=list)+++@dataclass(slots=True)+class _PreparedPage:+ """保存容器认领完成后、等待跨页与文本类型判定的轻量页面。"""++ page_size: tuple[float, float]+ remaining_lines: list[_LineItem]+ table_bboxes: list[BBox]+ drawing_lines: list[_AxisLine]+ fixed_blocks: list[dict[str, Any]]+ page_footnote_groups: list[set[int]] = field(default_factory=list)+++@dataclass(slots=True)+class _MarginalCandidate:+ """保存页眉页脚带中的单行候选及其正向归一化几何。"""++ page_index: int+ line: _LineItem+ local_bbox: BBox+ local_page_size: tuple[float, float]+ region: Literal["header", "footer", "side"]+++@dataclass(slots=True)+class _LaneBodyProfile:+ """保存标题判定使用的栏带正文排版基线,不包含文本内容特征。"""++ body_height: float+ body_font: tuple[str, int] | None+ body_weight: float | None+ regular_gap: float+ style_support: dict[tuple[str, int], float]diff --git a/mineru/backend/flash/native_pdf/native_text.py b/mineru/backend/flash/native_pdf/native_text.pynew file mode 100644index 00000000..9bab5fb3--- /dev/null+++ b/mineru/backend/flash/native_pdf/native_text.py@@ -0,0 +1,401 @@+# Copyright (c) Opendatalab. All rights reserved.++"""将 PDF 原生字符重建为带排版信息的视觉文本行。"""++from __future__ import annotations++import math+import re+import statistics+from typing import Any, Literal, Sequence++from pdftext.schema import Char++from mineru.types import BBox+from mineru.utils.pdf_document import PDFDocument++from .models import (+ _AxisLine,+ _LineItem,+)+from .geometry import (+ _bbox_center_y,+ _bbox_union,+ _bbox_union_many,+ _clip_bbox,+ _coerce_bbox,+ _horizontal_bbox_gap,+ _rotate_bbox_to_upright,+)+++_PDF_CONTROL_CHAR_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")+++def _build_native_line_items(+ pdf_lines: Sequence[dict[str, Any]],+ page_size: tuple[float, float],+ *,+ page_rotation: int = 0,+) -> list[_LineItem]:+ """将 pdftext 粗行按字符间隙精修成 Flash 视觉 run。"""++ items: list[_LineItem] = []+ for visual_row_id, pdf_line in enumerate(pdf_lines):+ bbox = _clip_bbox(_coerce_bbox(pdf_line.get("bbox")), page_size)+ if bbox is None:+ continue+ spans = pdf_line.get("spans") or []+ chars = [char for span in spans for char in (span.get("chars") or []) if isinstance(char, dict)]+ coarse_item = _LineItem(+ text="".join(str(span.get("text") or "") for span in spans),+ bbox=bbox,+ angle=(_normalize_pdftext_angle(pdf_line.get("rotation")) + int(page_rotation or 0)) % 360,+ source_index=-1,+ chars=chars,+ visual_row_id=visual_row_id,+ )+ items.extend(_split_native_visual_runs(coarse_item, page_size))++ merged_items = _merge_native_inline_scripts(items, page_size)+ for source_index, item in enumerate(merged_items):+ # source_index 必须在页内唯一,表格投影和失败回滚都依赖该精确成员标识。+ item.source_index = source_index+ return merged_items+++def _split_native_visual_runs(+ line: _LineItem,+ page_size: tuple[float, float],+) -> list[_LineItem]:+ """保留字符源顺序与空白信息,并将一个 pdftext 粗行拆成远距视觉 run。"""++ tokens: list[tuple[Char, str, BBox | None, BBox | None]] = []+ for char in line.chars:+ raw_char = str(char.get("char") or "")+ if raw_char in {"\r", "\n"}:+ continue+ bbox = _clip_bbox(_coerce_bbox(char.get("bbox")), page_size)+ local_bbox = _rotate_bbox_to_upright(bbox, page_size, line.angle) if bbox is not None else None+ tokens.append((char, raw_char, bbox, local_bbox))++ visible_indices = [+ index+ for index, (_char, raw_char, _bbox, local_bbox) in enumerate(tokens)+ if raw_char.isprintable() and not raw_char.isspace() and local_bbox is not None+ ]+ if not visible_indices:+ text = _normalize_native_run_text(line.text)+ if not text:+ return []+ local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, line.angle)+ line.text = text+ line.effective_height = max(0.1, local_bbox[3] - local_bbox[1])+ return [line]++ glyph_widths = [+ max(0.1, tokens[index][3][2] - tokens[index][3][0]) # type: ignore[index]+ for index in visible_indices+ ]+ median_glyph_width = statistics.median(glyph_widths)+ local_page_width = page_size[1] if line.angle in {90, 270} else page_size[0]+ hard_gap_threshold = max(15.0, 3.0 * median_glyph_width, 0.02 * local_page_width)+ adjacent_gaps: list[float] = []+ for previous, current in zip(visible_indices, visible_indices[1:]):+ previous_bbox = tokens[previous][3]+ current_bbox = tokens[current][3]+ if previous_bbox is None or current_bbox is None:+ continue+ gap = _horizontal_bbox_gap(previous_bbox, current_bbox)+ if gap < hard_gap_threshold:+ adjacent_gaps.append(gap)+ # 少于三个相邻样本无法可靠代表“常规”字距;零间隙也是真实的紧排字距,+ # 必须纳入统计,避免唯一的 15pt cell gap 反过来抬高软拆阈值。+ median_regular_gap = statistics.median(adjacent_gaps) if len(adjacent_gaps) >= 3 else 0.0++ split_indices: list[int] = []+ for previous, current in zip(visible_indices, visible_indices[1:]):+ previous_bbox = tokens[previous][3]+ current_bbox = tokens[current][3]+ if previous_bbox is None or current_bbox is None:+ continue+ gap = _horizontal_bbox_gap(previous_bbox, current_bbox)+ has_source_whitespace = any(tokens[index][1].isspace() for index in range(previous + 1, current))+ soft_gap_threshold = max(+ 8.0,+ 2.2 * median_glyph_width,+ 3.0 * median_regular_gap,+ )+ if gap >= hard_gap_threshold or (has_source_whitespace and gap >= soft_gap_threshold):+ split_indices.append(current)++ ranges: list[tuple[int, int]] = []+ start = 0+ for split_index in split_indices:+ ranges.append((start, split_index))+ start = split_index+ ranges.append((start, len(tokens)))++ output: list[_LineItem] = []+ for run_index, (start, end) in enumerate(ranges):+ run_tokens = tokens[start:end]+ run_text = _normalize_native_run_text("".join(token[1] for token in run_tokens))+ run_bboxes = [+ token[2]+ for token in run_tokens+ if token[2] is not None and token[1].isprintable() and not token[1].isspace()+ ]+ if not run_text or not run_bboxes:+ continue+ run_chars = [token[0] for token in run_tokens]+ run_item = _LineItem(+ text=run_text,+ bbox=_bbox_union_many(run_bboxes),+ angle=line.angle,+ source_index=-1,+ chars=run_chars,+ visual_row_id=line.visual_row_id,+ run_index=run_index,+ split_from_row=len(ranges) > 1,+ )+ _fill_native_typography(run_item, page_size)+ output.append(run_item)+ return output+++def _normalize_native_run_text(text: str) -> str:+ """清理原生 run 文本,并把字母后的 PDF 软断词标记转换成 ASCII hyphen。"""++ normalized = text.replace("\r\n", "\n").replace("\r", "\n")+ normalized = re.sub(r"(?<=[A-Za-z])\x02(?=\s*$)", "-", normalized)+ normalized = _sanitize_pdf_control_text(normalized, preserve_newlines=False)+ normalized = re.sub(r"[\t\f\v ]+", " ", normalized)+ return normalized.strip()+++def _sanitize_pdf_control_text(text: str, *, preserve_newlines: bool) -> str:+ """删除 PDF 字体编码残留控制字符,并按调用场景决定是否保留物理换行。"""++ normalized = str(text or "").replace("\r\n", "\n").replace("\r", "\n")+ normalized = re.sub(r"(?<=[A-Za-z])\x02(?=[\t ]*(?:\n|$))", "-", normalized)+ normalized = normalized.replace("\t", " ")+ if not preserve_newlines:+ normalized = normalized.replace("\n", "")+ return _PDF_CONTROL_CHAR_RE.sub("", normalized)+++def _fill_native_typography(line: _LineItem, page_size: tuple[float, float]) -> None:+ """使用非空字符 bbox 高度和 dominant font 填充原生行排版特征。"""++ heights: list[float] = []+ glyph_widths: list[float] = []+ font_counts: dict[tuple[str, int], int] = {}+ font_weights: dict[tuple[str, int], list[float]] = {}+ valid_font_chars = 0+ for char in line.chars:+ raw_char = str(char.get("char") or "")+ if not raw_char.isprintable() or raw_char.isspace():+ continue+ bbox = _clip_bbox(_coerce_bbox(char.get("bbox")), page_size)+ if bbox is None:+ continue+ local_bbox = _rotate_bbox_to_upright(bbox, page_size, line.angle)+ heights.append(max(0.1, local_bbox[3] - local_bbox[1]))+ glyph_widths.append(max(0.1, local_bbox[2] - local_bbox[0]))+ font = char.get("font") or {}+ font_name = str(font.get("name") or "")+ if not font_name:+ continue+ try:+ font_flags = int(font.get("flags") or 0)+ except (TypeError, ValueError):+ font_flags = 0+ signature = (font_name, font_flags)+ font_counts[signature] = font_counts.get(signature, 0) + 1+ try:+ font_weight = float(font.get("weight"))+ except (TypeError, ValueError):+ font_weight = math.nan+ if math.isfinite(font_weight):+ font_weights.setdefault(signature, []).append(font_weight)+ valid_font_chars += 1++ local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, line.angle)+ line.effective_height = statistics.median(heights) if heights else max(0.1, local_bbox[3] - local_bbox[1])+ line.median_glyph_width = statistics.median(glyph_widths) if glyph_widths else None+ if font_counts and valid_font_chars:+ line.font_signature, dominant_count = max(font_counts.items(), key=lambda item: item[1])+ line.font_coverage = dominant_count / valid_font_chars+ dominant_weights = font_weights.get(line.font_signature, [])+ line.dominant_font_weight = statistics.median(dominant_weights) if dominant_weights else None+ else:+ line.font_signature = None+ line.font_coverage = 0.0+ line.dominant_font_weight = None+++def _merge_native_inline_scripts(+ lines: list[_LineItem],+ page_size: tuple[float, float],+) -> list[_LineItem]:+ """以 mutual-nearest 规则把跨粗行的小字号前后置标记合入主体视觉行。"""++ candidates: list[tuple[float, int, int, Literal["prefix", "suffix"]]] = []+ for small_index, small in enumerate(lines):+ compact_text = "".join(char for char in small.text if not char.isspace())+ if not compact_text:+ continue+ small_local_bbox = _rotate_bbox_to_upright(small.bbox, page_size, small.angle)+ for base_index, base in enumerate(lines):+ if small_index == base_index or small.angle != base.angle or small.visual_row_id == base.visual_row_id:+ continue+ if small.effective_height <= 0 or base.effective_height <= 0:+ continue+ height_ratio = small.effective_height / base.effective_height+ if not 0.35 <= height_ratio <= 0.8:+ continue+ if len(compact_text) > 8 and small_local_bbox[2] - small_local_bbox[0] > 3.0 * base.effective_height:+ continue+ base_local_bbox = _rotate_bbox_to_upright(base.bbox, page_size, base.angle)+ vertical_overlap = max(+ 0.0,+ min(small_local_bbox[3], base_local_bbox[3]) - max(small_local_bbox[1], base_local_bbox[1]),+ )+ small_height = max(0.1, small_local_bbox[3] - small_local_bbox[1])+ overlap_ratio = vertical_overlap / small_height+ if overlap_ratio < 0.5:+ continue+ center_offset = abs(_bbox_center_y(small_local_bbox) - _bbox_center_y(base_local_bbox))+ if center_offset < max(0.5, 0.12 * base.effective_height):+ # 同基线居中的小字号文本更可能是表格相邻 cell,而不是上下标。+ continue+ gap_limit = max(1.5, 0.35 * base.effective_height)+ edge_options: list[tuple[float, Literal["prefix", "suffix"], float]] = []+ for position, gap in (+ ("prefix", base_local_bbox[0] - small_local_bbox[2]),+ ("suffix", small_local_bbox[0] - base_local_bbox[2]),+ ):+ if -0.35 * base.effective_height <= gap <= gap_limit:+ edge_options.append((abs(gap), position, gap))+ if not edge_options:+ continue+ _edge_distance, position, gap = min(edge_options, key=lambda item: item[0])++ outside_offset = max(+ base_local_bbox[1] - small_local_bbox[1],+ small_local_bbox[3] - base_local_bbox[3],+ )+ tightly_attached = abs(gap) <= max(1.0, 0.1 * base.effective_height)+ if outside_offset < max(0.5, 0.08 * base.effective_height) and not tightly_attached:+ # 紧贴边缘的小字号上下标可能完全落入高字形 bbox;其余内嵌小字仍按普通 cell 排除。+ continue+ metric = abs(gap) + (1.0 - overlap_ratio) * base.effective_height+ candidates.append((metric, small_index, base_index, position))++ best_base_for_small: dict[int, tuple[float, int, Literal["prefix", "suffix"]]] = {}+ best_small_for_base: dict[tuple[int, str], tuple[float, int]] = {}+ for metric, small_index, base_index, position in candidates:+ if small_index not in best_base_for_small or metric < best_base_for_small[small_index][0]:+ best_base_for_small[small_index] = (metric, base_index, position)+ base_key = (base_index, position)+ if base_key not in best_small_for_base or metric < best_small_for_base[base_key][0]:+ best_small_for_base[base_key] = (metric, small_index)++ matches: dict[int, dict[str, int]] = {}+ for small_index, (_metric, base_index, position) in best_base_for_small.items():+ if best_small_for_base.get((base_index, position), (math.inf, -1))[1] == small_index:+ matches.setdefault(base_index, {})[position] = small_index++ consumed_small_indices = {small_index for positions in matches.values() for small_index in positions.values()}+ merged_base_indices: set[int] = set()++ def merge_children(base_index: int, visiting: set[int]) -> None:+ """先合并更小的依赖标记,再把当前完整节点递归合入更大的主体行。"""++ if base_index in merged_base_indices or base_index in visiting:+ return+ visiting.add(base_index)+ positions = matches.get(base_index, {})+ for child_index in positions.values():+ merge_children(child_index, visiting)+ base = lines[base_index]+ merged_bbox = base.bbox+ merged_chars = list(base.chars)+ if "prefix" in positions:+ prefix_index = positions["prefix"]+ prefix = lines[prefix_index]+ base.text = f"{prefix.text.strip()} {base.text.lstrip()}"+ merged_bbox = _bbox_union(merged_bbox, prefix.bbox)+ merged_chars = [*prefix.chars, *merged_chars]+ base.split_from_row = base.split_from_row or prefix.split_from_row+ if "suffix" in positions:+ suffix_index = positions["suffix"]+ suffix = lines[suffix_index]+ base.text = f"{base.text.rstrip()}{suffix.text.strip()}"+ merged_bbox = _bbox_union(merged_bbox, suffix.bbox)+ merged_chars.extend(suffix.chars)+ base.split_from_row = base.split_from_row or suffix.split_from_row+ base.bbox = merged_bbox+ base.chars = merged_chars+ _fill_native_typography(base, page_size)+ visiting.remove(base_index)+ merged_base_indices.add(base_index)++ # 从最终不会被消费的根主体开始,确保 small -> medium -> large 链不会丢失最小节点。+ root_base_indices = [base_index for base_index in matches if base_index not in consumed_small_indices]+ for base_index in root_base_indices:+ merge_children(base_index, set())+ for base_index in matches:+ merge_children(base_index, set())++ output = [line for index, line in enumerate(lines) if index not in consumed_small_indices]+ output.sort(key=lambda item: (item.visual_row_id if item.visual_row_id is not None else math.inf, item.run_index))+ return output+++def _normalize_pdftext_angle(value: Any) -> int:+ """将 pdftext 弧度方向就近归一到四个标准角度。"""++ try:+ angle_radians = float(value or 0.0)+ except (TypeError, ValueError):+ return 0+ angle_degrees = math.degrees(angle_radians)+ normalized = int(round(angle_degrees / 90.0) * 90) % 360+ return normalized if normalized in {0, 90, 180, 270} else 0+++def _get_pdf_drawing_lines(pdf_doc: PDFDocument, page_idx: int) -> list[_AxisLine]:+ """读取 PDFDocument 的公共绘图线结果,并隔离具体 PDFium 类型。"""++ output: list[_AxisLine] = []+ for drawing_line in pdf_doc.get_page_drawing_lines(page_idx):+ bbox = _coerce_bbox(drawing_line.bbox)+ if bbox is None:+ continue+ output.append(+ _AxisLine(+ bbox=bbox,+ width=max(0.0, float(drawing_line.width)),+ orientation=drawing_line.orientation,+ )+ )+ return output+++def _median_native_glyph_width(line: _LineItem, page_size: tuple[float, float]) -> float | None:+ """返回单个原生 run 的可见字符中位宽度,缺少字符时返回空。"""++ if line.median_glyph_width is not None:+ return line.median_glyph_width+ widths: list[float] = []+ for char in line.chars:+ raw_char = str(char.get("char") or "")+ bbox = _clip_bbox(_coerce_bbox(char.get("bbox")), page_size)+ if not raw_char.isprintable() or raw_char.isspace() or bbox is None:+ continue+ local_bbox = _rotate_bbox_to_upright(bbox, page_size, line.angle)+ widths.append(max(0.1, local_bbox[2] - local_bbox[0]))+ line.median_glyph_width = statistics.median(widths) if widths else None+ return line.median_glyph_width+diff --git a/mineru/backend/flash/native_pdf/pipeline.py b/mineru/backend/flash/native_pdf/pipeline.pynew file mode 100644index 00000000..6ae07b26--- /dev/null+++ b/mineru/backend/flash/native_pdf/pipeline.py@@ -0,0 +1,309 @@+# Copyright (c) Opendatalab. All rights reserved.++"""编排 Flash 原生 PDF 的页面准备、语义处理和输出归一化。"""++from __future__ import annotations++from typing import Any+++from mineru.backend.utils.xycut_pp_sorter import sort_entries+from mineru.utils.pdf_document import PDFDocument, get_lines_from_chars++from .models import (+ _LineItem,+ _PageSource,+ _PreparedPage,+)+from .geometry import (+ _bbox_overlap_in_smaller,+ _bbox_union_many,+ _clip_bbox,+ _coerce_bbox,+ _normalize_bbox_to_thousandths,+ _rotate_bbox_to_upright,+)+from .native_text import (+ _build_native_line_items,+ _get_pdf_drawing_lines,+ _median_native_glyph_width,+ _sanitize_pdf_control_text,+)+from .line_merging import (+ _merge_post_semantic_text_runs,+ _merge_same_baseline_text_lines,+ _merge_title_resolved_visual_rows,+ _restore_dense_split_visual_rows,+)+from .tables import (+ _detect_table_candidates,+ _materialize_table_blocks,+)+from .graphics import (+ _IMAGE_CONTAINER_OVERLAP_THRESHOLD,+ _build_form_image_blocks,+ _build_graphic_like_blocks,+ _build_raster_image_blocks,+ _form_supersedes_nested_bbox,+ _select_form_image_bboxes,+)+from .formulas import _build_formula_like_blocks+from .auxiliary_text import (+ _classify_page_auxiliary_text,+ _classify_repeated_page_marginals,+)+from .titles import _classify_page_titles+from .text_blocks import _build_text_blocks+++_TEXT_SEMANTIC_TYPES = {+ "doc_title",+ "paragraph_title",+ "header",+ "footer",+ "page_number",+ "page_footnote",+ "aside_text",+}+++_OUTPUT_BLOCK_TYPES = {"text", "table", "image", "equation"} | _TEXT_SEMANTIC_TYPES+++def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]:+ """逐页读取数字 PDF,并在轻量页面上完成跨页文本类型判定。"""++ prepared_pages: list[_PreparedPage] = []+ for page_idx in range(pdf_doc.page_count):+ page_size = pdf_doc.page_size(page_idx)+ chars = pdf_doc.get_page_chars(page_idx)+ lines = _build_native_line_items(+ get_lines_from_chars(chars),+ page_size,+ page_rotation=pdf_doc.page_rotation(page_idx),+ )+ drawing_lines = _get_pdf_drawing_lines(pdf_doc, page_idx)+ source = _PageSource(+ page_size=page_size,+ lines=lines,+ chars=chars,+ drawing_lines=drawing_lines,+ image_bboxes=pdf_doc.get_page_image_bboxes(page_idx),+ form_bboxes=pdf_doc.get_page_form_bboxes(page_idx),+ )+ prepared_pages.append(_prepare_page_source(source))++ _classify_repeated_page_marginals(prepared_pages)+ return [+ _finalize_prepared_page(prepared, page_index)+ for page_index, prepared in enumerate(prepared_pages)+ ]+++def _prepare_page_source(source: _PageSource) -> _PreparedPage:+ """先认领视觉容器,再标注辅助文本并留下可跨页比较的轻量文本行。"""++ form_bboxes = _select_form_image_bboxes(source)+ candidates = [+ candidate+ for candidate in _detect_table_candidates(source)+ if not any(+ _form_supersedes_nested_bbox(form_bbox, candidate.bbox)+ for form_bbox in form_bboxes+ )+ ]+ table_blocks, claimed_line_indices = _materialize_table_blocks(+ source,+ candidates,+ )+ table_bboxes = [block["bbox"] for block in table_blocks]+ active_form_bboxes = [+ form_bbox+ for form_bbox in form_bboxes+ if not any(+ _bbox_overlap_in_smaller(form_bbox, table_bbox)+ >= _IMAGE_CONTAINER_OVERLAP_THRESHOLD+ for table_bbox in table_bboxes+ )+ ]+ form_image_blocks, claimed_form_line_indices = _build_form_image_blocks(+ source,+ active_form_bboxes,+ claimed_line_indices,+ )+ graphic_blocks, claimed_graphic_line_indices = _build_graphic_like_blocks(+ source,+ table_bboxes + active_form_bboxes,+ claimed_line_indices | claimed_form_line_indices,+ )+ raster_image_blocks, claimed_raster_line_indices = _build_raster_image_blocks(+ source,+ table_blocks + form_image_blocks + graphic_blocks,+ claimed_line_indices | claimed_form_line_indices | claimed_graphic_line_indices,+ )+ claimed_line_indices = (+ claimed_line_indices+ | claimed_form_line_indices+ | claimed_graphic_line_indices+ | claimed_raster_line_indices+ )+ remaining_lines = _merge_same_baseline_text_lines(+ [line for line in source.lines if line.source_index not in claimed_line_indices],+ source.page_size,+ table_bboxes,+ )+ _compact_prepared_lines(remaining_lines, source.page_size)+ prepared = _PreparedPage(+ page_size=source.page_size,+ remaining_lines=remaining_lines,+ table_bboxes=table_bboxes,+ drawing_lines=source.drawing_lines,+ fixed_blocks=table_blocks + form_image_blocks + graphic_blocks + raster_image_blocks,+ )+ _classify_page_auxiliary_text(prepared)+ return prepared+++def _compact_prepared_lines(+ lines: list[_LineItem],+ page_size: tuple[float, float],+) -> None:+ """缓存后续仍需的字符尺度并释放字符字典,限制跨页阶段内存占用。"""++ for line in lines:+ if line.median_glyph_width is None:+ line.median_glyph_width = _median_native_glyph_width(line, page_size)+ line.chars.clear()+++def _finalize_prepared_page(+ prepared: _PreparedPage,+ page_index: int,+) -> list[dict[str, Any]]:+ """按预分类语义、公式、标题、正文的优先级完成单页文本并排序。"""++ semantic_lines = [line for line in prepared.remaining_lines if line.semantic_type is not None]+ formula_input = [line for line in prepared.remaining_lines if line.semantic_type is None]+ formula_blocks, remaining_lines = _build_formula_like_blocks(+ formula_input,+ prepared.table_bboxes,+ prepared.page_size,+ )+ remaining_lines = _restore_dense_split_visual_rows(+ remaining_lines,+ prepared.page_size,+ prepared.table_bboxes,+ )+ _classify_page_titles(+ remaining_lines,+ prepared.page_size,+ page_index=page_index,+ container_bboxes=[block["bbox"] for block in prepared.fixed_blocks],+ )+ remaining_lines = _merge_title_resolved_visual_rows(+ remaining_lines,+ prepared.page_size,+ )+ remaining_lines = _merge_post_semantic_text_runs(+ remaining_lines,+ prepared.page_size,+ prepared.table_bboxes,+ )+ text_blocks = _build_text_blocks(+ semantic_lines + remaining_lines,+ prepared.table_bboxes,+ prepared.page_size,+ prepared.drawing_lines,+ page_footnote_groups=prepared.page_footnote_groups,+ )+ absolute_blocks = prepared.fixed_blocks + formula_blocks + text_blocks+ sorted_blocks = _sort_blocks_with_visual_row_groups(absolute_blocks, prepared.page_size)+ return [+ normalized+ for block in sorted_blocks+ if (normalized := _normalize_output_block(block, prepared.page_size)) is not None+ ]+++def _analyze_page_source(source: _PageSource) -> list[dict[str, Any]]:+ """兼容单页测试入口;单页不凭边缘位置猜测页眉、页脚或页码。"""++ if not source.lines and not source.image_bboxes:+ return []+ return _finalize_prepared_page(_prepare_page_source(source), page_index=0)+++def _sort_blocks_with_visual_row_groups(+ blocks: list[dict[str, Any]],+ page_size: tuple[float, float],+) -> list[dict[str, Any]]:+ """把同一粗行拆出的单行 block 包装成虚拟项排序,再按局部 x 顺序展开。"""++ grouped_indices: dict[int, list[int]] = {}+ for index, block in enumerate(blocks):+ row_id = block.get("_single_run_row_id")+ if isinstance(row_id, int):+ grouped_indices.setdefault(row_id, []).append(index)++ virtual_groups: dict[int, dict[str, Any]] = {}+ consumed_indices: set[int] = set()+ for row_id, indices in grouped_indices.items():+ if len(indices) < 2:+ continue+ members = [blocks[index] for index in indices]+ virtual_group = {+ "type": "_xycut_visual_row_group",+ "bbox": _bbox_union_many([member["bbox"] for member in members]),+ "angle": members[0].get("angle", 0),+ "content": "",+ "_members": members,+ }+ virtual_groups[row_id] = virtual_group+ consumed_indices.update(indices)++ sortable_blocks = [block for index, block in enumerate(blocks) if index not in consumed_indices]+ sortable_blocks.extend(virtual_groups.values())+ sorted_payloads = sort_entries(sortable_blocks)+ output: list[dict[str, Any]] = []+ for payload in sorted_payloads:+ members = payload.get("_members")+ if not isinstance(members, list):+ output.append(payload)+ continue+ angle = int(payload.get("angle", 0) or 0) % 360+ members.sort(+ key=lambda member: (+ _rotate_bbox_to_upright(member["bbox"], page_size, angle)[0],+ _rotate_bbox_to_upright(member["bbox"], page_size, angle)[1],+ )+ )+ output.extend(members)+ return output+++def _normalize_output_block(+ block: dict[str, Any],+ page_size: tuple[float, float],+) -> dict[str, Any] | None:+ """在排序完成后将绝对 bbox 裁剪并归一化为 model_list 坐标。"""++ page_width, page_height = page_size+ bbox = _clip_bbox(_coerce_bbox(block.get("bbox")), page_size)+ if bbox is None or page_width <= 0 or page_height <= 0:+ return None+ content = block.get("content")+ if not isinstance(content, str):+ return None+ content = _sanitize_pdf_control_text(content, preserve_newlines=True)+ block_type = block.get("type")+ normalized_type = block_type if block_type in _OUTPUT_BLOCK_TYPES else "text"+ if normalized_type != "image" and not content.strip():+ return None+ normalized_bbox = _normalize_bbox_to_thousandths(bbox, page_size)+ return {+ "type": normalized_type,+ "bbox": normalized_bbox,+ "angle": 0 if normalized_type == "image" else int(block.get("angle", 0) or 0) % 360,+ "content": content,+ }+diff --git a/mineru/backend/flash/native_pdf/tables.py b/mineru/backend/flash/native_pdf/tables.pynew file mode 100644index 00000000..1441be46--- /dev/null+++ b/mineru/backend/flash/native_pdf/tables.py@@ -0,0 +1,714 @@+# Copyright (c) Opendatalab. All rights reserved.++"""检测、投影并物化 Flash 原生 PDF 表格。"""++from __future__ import annotations++import re+import statistics+from typing import Any++from loguru import logger++from mineru.backend.hybrid.table_text import project_pdf_table_text+from mineru.types import BBox++from .models import (+ _Fragment,+ _LineItem,+ _LocalAxisLine,+ _PageSource,+ _TableCandidate,+ _VisualRow,+)+from .geometry import (+ _bbox_axis_overlap_ratio,+ _bbox_center_x,+ _bbox_center_y,+ _bbox_overlap_in_smaller,+ _bbox_union,+ _bbox_union_many,+ _point_in_bbox,+ _rotate_bbox_from_upright,+ _rotate_bbox_to_upright,+ _transform_axis_lines,+)+from .line_layout import _line_effective_height+from .line_merging import _same_baseline_geometry+++_TABLE_CAPTION_RE = re.compile(+ r"^(?:table|tab\.?|表格?)[\s:.–—-]*(?:\d+|[ivxlcdm]+|[一二三四五六七八九十]+)\b(?P<suffix>.*)$",+ re.IGNORECASE,+)+++_TABLE_NOTE_RE = re.compile(+ r"^(?:notes?|sources?)\b|^(?:注释?|说明)\s*[::]?|^for\s+[*†‡]"+ r"|^(?:\d+|[*†‡])\s+\S"+ r"|^(?:[*†‡]|[a-z]|p|t|ns|na)\s+(?:indicates?|denotes?|rainfall\b|total\b|low\b|for\b)",+ re.IGNORECASE,+)+++_TABLE_SPLIT_NUMBER_RE = re.compile(+ r"^(?:\d+|[ivxlcdm]+|[一二三四五六七八九十]+)[.::]?$",+ re.IGNORECASE,+)+++def _detect_table_candidates(source: _PageSource) -> list[_TableCandidate]:+ """按文本方向融合三条长横线与规则文本分布,生成表格候选。"""++ candidates: list[_TableCandidate] = []+ angles = sorted({line.angle for line in source.lines})+ for angle in angles:+ angle_lines = [line for line in source.lines if line.angle == angle]+ if not angle_lines:+ continue+ fragments = _build_fragments(angle_lines, source.page_size)+ if not fragments:+ continue+ median_height = _median_fragment_height(fragments)+ rows = _cluster_fragment_rows(fragments, median_height)+ local_axis_lines = _transform_axis_lines(+ source.drawing_lines,+ source.page_size,+ angle,+ )+ candidates.extend(+ _build_rule_table_candidates(+ rows,+ angle_lines,+ source.page_size,+ angle,+ median_height,+ local_axis_lines,+ )+ )+ return _merge_table_candidates(candidates)+++def _build_fragments(+ lines: list[_LineItem],+ page_size: tuple[float, float],+) -> list[_Fragment]:+ """将精修后的原生 run 转换成表格单元候选。"""++ fragments: list[_Fragment] = []+ for line in lines:+ local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, line.angle)+ fragments.append(+ _Fragment(+ text=line.text,+ bbox=line.bbox,+ local_bbox=local_bbox,+ line_index=line.source_index,+ # 复用原生粗行身份,避免同一字符行内不同 cell+ # 因轻微基线差异被误拆成多行。+ visual_row_id=line.visual_row_id,+ )+ )+ return fragments+++def _cluster_fragment_rows(+ fragments: list[_Fragment],+ median_height: float,+) -> list[_VisualRow]:+ """优先复用原生视觉行身份,其余片段按中心线容差聚成表格行。"""++ tolerance = max(2.0, median_height * 0.5)+ native_groups: dict[int, list[_Fragment]] = {}+ geometric_fragments: list[_Fragment] = []+ for fragment in fragments:+ if fragment.visual_row_id is None:+ geometric_fragments.append(fragment)+ else:+ native_groups.setdefault(fragment.visual_row_id, []).append(fragment)++ # 先锁定同一原生粗行拆出的 run,再允许不同粗行按基线几何合并;+ # 旋转表格常把同一数据行的各 cell 分成多个 pdftext 粗行,不能只依赖 row id。+ seed_groups = [*native_groups.values(), *[[fragment] for fragment in geometric_fragments]]+ seed_groups.sort(+ key=lambda group: (+ statistics.fmean(_bbox_center_y(item.local_bbox) for item in group),+ min(item.local_bbox[0] for item in group),+ )+ )+ grouped: list[list[_Fragment]] = []+ for seed_group in seed_groups:+ center_y = statistics.fmean(_bbox_center_y(item.local_bbox) for item in seed_group)+ target_group: list[_Fragment] | None = None+ for group in grouped:+ group_center = statistics.fmean(_bbox_center_y(item.local_bbox) for item in group)+ if abs(center_y - group_center) <= tolerance:+ target_group = group+ break+ if target_group is None:+ grouped.append(list(seed_group))+ else:+ target_group.extend(seed_group)++ rows: list[_VisualRow] = []+ for group in grouped:+ group.sort(key=lambda item: item.local_bbox[0])+ bbox = _bbox_union_many([item.local_bbox for item in group])+ visual_row_ids = {item.visual_row_id for item in group if item.visual_row_id is not None}+ rows.append(+ _VisualRow(+ fragments=group,+ center_y=sum(_bbox_center_y(item.local_bbox) for item in group) / len(group),+ bbox=bbox,+ visual_row_id=next(iter(visual_row_ids)) if len(visual_row_ids) == 1 else None,+ )+ )+ rows.sort(key=lambda row: row.center_y)+ return rows+++def _build_rule_table_candidates(+ rows: list[_VisualRow],+ lines: list[_LineItem],+ page_size: tuple[float, float],+ angle: int,+ median_height: float,+ axis_lines: list[_LocalAxisLine],+) -> list[_TableCandidate]:+ """用三条长横线确定区域,再以连续多列文本分布确认表格。"""++ candidates: list[_TableCandidate] = []+ for rule_group in _group_long_horizontal_rules(axis_lines, median_height):+ rule_bbox = _bbox_union_many([line.bbox for line in rule_group])+ core_rows: list[_VisualRow] = []+ for row in rows:+ clipped_row = _clip_visual_row_to_corridor(row, rule_bbox, margin=0.0)+ if clipped_row is not None and rule_bbox[1] <= clipped_row.center_y <= rule_bbox[3]:+ core_rows.append(clipped_row)++ dense_rows = _longest_dense_multi_cell_rows(core_rows, median_height)+ if len(dense_rows) < 3:+ continue+ stable_columns, column_coverage = _count_stable_columns(dense_rows, median_height)+ if stable_columns < 2 or column_coverage < 0.5:+ continue++ caption_line = _find_table_caption(lines, rule_bbox, page_size, angle, median_height)+ candidate = _expand_rule_table_candidate(+ rule_group,+ core_rows,+ rows,+ page_size,+ angle,+ median_height,+ caption_line,+ )+ candidate.score = float(len(rule_group) + len(dense_rows) + stable_columns)+ candidates.append(candidate)+ return candidates+++def _group_long_horizontal_rules(+ axis_lines: list[_LocalAxisLine],+ median_height: float,+) -> list[list[_LocalAxisLine]]:+ """按近似左右端点和纵向距离聚合长横线,并去除同位置重复路径。"""++ minimum_length = max(40.0, 10.0 * median_height)+ horizontal_lines = [+ line for line in axis_lines if line.orientation == "horizontal" and line.bbox[2] - line.bbox[0] >= minimum_length+ ]+ endpoint_tolerance = max(4.0, 2.0 * median_height)+ span_groups: list[list[_LocalAxisLine]] = []+ for line in sorted(horizontal_lines, key=lambda item: (item.bbox[0], item.bbox[2], item.bbox[1])):+ target = next(+ (+ group+ for group in span_groups+ if abs(line.bbox[0] - group[0].bbox[0]) <= endpoint_tolerance+ and abs(line.bbox[2] - group[0].bbox[2]) <= endpoint_tolerance+ ),+ None,+ )+ if target is None:+ span_groups.append([line])+ else:+ target.append(line)++ output: list[list[_LocalAxisLine]] = []+ maximum_vertical_gap = 24.0 * median_height+ for span_group in span_groups:+ vertical_groups: list[list[_LocalAxisLine]] = []+ for line in sorted(span_group, key=lambda item: _bbox_center_y(item.bbox)):+ if (+ not vertical_groups+ or _bbox_center_y(line.bbox) - _bbox_center_y(vertical_groups[-1][-1].bbox) > maximum_vertical_gap+ ):+ vertical_groups.append([line])+ else:+ vertical_groups[-1].append(line)++ for vertical_group in vertical_groups:+ unique_lines: list[_LocalAxisLine] = []+ for line in vertical_group:+ if any(abs(_bbox_center_y(line.bbox) - _bbox_center_y(item.bbox)) <= 1.0 for item in unique_lines):+ continue+ unique_lines.append(line)+ if len(unique_lines) >= 3:+ output.append(unique_lines)+ return output+++def _clip_visual_row_to_corridor(+ row: _VisualRow,+ corridor_bbox: BBox,+ *,+ margin: float,+) -> _VisualRow | None:+ """仅保留横向走廊内的片段,避免同基线的另一栏文本污染表格区域。"""++ fragments = [+ fragment+ for fragment in row.fragments+ if corridor_bbox[0] - margin <= _bbox_center_x(fragment.local_bbox) <= corridor_bbox[2] + margin+ ]+ if not fragments:+ return None+ fragments.sort(key=lambda fragment: fragment.local_bbox[0])+ return _VisualRow(+ fragments=fragments,+ center_y=sum(_bbox_center_y(fragment.local_bbox) for fragment in fragments) / len(fragments),+ bbox=_bbox_union_many([fragment.local_bbox for fragment in fragments]),+ visual_row_id=row.visual_row_id,+ )+++def _longest_dense_multi_cell_rows(+ rows: list[_VisualRow],+ median_height: float,+) -> list[_VisualRow]:+ """返回行距不超过四倍行高的最长连续多单元格文本段。"""++ segments: list[list[_VisualRow]] = []+ for row in (item for item in rows if len(item.fragments) >= 2):+ if not segments or row.center_y - segments[-1][-1].center_y > 4.0 * median_height:+ segments.append([row])+ else:+ segments[-1].append(row)+ return max(segments, key=len, default=[])+++def _expand_rule_table_candidate(+ rule_group: list[_LocalAxisLine],+ core_rows: list[_VisualRow],+ all_rows: list[_VisualRow],+ page_size: tuple[float, float],+ angle: int,+ median_height: float,+ caption_line: _LineItem | None,+) -> _TableCandidate:+ """合并横线核心、上方标题和下方脚注,构造统一投影候选。"""++ rule_bbox = _bbox_union_many([line.bbox for line in rule_group])+ core_line_indices = {fragment.line_index for row in core_rows for fragment in row.fragments}+ caption_rows = _collect_caption_rows(all_rows, caption_line, rule_bbox, median_height)+ footnote_rows = _collect_footnote_rows(+ all_rows,+ rule_bbox,+ median_height,+ core_line_indices,+ )+ included_rows = [*caption_rows, *core_rows, *footnote_rows]+ core_local_bbox = _bbox_union(rule_bbox, _bbox_union_many([row.bbox for row in core_rows]))+ local_bbox = _bbox_union(core_local_bbox, _bbox_union_many([row.bbox for row in included_rows]))+ return _TableCandidate(+ bbox=_rotate_bbox_from_upright(local_bbox, page_size, angle),+ local_bbox=local_bbox,+ angle=angle,+ score=0.0,+ core_bbox=_rotate_bbox_from_upright(core_local_bbox, page_size, angle),+ line_indices={fragment.line_index for row in included_rows for fragment in row.fragments},+ )+++def _collect_caption_rows(+ rows: list[_VisualRow],+ caption_line: _LineItem | None,+ rule_bbox: BBox,+ median_height: float,+) -> list[_VisualRow]:+ """收集显式标题所在行及其到表格上边界之间的连续换行。"""++ if caption_line is None:+ return []+ caption_row_index = next(+ (+ index+ for index, row in enumerate(rows)+ if any(fragment.line_index == caption_line.source_index for fragment in row.fragments)+ ),+ None,+ )+ if caption_row_index is None:+ return []++ output: list[_VisualRow] = []+ previous_bbox: BBox | None = None+ margin = 2.0 * median_height+ for index, row in enumerate(rows[caption_row_index:], start=caption_row_index):+ clipped_row = _clip_visual_row_to_corridor(row, rule_bbox, margin=margin)+ if clipped_row is None:+ continue+ if index > caption_row_index and clipped_row.center_y >= rule_bbox[1]:+ break+ if previous_bbox is not None and max(0.0, clipped_row.bbox[1] - previous_bbox[3]) > 2.0 * median_height:+ break+ output.append(clipped_row)+ previous_bbox = clipped_row.bbox++ if not output or rule_bbox[1] - output[-1].bbox[3] > 2.0 * median_height:+ return []+ return output+++def _collect_footnote_rows(+ rows: list[_VisualRow],+ rule_bbox: BBox,+ median_height: float,+ core_line_indices: set[int],+) -> list[_VisualRow]:+ """从表格下边界开始吸收带通用标记的脚注及其连续换行。"""++ output: list[_VisualRow] = []+ bottom = rule_bbox[3]+ note_chain_started = False+ margin = 2.0 * median_height+ selected_line_indices = set(core_line_indices)+ for row in rows:+ clipped_row = _clip_visual_row_to_corridor(row, rule_bbox, margin=margin)+ if clipped_row is None or clipped_row.bbox[3] <= bottom:+ continue+ line_indices = {fragment.line_index for fragment in clipped_row.fragments}+ if line_indices.issubset(selected_line_indices):+ bottom = max(bottom, clipped_row.bbox[3])+ continue+ if max(0.0, clipped_row.bbox[1] - bottom) > 1.5 * median_height:+ break+ if not note_chain_started and not _is_table_note_text(_visual_row_text(clipped_row)):+ break+ output.append(clipped_row)+ selected_line_indices.update(line_indices)+ bottom = max(bottom, clipped_row.bbox[3])+ note_chain_started = True+ return output+++def _visual_row_text(row: _VisualRow) -> str:+ """按局部 x 顺序拼接视觉行文本,供拆分脚注标记判断。"""++ return " ".join(fragment.text.strip() for fragment in row.fragments if fragment.text.strip())+++def _is_table_note_text(text: str) -> bool:+ """判断表后首行是否具有明确的注释、来源或脚注标记。"""++ return bool(_TABLE_NOTE_RE.match(str(text or "").strip()))+++def _find_table_caption(+ lines: list[_LineItem],+ core_bbox: BBox,+ page_size: tuple[float, float],+ angle: int,+ median_height: float,+) -> _LineItem | None:+ """在核心表格上方最多十二倍行高内查找显式 Table/表标题。"""++ candidates: list[tuple[float, _LineItem]] = []+ for line in lines:+ text = line.text.strip()+ caption_match = _TABLE_CAPTION_RE.match(text)+ is_split_label = text.lower().rstrip(".") in {"table", "tab", "表", "表格"}+ if caption_match is None and not is_split_label:+ continue+ if caption_match is not None:+ suffix = caption_match.group("suffix").strip(" .:–—-")+ # 小写连续句通常是“Table 5 also ...”这类正文,不应作为标题。+ if suffix and suffix[0].islower():+ continue+ local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, angle)+ if _bbox_axis_overlap_ratio(local_bbox, core_bbox, axis="x") < 0.05:+ continue+ if is_split_label:+ has_number_peer = bool(+ _find_caption_number_peers(+ line,+ lines,+ page_size,+ angle,+ median_height,+ )+ )+ if not has_number_peer:+ continue+ gap = core_bbox[1] - local_bbox[3]+ if -median_height <= gap <= 12.0 * median_height:+ candidates.append((abs(gap), line))+ if not candidates:+ return None+ return min(candidates, key=lambda item: item[0])[1]+++def _find_caption_number_peers(+ caption_line: _LineItem,+ lines: list[_LineItem],+ page_size: tuple[float, float],+ angle: int,+ median_height: float,+) -> list[_LineItem]:+ """查找与拆分 Table/表 标签同一视觉行的编号文本。"""++ caption_local_bbox = _rotate_bbox_to_upright(caption_line.bbox, page_size, angle)+ peers: list[_LineItem] = []+ for peer in lines:+ if peer.source_index == caption_line.source_index:+ continue+ if not _TABLE_SPLIT_NUMBER_RE.match(peer.text.strip()):+ continue+ peer_local_bbox = _rotate_bbox_to_upright(peer.bbox, page_size, angle)+ gap = peer_local_bbox[0] - caption_local_bbox[2]+ if _bbox_axis_overlap_ratio(caption_local_bbox, peer_local_bbox, axis="y") >= 0.5 and 0.0 <= gap <= 4.0 * median_height:+ peers.append(peer)+ return sorted(+ peers,+ key=lambda peer: _rotate_bbox_to_upright(peer.bbox, page_size, angle)[0],+ )+++def _count_stable_columns(+ rows: list[_VisualRow],+ median_height: float,+) -> tuple[int, float]:+ """分别聚类片段左边界、中心和右边界,返回最稳定的列分布。"""++ tolerance = max(3.0, median_height * 0.75)+ best_result = (0, 0.0)+ # 三种对齐方式分别聚类,避免把同一片段的不同锚点混算为多列。+ for alignment in ("left", "center", "right"):+ clusters: list[dict[str, Any]] = []+ for row_index, row in enumerate(rows):+ for fragment in row.fragments:+ left, _top, right, _bottom = fragment.local_bbox+ if alignment == "left":+ anchor = left+ elif alignment == "center":+ anchor = (left + right) / 2+ else:+ anchor = right+ cluster = next(+ (item for item in clusters if abs(anchor - float(item["mean"])) <= tolerance),+ None,+ )+ if cluster is None:+ clusters.append({"mean": anchor, "values": [anchor], "rows": {row_index}})+ else:+ cluster["values"].append(anchor)+ cluster["rows"].add(row_index)+ cluster["mean"] = sum(cluster["values"]) / len(cluster["values"])+ stable_coverages = [+ len(cluster["rows"]) / len(rows)+ for cluster in clusters+ if len(cluster["rows"]) / len(rows) >= 0.5+ ]+ result = (+ len(stable_coverages),+ min(stable_coverages) if stable_coverages else 0.0,+ )+ # 仅在结果严格更优时更新,平局时保留既有的左对齐优先级。+ if result > best_result:+ best_result = result+ return best_result+++def _merge_table_candidates(candidates: list[_TableCandidate]) -> list[_TableCandidate]:+ """合并同方向且明显重叠的横线候选,避免同一表格重复输出。"""++ merged: list[_TableCandidate] = []+ for candidate in sorted(candidates, key=lambda item: item.score, reverse=True):+ target = next(+ (+ item+ for item in merged+ if item.angle == candidate.angle and _bbox_overlap_in_smaller(candidate.bbox, item.bbox) >= 0.2+ ),+ None,+ )+ if target is None:+ merged.append(candidate)+ continue+ target.bbox = _bbox_union(target.bbox, candidate.bbox)+ target.local_bbox = _bbox_union(target.local_bbox, candidate.local_bbox)+ if target.core_bbox is None:+ target.core_bbox = candidate.core_bbox+ elif candidate.core_bbox is not None:+ target.core_bbox = _bbox_union(target.core_bbox, candidate.core_bbox)+ target.line_indices.update(candidate.line_indices)+ target.score = max(target.score, candidate.score)+ return sorted(merged, key=lambda item: (item.bbox[1], item.bbox[0]))+++def _materialize_table_blocks(+ source: _PageSource,+ candidates: list[_TableCandidate],+) -> tuple[list[dict[str, Any]], set[int]]:+ """为候选生成空间投影 content,仅认领投影成功的文本行。"""++ blocks: list[dict[str, Any]] = []+ claimed: set[int] = set()+ for candidate in sorted(candidates, key=lambda item: item.score, reverse=True):+ if any(_bbox_overlap_in_smaller(candidate.bbox, block["bbox"]) >= 0.5 for block in blocks):+ continue+ output_angle = candidate.angle+ projection_line_indices = _candidate_projection_line_indices(source, candidate)+ try:+ candidate_chars = [+ char for line in source.lines if line.source_index in projection_line_indices for char in line.chars+ ]+ content = project_pdf_table_text(+ candidate_chars,+ candidate.bbox,+ angle=candidate.angle,+ )+ except Exception as exc:+ # 单个表格的字符投影异常只撤销该候选,不能中止整页提取。+ logger.warning(f"Flash table projection failed and rolled back: bbox={candidate.bbox}, error={exc}")+ continue+ if not content or not content.strip():+ continue+ blocks.append(+ {+ "type": "table",+ "bbox": candidate.bbox,+ "angle": output_angle,+ "content": content,+ }+ )+ # 只认领候选明确接纳的视觉行,避免远标题与表格之间的正文被矩形 bbox 连带删除。+ claimed.update(projection_line_indices)+ blocks.sort(key=lambda block: (block["bbox"][1], block["bbox"][0]))+ return blocks, claimed+++def _candidate_projection_line_indices(+ source: _PageSource,+ candidate: _TableCandidate,+) -> set[int]:+ """合并核心成员、同基线续段及非零角度表格的表头文本。"""++ line_indices = set(candidate.line_indices)+ if candidate.core_bbox is not None:+ for line in source.lines:+ if _point_in_bbox(+ (_bbox_center_x(line.bbox), _bbox_center_y(line.bbox)),+ candidate.core_bbox,+ ):+ line_indices.add(line.source_index)+ if candidate.angle == 0:+ _expand_candidate_same_baseline_members(source, candidate, line_indices)+ return line_indices+ if candidate.core_bbox is None:+ return line_indices++ candidate_local_bbox = _rotate_bbox_to_upright(+ candidate.bbox,+ source.page_size,+ candidate.angle,+ )+ core_local_bbox = _rotate_bbox_to_upright(+ candidate.core_bbox,+ source.page_size,+ candidate.angle,+ )+ for line in source.lines:+ if line.angle != candidate.angle:+ continue+ page_center = (_bbox_center_x(line.bbox), _bbox_center_y(line.bbox))+ if not _point_in_bbox(page_center, candidate.bbox):+ continue+ local_bbox = _rotate_bbox_to_upright(+ line.bbox,+ source.page_size,+ candidate.angle,+ )+ local_center_y = _bbox_center_y(local_bbox)+ if not candidate_local_bbox[1] <= local_center_y <= candidate_local_bbox[3]:+ continue+ if _bbox_axis_overlap_ratio(local_bbox, core_local_bbox, axis="x") < 0.05:+ continue+ line_indices.add(line.source_index)+ return line_indices+++def _expand_candidate_same_baseline_members(+ source: _PageSource,+ candidate: _TableCandidate,+ line_indices: set[int],+) -> None:+ """迭代吸收完整候选框内与已认领成员同基线相邻的 angle=0 续段。"""++ local_bboxes = {+ line.source_index: _rotate_bbox_to_upright(+ line.bbox,+ source.page_size,+ candidate.angle,+ )+ for line in source.lines+ if line.angle == candidate.angle+ }+ changed = True+ while changed:+ changed = False+ selected_lines = [+ line+ for line in source.lines+ if line.angle == candidate.angle and line.source_index in line_indices+ ]+ for line in source.lines:+ if line.angle != candidate.angle or line.source_index in line_indices:+ continue+ if not _point_in_bbox(+ (_bbox_center_x(line.bbox), _bbox_center_y(line.bbox)),+ candidate.bbox,+ ):+ continue+ line_bbox = local_bboxes[line.source_index]+ line_height = _line_effective_height(line, line_bbox)+ for selected in selected_lines:+ if (+ line.font_signature is not None+ and selected.font_signature is not None+ and line.font_signature != selected.font_signature+ ):+ continue+ selected_bbox = local_bboxes[selected.source_index]+ if not _same_baseline_geometry(+ line_bbox,+ line_height,+ selected_bbox,+ _line_effective_height(selected, selected_bbox),+ ):+ continue+ line_indices.add(line.source_index)+ changed = True+ break+++def _median_fragment_height(fragments: list[_Fragment]) -> float:+ """返回正向文本片段高度的中位数。"""++ heights = [+ fragment.local_bbox[3] - fragment.local_bbox[1]+ for fragment in fragments+ if fragment.local_bbox[3] > fragment.local_bbox[1]+ ]+ return max(0.1, float(statistics.median(heights)) if heights else 1.0)diff --git a/mineru/backend/flash/native_pdf/text_blocks.py b/mineru/backend/flash/native_pdf/text_blocks.pynew file mode 100644index 00000000..1aa38d39--- /dev/null+++ b/mineru/backend/flash/native_pdf/text_blocks.py@@ -0,0 +1,496 @@+# Copyright (c) Opendatalab. All rights reserved.++"""将剩余文本行构造成正文和页脚注块。"""++from __future__ import annotations++import statistics+from typing import Any, Sequence+++from mineru.backend.utils.char_utils import resolve_text_line_boundary+from mineru.types import BBox+from mineru.utils.language import detect_lang++from .models import (+ _AxisLine,+ _LineItem,+ _LocalAxisLine,+ _TextLane,+)+from .geometry import (+ _bbox_center_y,+ _bbox_union_many,+ _rotate_bbox_from_upright,+ _rotate_bbox_to_upright,+ _transform_axis_lines,+)+from .native_text import _normalize_native_run_text+from .line_layout import (+ _connection_crosses_table,+ _effective_text_row_gap,+ _estimate_lane_gap,+ _horizontal_rule_separates_rows,+ _infer_text_lanes,+ _line_effective_height,+ _should_connect_semantic_rows,+ _should_connect_text_rows,+)+def _build_hanging_indent_group_map(+ lane: _TextLane,+ table_bboxes: list[BBox],+ axis_lines: list[_LocalAxisLine],+) -> dict[int, int]:+ """仅按重复的左突首行和稳定续行缩进识别悬挂缩进条目。"""++ if lane.is_span or len(lane.lines) < 4:+ return {}+ rows = sorted(+ (item for item in lane.lines if item[0].semantic_type is None),+ key=lambda item: (item[1+ ][1], item[1][0], item[0].source_index),+ )+ if len(rows) < 4:+ return {}+ median_height = statistics.median(+ _line_effective_height(line, bbox) for line, bbox in rows+ )+ start_tolerance = max(5.0, 0.65 * median_height)+ minimum_indent = max(7.0, 0.8 * median_height)+ continuation_tolerance = max(4.0, 0.55 * median_height)++ def rows_are_adjacent(+ previous: tuple[_LineItem, BBox],+ current: tuple[_LineItem, BBox],+ ) -> bool:+ """检查相邻行的净空和几何障碍是否允许组成同一缩进序列。"""++ effective_gap = _effective_text_row_gap(previous, current)+ if not -0.6 * median_height <= effective_gap <= 1.3 * median_height:+ return False+ if _connection_crosses_table(+ previous[0].bbox,+ current[0].bbox,+ table_bboxes,+ ):+ return False+ return not _horizontal_rule_separates_rows(+ previous[1],+ current[1],+ lane,+ axis_lines,+ )++ def consume_entry(+ start_index: int,+ start_left: float,+ expected_continuation_left: float | None,+ *,+ require_next_start: bool,+ ) -> tuple[int, float] | None:+ """消费一个左突首行及其续行,并返回下一条首行位置。"""++ continuation_index = start_index + 1+ if continuation_index >= len(rows):+ return None+ first_continuation = rows[continuation_index]+ if not rows_are_adjacent(rows[start_index], first_continuation):+ return None+ continuation_left = first_continuation[1][0]+ if continuation_left < start_left + minimum_indent:+ return None+ if (+ expected_continuation_left is not None+ and abs(continuation_left - expected_continuation_left) > continuation_tolerance+ ):+ return None++ continuation_index += 1+ while continuation_index < len(rows):+ previous = rows[continuation_index - 1]+ current = rows[continuation_index]+ current_left = current[1][0]+ if not rows_are_adjacent(previous, current):+ break+ if current_left < start_left + minimum_indent:+ break+ if abs(current_left - continuation_left) > continuation_tolerance:+ break+ continuation_index += 1++ if not require_next_start:+ return continuation_index, continuation_left+ if continuation_index >= len(rows):+ return None+ if not rows_are_adjacent(rows[continuation_index - 1], rows[continuation_index]):+ return None+ if abs(rows[continuation_index][1][0] - start_left) > start_tolerance:+ return None+ return continuation_index, continuation_left++ group_map: dict[int, int] = {}+ group_index = 0+ row_index = 0+ while row_index < len(rows) - 3:+ start_left = rows[row_index][1][0]+ first_entry = consume_entry(+ row_index,+ start_left,+ None,+ require_next_start=True,+ )+ if first_entry is None:+ row_index += 1+ continue++ next_start_index, continuation_left = first_entry+ start_indices = [row_index, next_start_index]+ current_start_index = next_start_index+ while True:+ next_entry = consume_entry(+ current_start_index,+ start_left,+ continuation_left,+ require_next_start=True,+ )+ if next_entry is None:+ break+ next_start_index, _continuation_left = next_entry+ start_indices.append(next_start_index)+ current_start_index = next_start_index++ final_entry = consume_entry(+ start_indices[-1],+ start_left,+ continuation_left,+ require_next_start=False,+ )+ if final_entry is None:+ row_index += 1+ continue+ end_index, _continuation_left = final_entry++ entry_ranges = [+ (start, end)+ for start, end in zip(+ start_indices,+ [*start_indices[1:], end_index],+ strict=True,+ )+ ]+ for start, end in entry_ranges:+ for line, _bbox in rows[start:end]:+ group_map[line.source_index] = group_index+ group_index += 1+ row_index = end_index++ return group_map+++def _build_grouped_page_footnote_blocks(+ lines: list[_LineItem],+ source_groups: Sequence[set[int]],+ page_size: tuple[float, float],+) -> tuple[list[dict[str, Any]], set[int]]:+ """按分隔线组切分几何脚注条目,并返回已消费的来源编号。"""++ footnote_by_source = {+ line.source_index: line+ for line in lines+ if line.semantic_type == "page_footnote"+ }+ blocks: list[dict[str, Any]] = []+ consumed_source_indices: set[int] = set()+ for source_group in source_groups:+ group_lines = [+ footnote_by_source[source_index]+ for source_index in source_group+ if source_index in footnote_by_source+ ]+ for angle in sorted({line.angle for line in group_lines}):+ directional_lines = [line for line in group_lines if line.angle == angle]+ tight_bboxes = _tight_page_footnote_bboxes(+ directional_lines,+ page_size,+ )+ for entry_lines in _split_page_footnote_entries(+ directional_lines,+ page_size,+ ):+ ordered_lines = sorted(+ entry_lines,+ key=lambda line: (+ _rotate_bbox_to_upright(line.bbox, page_size, angle)[1],+ _rotate_bbox_to_upright(line.bbox, page_size, angle)[0],+ line.source_index,+ ),+ )+ content = _merge_text_line_content([line.text for line in ordered_lines])+ if not content:+ continue+ visual_row_ids = {+ line.visual_row_id+ for line in ordered_lines+ if line.visual_row_id is not None+ }+ single_run_row_id = (+ ordered_lines[0].visual_row_id+ if len(ordered_lines) == 1+ and ordered_lines[0].split_from_row+ and ordered_lines[0].visual_row_id is not None+ else None+ )+ blocks.append(+ {+ "type": "page_footnote",+ "bbox": _bbox_union_many(+ [tight_bboxes[line.source_index] for line in ordered_lines]+ ),+ "angle": angle,+ "content": content,+ "_visual_row_ids": visual_row_ids,+ "_single_run_row_id": single_run_row_id,+ }+ )+ consumed_source_indices.update(+ line.source_index for line in ordered_lines+ )+ return blocks, consumed_source_indices+++def _split_page_footnote_entries(+ lines: list[_LineItem],+ page_size: tuple[float, float],+) -> list[list[_LineItem]]:+ """按首行或续行缩进模式,把同一分隔线下的脚注行切成条目。"""++ if not lines:+ return []+ angle = lines[0].angle+ line_geometry = [+ (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))+ for line in lines+ ]+ line_geometry.sort(+ key=lambda item: (item[1][1], item[1][0], item[0].source_index)+ )+ if len(line_geometry) == 1:+ return [[line_geometry[0][0]]]++ effective_heights = [+ _line_effective_height(line, bbox)+ for line, bbox in line_geometry+ ]+ median_height = statistics.median(effective_heights)+ glyph_widths = [+ line.median_glyph_width+ for line, _bbox in line_geometry+ if line.median_glyph_width is not None+ ]+ median_glyph_width = (+ statistics.median(glyph_widths)+ if glyph_widths+ else 0.5 * median_height+ )+ indent_threshold = max(1.5 * median_height, 2.0 * median_glyph_width)+ base_left = min(bbox[0] for _line, bbox in line_geometry)+ maximum_row_width = max(bbox[2] - bbox[0] for _line, bbox in line_geometry)+ first_line_is_indented = line_geometry[0][1][0] - base_left > indent_threshold++ entries: list[list[_LineItem]] = [[line_geometry[0][0]]]+ for previous, current in zip(line_geometry, line_geometry[1:]):+ previous_width = previous[1][2] - previous[1][0]+ previous_is_near_full = previous_width >= 0.8 * maximum_row_width+ current_is_indented = current[1][0] - base_left > indent_threshold+ # 满行后必然续接;其余行按首页观测到的首行/续行缩进模式决定边界。+ continues_previous = previous_is_near_full or (+ not current_is_indented+ if first_line_is_indented+ else current_is_indented+ )+ if continues_previous:+ entries[-1].append(current[0])+ else:+ entries.append([current[0]])+ return entries+++def _tight_page_footnote_bboxes(+ lines: list[_LineItem],+ page_size: tuple[float, float],+) -> dict[int, BBox]:+ """以有效行高和相邻行距收紧脚注框,避免异常字体框跨入相邻条目。"""++ if not lines:+ return {}+ angle = lines[0].angle+ line_geometry = [+ (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))+ for line in lines+ ]+ line_geometry.sort(+ key=lambda item: (item[1][1], item[1][0], item[0].source_index)+ )+ median_height = statistics.median(+ _line_effective_height(line, bbox)+ for line, bbox in line_geometry+ )+ row_pitches = [+ current[1][1] - previous[1][1]+ for previous, current in zip(line_geometry, line_geometry[1:])+ if current[1][1] - previous[1][1] > 0.25 * median_height+ ]+ median_pitch = statistics.median(row_pitches) if row_pitches else None++ output: dict[int, BBox] = {}+ for line, bbox in line_geometry:+ tight_height = min(+ bbox[3] - bbox[1],+ _line_effective_height(line, bbox),+ )+ if median_pitch is not None:+ tight_height = min(tight_height, 0.9 * median_pitch)+ tight_height = max(0.1, tight_height)+ center_y = _bbox_center_y(bbox)+ tight_local_bbox = (+ bbox[0],+ center_y - 0.5 * tight_height,+ bbox[2],+ center_y + 0.5 * tight_height,+ )+ output[line.source_index] = _rotate_bbox_from_upright(+ tight_local_bbox,+ page_size,+ angle,+ )+ return output+++def _build_text_blocks(+ lines: list[_LineItem],+ table_bboxes: list[BBox],+ page_size: tuple[float, float],+ drawing_lines: list[_AxisLine] | None = None,+ *,+ page_footnote_groups: Sequence[set[int]] | None = None,+) -> list[dict[str, Any]]:+ """先构建分组脚注,再按类型屏障、栏带和自然段边界聚合其余文本。"""++ blocks, grouped_footnote_indices = _build_grouped_page_footnote_blocks(+ lines,+ page_footnote_groups or [],+ page_size,+ )+ lines = [+ line+ for line in lines+ if line.source_index not in grouped_footnote_indices+ ]+ for angle in sorted({line.angle for line in lines}):+ line_geometry = [(line, _rotate_bbox_to_upright(line.bbox, page_size, angle)) for line in lines if line.angle == angle]+ if not line_geometry:+ continue+ line_geometry.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))+ effective_heights = [_line_effective_height(line, bbox) for line, bbox in line_geometry]+ median_height = statistics.median(effective_heights) if effective_heights else 1.0+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]+ lanes = _infer_text_lanes(line_geometry, local_page_width, median_height)+ local_axis_lines = _transform_axis_lines(drawing_lines or [], page_size, angle)++ for lane in lanes:+ lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))+ if not lane.lines:+ continue+ regular_gap, gap_mad = _estimate_lane_gap(lane)+ hanging_indent_groups = _build_hanging_indent_group_map(+ lane,+ table_bboxes,+ local_axis_lines,+ )+ component: list[tuple[_LineItem, BBox]] = [lane.lines[0]]+ components: list[list[tuple[_LineItem, BBox]]] = []+ for previous, current in zip(lane.lines, lane.lines[1:]):+ previous_type = previous[0].semantic_type+ current_type = current[0].semantic_type+ if previous_type != current_type:+ should_connect = False+ elif previous_type is not None:+ should_connect = _should_connect_semantic_rows(+ previous,+ current,+ lane,+ regular_gap,+ table_bboxes,+ local_axis_lines,+ )+ else:+ previous_group = hanging_indent_groups.get(previous[0].source_index)+ current_group = hanging_indent_groups.get(current[0].source_index)+ if previous_group is not None or current_group is not None:+ should_connect = previous_group is not None and previous_group == current_group+ else:+ should_connect = _should_connect_text_rows(+ previous,+ current,+ lane,+ regular_gap,+ gap_mad,+ table_bboxes,+ local_axis_lines,+ )+ if should_connect:+ component.append(current)+ else:+ components.append(component)+ component = [current]+ components.append(component)++ for component_geometry in components:+ component_lines = [item[0] for item in component_geometry]+ content = _merge_text_line_content([line.text for line in component_lines])+ if not content:+ continue+ visual_row_ids = {+ line.visual_row_id for line in component_lines if line.visual_row_id is not None+ }+ single_run_row_id = (+ component_lines[0].visual_row_id+ if len(component_lines) == 1+ and component_lines[0].split_from_row+ and component_lines[0].visual_row_id is not None+ else None+ )+ blocks.append(+ {+ "type": component_lines[0].semantic_type or "text",+ "bbox": _bbox_union_many([line.bbox for line in component_lines]),+ "angle": angle,+ "content": content,+ "_visual_row_ids": visual_row_ids,+ "_single_run_row_id": single_run_row_id,+ }+ )+ return blocks+++def _merge_text_line_content(line_texts: Sequence[str]) -> str:+ """按 Hybrid 语言与行末连字规则折叠普通文本行。"""++ normalized_lines = [_normalize_native_run_text(str(text or "")) for text in line_texts]+ normalized_lines = [text for text in normalized_lines if text]+ if not normalized_lines:+ return ""+ try:+ block_language = detect_lang("".join(normalized_lines))+ except Exception:+ block_language = ""+ content_parts = [normalized_lines[0]]+ for current_line in normalized_lines[1:]:+ processed_previous, separator = resolve_text_line_boundary(+ content_parts[-1],+ block_language=block_language,+ next_starts_with_lowercase=current_line[0].islower(),+ )+ content_parts[-1] = processed_previous+ content_parts.extend([separator, current_line])+ return "".join(content_parts).strip()diff --git a/mineru/backend/flash/native_pdf/titles.py b/mineru/backend/flash/native_pdf/titles.pynew file mode 100644index 00000000..8df764f5--- /dev/null+++ b/mineru/backend/flash/native_pdf/titles.py@@ -0,0 +1,654 @@+# Copyright (c) Opendatalab. All rights reserved.++"""基于排版差异分类文档标题和段落标题。"""++from __future__ import annotations++import statistics+from typing import Literal+++from mineru.types import BBox++from .models import (+ _LaneBodyProfile,+ _LineItem,+ _TextLane,+)+from .geometry import (+ _bbox_axis_overlap_ratio,+ _bbox_center_x,+ _bbox_center_y,+ _rotate_bbox_to_upright,+)+from .line_layout import (+ _effective_text_row_gap,+ _estimate_lane_gap,+ _infer_text_lanes,+ _line_effective_height,+ _should_connect_semantic_rows,+ _title_fonts_compatible,+)+++def _classify_page_titles(+ lines: list[_LineItem],+ page_size: tuple[float, float],+ *,+ page_index: int,+ container_bboxes: list[BBox],+) -> None:+ """只用页面几何与字体排版标注首页文档标题和各页段落标题。"""++ for angle in sorted({line.angle for line in lines if line.semantic_type is None}):+ line_geometry = [+ (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))+ for line in lines+ if line.angle == angle and line.semantic_type is None+ ]+ if not line_geometry:+ continue+ median_height = statistics.median(+ _line_effective_height(line, bbox) for line, bbox in line_geometry+ )+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]+ local_page_height = page_size[0] if angle in {90, 270} else page_size[1]+ lanes = _infer_text_lanes(line_geometry, local_page_width, median_height)+ for lane in lanes:+ lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))++ document_title_bottom: float | None = None+ if page_index == 0:+ document_title_bottom = _classify_document_title(+ lanes,+ local_page_height,+ )+ preserve_front_matter_boundaries = _document_title_uses_page_fallback(+ lanes,+ )++ local_container_bboxes = [+ _rotate_bbox_to_upright(bbox, page_size, angle)+ for bbox in container_bboxes+ ]+ for lane in lanes:+ profile = _infer_lane_body_profile(lane)+ _classify_paragraph_titles_in_lane(+ lane,+ profile,+ local_page_height,+ local_container_bboxes,+ document_title_bottom=document_title_bottom,+ preserve_front_matter_boundaries=preserve_front_matter_boundaries,+ )+++def _infer_lane_body_profile(lane: _TextLane) -> _LaneBodyProfile:+ """从栏带的长行主体估计正文行高、主字体、字重、常规行距和样式占比。"""++ available = [item for item in lane.lines if item[0].semantic_type is None]+ if not available:+ return _LaneBodyProfile(1.0, None, None, 0.35, {})+ lane_width = max(0.1, lane.right - lane.left)+ long_lines = [item for item in available if item[1][2] - item[1][0] >= 0.45 * lane_width]+ body_rows = long_lines or available+ body_line_ids = {id(line) for line, _bbox in body_rows}+ body_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in body_rows)++ font_support: dict[tuple[str, int], float] = {}+ style_support: dict[tuple[str, int], float] = {}+ total_style_width = 0.0+ for line, bbox in available:+ if line.font_signature is None or line.font_coverage < 0.75:+ continue+ line_width = max(0.1, bbox[2] - bbox[0])+ style_support[line.font_signature] = style_support.get(line.font_signature, 0.0) + line_width+ total_style_width += line_width+ if id(line) in body_line_ids and 0.75 <= _line_effective_height(line, bbox) / body_height <= 1.35:+ font_support[line.font_signature] = font_support.get(line.font_signature, 0.0) + line_width+ body_font = max(font_support, key=font_support.get) if font_support else None+ if total_style_width > 0:+ style_support = {signature: width / total_style_width for signature, width in style_support.items()}++ body_weights = [+ line.dominant_font_weight+ for line, bbox in body_rows+ if line.dominant_font_weight is not None+ and (body_font is None or line.font_signature == body_font)+ and 0.75 <= _line_effective_height(line, bbox) / body_height <= 1.35+ ]+ regular_gap, _gap_mad = _estimate_lane_gap(lane)+ return _LaneBodyProfile(+ body_height=max(0.1, body_height),+ body_font=body_font,+ body_weight=statistics.median(body_weights) if body_weights else None,+ regular_gap=regular_gap,+ style_support=style_support,+ )+++def _classify_document_title(+ lanes: list[_TextLane],+ local_page_height: float,+) -> 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)+ )+ 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]+ for row_index, item in enumerate(available[:5]):+ line, bbox = item+ reference_height = min(profile.body_height, 1.25 * document_body_height)+ height_ratio = _line_effective_height(line, bbox) / max(0.1, reference_height)+ document_height_ratio = _line_effective_height(line, bbox) / max(+ 0.1,+ document_body_height,+ )+ width_ratio = (bbox[2] - bbox[0]) / lane_width+ centered = abs(_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) <= 0.15 * lane_width+ spans_columns_fallback = (+ lane.is_span+ and centered+ and width_ratio >= 0.65+ and document_height_ratio >= 1.3+ )+ if (+ _bbox_center_y(bbox) > 0.45 * local_page_height+ or (height_ratio < 1.4 and not spans_columns_fallback)+ or width_ratio < 0.2+ or (not centered and height_ratio < 1.7)+ ):+ continue+ top_preference = max(0.0, 0.45 - _bbox_center_y(bbox) / local_page_height)+ score = height_ratio + (0.75 if centered else 0.0) + top_preference - 0.05 * row_index+ candidates.append((score, lane, row_index, item))+ if not candidates:+ return None++ _score, lane, _row_index, anchor = max(candidates, key=lambda item: item[0])+ anchor_line, anchor_bbox = anchor+ anchor_height = _line_effective_height(anchor_line, anchor_bbox)+ anchor_line.semantic_type = "doc_title"+ selected = [anchor]+ ordered = lane.lines+ anchor_index = ordered.index(anchor)+ for direction in (-1, 1):+ index = anchor_index + direction+ previous_bbox = anchor_bbox+ while 0 <= index < len(ordered):+ candidate_line, candidate_bbox = ordered[index]+ if candidate_line.semantic_type is not None:+ break+ candidate_height = _line_effective_height(candidate_line, candidate_bbox)+ if not 0.8 <= candidate_height / anchor_height <= 1.25:+ break+ if not _title_fonts_compatible(anchor_line, candidate_line):+ break+ vertical_gap = max(candidate_bbox[1] - previous_bbox[3], previous_bbox[1] - candidate_bbox[3], 0.0)+ lane_width = max(0.1, lane.right - lane.left)+ centered = abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(anchor_bbox)) <= 0.18 * lane_width+ aligned = abs(candidate_bbox[0] - anchor_bbox[0]) <= 0.75 * anchor_height+ if vertical_gap > 1.1 * anchor_height or not (centered or aligned):+ break+ candidate_line.semantic_type = "doc_title"+ selected.append((candidate_line, candidate_bbox))+ previous_bbox = candidate_bbox+ index += direction+ return max(bbox[3] for _line, bbox in selected)+++def _document_title_uses_page_fallback(lanes: list[_TextLane]) -> bool:+ """判断首页标题是否依赖跨栏 1.30 倍全文正文行高兜底。"""++ title_heights = [+ _line_effective_height(line, bbox)+ for lane in lanes+ for line, bbox in lane.lines+ if line.semantic_type == "doc_title"+ ]+ column_body_heights = [+ _infer_lane_body_profile(lane).body_height+ for lane in lanes+ if not lane.is_span+ ]+ if not title_heights or not column_body_heights:+ return False+ document_body_height = statistics.median(column_body_heights)+ return any(+ 1.3 <= title_height / max(0.1, document_body_height) < 1.4+ for title_height in title_heights+ )+++def _classify_paragraph_titles_in_lane(+ lane: _TextLane,+ profile: _LaneBodyProfile,+ local_page_height: float,+ container_bboxes: list[BBox],+ *,+ document_title_bottom: float | None,+ preserve_front_matter_boundaries: bool,+) -> None:+ """以字号、样式、留白、对齐、栏宽和容器邻接判定段落标题。"""++ lane_width = max(0.1, lane.right - lane.left)+ rows = lane.lines+ selected_indices: set[int] = set()+ front_matter_boundary = _infer_front_matter_boundary(+ lane,+ profile,+ local_page_height,+ document_title_bottom=document_title_bottom,+ )+ for index, (line, bbox) in enumerate(rows):+ if line.semantic_type is not None:+ continue+ if not 0.07 * local_page_height <= _bbox_center_y(bbox) <= 0.93 * local_page_height:+ continue+ inside_front_matter = (+ front_matter_boundary is not None+ and _bbox_center_y(bbox) <= front_matter_boundary+ )+ if inside_front_matter and not preserve_front_matter_boundaries:+ continue+ if _line_near_visual_container(bbox, container_bboxes, profile.body_height):+ continue++ line_height = _line_effective_height(line, bbox)+ height_ratio = line_height / profile.body_height+ width_ratio = (bbox[2] - bbox[0]) / lane_width+ centered = abs(_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) <= 0.12 * lane_width+ left_aligned = abs(bbox[0] - lane.left) <= 0.65 * profile.body_height+ style_differs = (+ profile.body_font is not None+ and line.font_signature is not None+ and line.font_coverage >= 0.75+ and line.font_signature != profile.body_font+ )+ style_support = profile.style_support.get(line.font_signature, 1.0) if line.font_signature is not None else 1.0+ weight_emphasized = (+ profile.body_weight is not None+ and line.dominant_font_weight is not None+ and line.dominant_font_weight >= max(profile.body_weight + 100.0, 1.15 * profile.body_weight)+ )+ gap_above = _normalized_title_gap(rows, index, direction=-1, body_height=profile.body_height)+ gap_below = _normalized_title_gap(rows, index, direction=1, body_height=profile.body_height)+ has_spacing_signal = gap_above >= 0.35++ if _visual_row_has_body_style_sibling(rows, index):+ continue+ if _is_near_full_mixed_inline_row(+ rows,+ index,+ lane_width,+ profile,+ ):+ continue+ if (+ index > 0+ and rows[index - 1][0].semantic_type == "paragraph_title"+ and width_ratio >= 0.85+ and gap_above < 1.0+ and not _title_fonts_compatible(rows[index - 1][0], line)+ ):+ continue+ if height_ratio < 0.9 and not inside_front_matter and not _has_following_body_row(+ rows,+ index,+ lane_width,+ profile,+ ):+ continue+ if width_ratio >= 0.9 and height_ratio < 1.15 and not (+ style_differs and gap_above >= 0.65+ ):+ continue+ score = 0.0+ if style_differs:+ score += 2.0+ if style_support <= 0.2:+ score += 0.75+ if weight_emphasized:+ score += 1.0+ if height_ratio >= 1.18:+ score += 2.0+ elif height_ratio <= 0.9 and centered:+ score += 0.75+ if width_ratio <= 0.78:+ score += 0.75+ if centered and width_ratio <= 0.85:+ score += 1.25+ if gap_above >= 0.65:+ score += 1.25+ elif gap_above >= 0.35:+ score += 0.5+ if gap_below >= 0.35:+ score += 0.75+ if left_aligned:+ score += 0.25++ strong_layout_signal = (+ height_ratio >= 1.18+ or style_differs+ or weight_emphasized+ or (centered and width_ratio <= 0.7 and gap_above >= 0.35 and gap_below >= 0.2)+ )+ if score >= 4.0 and has_spacing_signal and strong_layout_signal:+ if _is_full_width_inline_heading(+ rows,+ index,+ lane_width,+ profile,+ ):+ continue+ line.semantic_type = "paragraph_title"+ selected_indices.add(index)++ _unify_visual_row_title_types(+ lane,+ selected_indices,+ )+ _expand_paragraph_title_neighbors(+ lane,+ selected_indices,+ profile,+ )+ if front_matter_boundary is not None and preserve_front_matter_boundaries:+ _protect_front_matter_title_types(+ lane,+ profile,+ front_matter_boundary,+ )+++def _protect_front_matter_title_types(+ lane: _TextLane,+ profile: _LaneBodyProfile,+ front_matter_boundary: float,+) -> None:+ """把作者区误命中的标题降为正文,并仅保留原本需要跨行聚合的内部标记。"""++ front_title_indices = [+ index+ for index, (line, bbox) in enumerate(lane.lines)+ if line.semantic_type == "paragraph_title"+ and _bbox_center_y(bbox) <= front_matter_boundary+ ]+ connected_indices: set[int] = set()+ for position, first_index in enumerate(front_title_indices):+ for second_index in front_title_indices[position + 1 :]:+ if _should_connect_semantic_rows(+ lane.lines[first_index],+ lane.lines[second_index],+ lane,+ profile.regular_gap,+ [],+ [],+ ):+ connected_indices.update((first_index, second_index))+ for index in front_title_indices:+ lane.lines[index][0].semantic_type = (+ "text" if index in connected_indices else None+ )+++def _visual_row_has_body_style_sibling(+ rows: list[tuple[_LineItem, BBox]],+ index: int,+) -> bool:+ """检查同一完整视觉行是否同时包含标题样式与正文样式 run。"""++ line, _bbox = rows[index]+ if line.visual_row_id is None:+ return False+ siblings = [+ sibling+ for sibling, _sibling_bbox in rows+ if sibling is not line and sibling.visual_row_id == line.visual_row_id+ ]+ return any(not _title_fonts_compatible(line, sibling) for sibling in siblings)+++def _is_near_full_mixed_inline_row(+ rows: list[tuple[_LineItem, BBox]],+ index: int,+ lane_width: float,+ profile: _LaneBodyProfile,+) -> bool:+ """识别近满栏混合字体行内强调,避免把粗体条目头单独标成标题。"""++ line, bbox = rows[index]+ line_height = _line_effective_height(line, bbox)+ if (+ line.font_coverage >= 0.95+ or (bbox[2] - bbox[0]) < 0.85 * lane_width+ or not 0.85 <= line_height / profile.body_height <= 1.15+ or index + 1 >= len(rows)+ ):+ return False+ next_line, next_bbox = rows[index + 1]+ next_height = _line_effective_height(next_line, next_bbox)+ gap_below = _effective_text_row_gap(rows[index], rows[index + 1])+ return (+ next_line.semantic_type is None+ and 0.8 <= next_height / profile.body_height <= 1.2+ and gap_below <= profile.regular_gap + 0.25 * profile.body_height+ )+++def _is_full_width_inline_heading(+ rows: list[tuple[_LineItem, BBox]],+ index: int,+ lane_width: float,+ profile: _LaneBodyProfile,+) -> bool:+ """识别后接常规正文续行的满栏正常字号行内标题。"""++ line, bbox = rows[index]+ line_height = _line_effective_height(line, bbox)+ if (+ not 0.85 <= line_height / profile.body_height <= 1.15+ or (bbox[2] - bbox[0]) < 0.9 * lane_width+ or index + 1 >= len(rows)+ ):+ return False++ next_line, next_bbox = rows[index + 1]+ next_height = _line_effective_height(next_line, next_bbox)+ next_uses_body_font = (+ profile.body_font is None+ or next_line.font_signature is None+ or next_line.font_coverage < 0.75+ or next_line.font_signature == profile.body_font+ )+ return (+ next_line.semantic_type is None+ and next_uses_body_font+ and 0.75 <= next_height / profile.body_height <= 1.15+ and (next_bbox[2] - next_bbox[0]) >= 0.75 * lane_width+ and _effective_text_row_gap(rows[index], rows[index + 1])+ <= profile.regular_gap + 0.25 * profile.body_height+ )+++def _has_following_body_row(+ rows: list[tuple[_LineItem, BBox]],+ index: int,+ lane_width: float,+ profile: _LaneBodyProfile,+) -> bool:+ """检查小字号候选下方是否仍有正常字号的正文续行。"""++ for line, bbox in rows[index + 1 :]:+ height_ratio = _line_effective_height(line, bbox) / profile.body_height+ width_ratio = (bbox[2] - bbox[0]) / lane_width+ if 0.9 <= height_ratio <= 1.2 and width_ratio >= 0.45:+ return True+ return False+++def _unify_visual_row_title_types(+ lane: _TextLane,+ selected_indices: set[int],+) -> None:+ """按完整 visual_row_id 统一标题类型:同样式整行晋升,混合样式整行降级。"""++ row_indices: dict[int, list[int]] = {}+ for index, (line, _bbox) in enumerate(lane.lines):+ if line.visual_row_id is not None:+ row_indices.setdefault(line.visual_row_id, []).append(index)+ for indices in row_indices.values():+ title_indices = [+ index+ for index in indices+ if lane.lines[index][0].semantic_type == "paragraph_title"+ ]+ if not title_indices:+ continue+ anchor_line, anchor_bbox = lane.lines[title_indices[0]]+ anchor_height = _line_effective_height(anchor_line, anchor_bbox)+ compatible = all(+ 0.75+ <= _line_effective_height(lane.lines[index][0], lane.lines[index][1])+ / anchor_height+ <= 1.25+ and _title_fonts_compatible(anchor_line, lane.lines[index][0])+ for index in indices+ )+ if compatible:+ for index in indices:+ lane.lines[index][0].semantic_type = "paragraph_title"+ selected_indices.add(index)+ continue+ for index in title_indices:+ lane.lines[index][0].semantic_type = None+ selected_indices.discard(index)+++def _infer_front_matter_boundary(+ lane: _TextLane,+ profile: _LaneBodyProfile,+ local_page_height: float,+ *,+ document_title_bottom: float | None,+) -> float | None:+ """用短行后衔接满栏正文的几何转折点界定首页作者等前置信息。"""++ if document_title_bottom is None:+ return None+ default_boundary = max(+ document_title_bottom + 2.5 * profile.body_height,+ 0.39 * local_page_height,+ )+ lane_width = max(0.1, lane.right - lane.left)+ for index, (line, bbox) in enumerate(lane.lines[:-1]):+ if bbox[1] <= document_title_bottom:+ continue+ next_line, next_bbox = lane.lines[index + 1]+ width_ratio = (bbox[2] - bbox[0]) / lane_width+ next_width_ratio = (next_bbox[2] - next_bbox[0]) / lane_width+ left_aligned = abs(bbox[0] - lane.left) <= 0.65 * profile.body_height+ centered = abs(+ _bbox_center_x(bbox) - (lane.left + lane.right) / 2.0+ ) <= 0.12 * lane_width+ next_height_ratio = _line_effective_height(next_line, next_bbox) / profile.body_height+ gap_below = max(0.0, _effective_text_row_gap((line, bbox), (next_line, next_bbox)))+ if (+ width_ratio <= 0.35+ and next_width_ratio >= 0.75+ and (left_aligned or centered)+ and 0.75 <= next_height_ratio <= 1.35+ and gap_below <= 1.5 * profile.body_height+ ):+ return min(default_boundary, bbox[1] - 0.1)+ return default_boundary+++def _normalized_title_gap(+ rows: list[tuple[_LineItem, BBox]],+ index: int,+ *,+ direction: Literal[-1, 1],+ body_height: float,+) -> float:+ """返回标题候选与相邻物理行之间按正文行高归一化的有效净空。"""++ neighbor_index = index + direction+ if not 0 <= neighbor_index < len(rows):+ return 0.5+ if direction < 0:+ gap = _effective_text_row_gap(rows[neighbor_index], rows[index])+ else:+ gap = _effective_text_row_gap(rows[index], rows[neighbor_index])+ return max(0.0, gap) / max(0.1, body_height)+++def _line_near_visual_container(+ line_bbox: BBox,+ container_bboxes: list[BBox],+ body_height: float,+) -> bool:+ """检查短行是否紧邻图、表等容器,以纯几何方式抑制 caption 误判。"""++ for container_bbox in container_bboxes:+ if _bbox_axis_overlap_ratio(line_bbox, container_bbox, axis="x") < 0.35:+ continue+ vertical_gap = max(line_bbox[1] - container_bbox[3], container_bbox[1] - line_bbox[3], 0.0)+ if vertical_gap <= 1.5 * body_height:+ return True+ return False+++def _expand_paragraph_title_neighbors(+ lane: _TextLane,+ selected_indices: set[int],+ profile: _LaneBodyProfile,+) -> None:+ """用相邻行的字体、尺寸、对齐和紧凑净空补齐折行段落标题。"""++ if not selected_indices:+ return+ rows = lane.lines+ lane_width = max(0.1, lane.right - lane.left)+ pending = list(selected_indices)+ while pending:+ selected_index = pending.pop()+ selected_line, selected_bbox = rows[selected_index]+ selected_height = _line_effective_height(selected_line, selected_bbox)+ for candidate_index in (selected_index - 1, selected_index + 1):+ if not 0 <= candidate_index < len(rows) or candidate_index in selected_indices:+ continue+ candidate_line, candidate_bbox = rows[candidate_index]+ if candidate_line.semantic_type is not None:+ continue+ candidate_height = _line_effective_height(candidate_line, candidate_bbox)+ if not 0.75 <= candidate_height / selected_height <= 1.25:+ continue+ if candidate_bbox[2] - candidate_bbox[0] > 0.8 * lane_width:+ continue+ if not _title_fonts_compatible(selected_line, candidate_line):+ continue+ vertical_gap = max(+ candidate_bbox[1] - selected_bbox[3],+ selected_bbox[1] - candidate_bbox[3],+ 0.0,+ )+ centers_align = abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(selected_bbox)) <= 0.15 * lane_width+ left_edges_align = abs(candidate_bbox[0] - selected_bbox[0]) <= 0.75 * profile.body_height+ wrapped_indent = abs(candidate_bbox[0] - selected_bbox[0]) <= 2.0 * profile.body_height+ if vertical_gap > 0.65 * profile.body_height or not (+ centers_align or left_edges_align or wrapped_indent+ ):+ continue+ candidate_line.semantic_type = "paragraph_title"+ selected_indices.add(candidate_index)+ pending.append(candidate_index)+diff --git a/mineru/backend/flash/pdf_extractor.py b/mineru/backend/flash/pdf_extractor.pyindex 70064f09..98748f4f 100644--- a/mineru/backend/flash/pdf_extractor.py+++ b/mineru/backend/flash/pdf_extractor.py@@ -1,5410 +1,38 @@-"""Flash PDF 原生文本与表格提取器。+# Copyright (c) Opendatalab. All rights reserved.-Flash 仅处理 PDF 原生文本;需要 OCR 时统一委托 Hybrid low。-"""--from __future__ import annotations--import math-import re-import statistics-import unicodedata-from dataclasses import dataclass, field, replace-from difflib import SequenceMatcher-from typing import Any, Literal, Sequence--from loguru import logger-from pdftext.schema import Char--from mineru.backend.hybrid.table_text import project_pdf_table_text-from mineru.backend.utils.char_utils import is_hyphen_at_line_end, resolve_text_line_boundary-from mineru.backend.utils.xycut_pp_sorter import sort_entries-from mineru.cli_old.common import read_fn-from mineru.types import BBox-from mineru.utils.language import detect_lang-from mineru.utils.pdf_document import PDFDocument, get_lines_from_chars---_TABLE_CAPTION_RE = re.compile(- r"^(?:table|tab\.?|表格?)[\s:.–—-]*(?:\d+|[ivxlcdm]+|[一二三四五六七八九十]+)\b(?P<suffix>.*)$",- re.IGNORECASE,-)-_TABLE_NOTE_RE = re.compile(- r"^(?:notes?|sources?)\b|^(?:注释?|说明)\s*[::]?|^for\s+[*†‡]"- r"|^(?:\d+|[*†‡])\s+\S"- r"|^(?:[*†‡]|[a-z]|p|t|ns|na)\s+(?:indicates?|denotes?|rainfall\b|total\b|low\b|for\b)",- re.IGNORECASE,-)-_TABLE_SPLIT_NUMBER_RE = re.compile(- r"^(?:\d+|[ivxlcdm]+|[一二三四五六七八九十]+)[.::]?$",- re.IGNORECASE,-)-_FORMULA_NUMBER_SUFFIX_RE = re.compile(- r"^(?P<prefix>.*?)(?P<marker>[((﹙][^()()﹙﹚\r\n]+[))﹚])\s*$"-)-_PDF_CONTROL_CHAR_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")-_MIN_RASTER_IMAGE_PAGE_AREA_RATIO = 0.005-_MIN_FORM_IMAGE_PAGE_AREA_RATIO = 0.01-_MAX_FORM_IMAGE_PAGE_AREA_RATIO = 0.8-_IMAGE_CONTAINER_OVERLAP_THRESHOLD = 0.5-_TEXT_SEMANTIC_TYPES = {- "doc_title",- "paragraph_title",- "header",- "footer",- "page_number",- "page_footnote",- "aside_text",-}-_OUTPUT_BLOCK_TYPES = {"text", "table", "image", "equation"} | _TEXT_SEMANTIC_TYPES-_PAGE_NUMBER_RE = re.compile(- r"^\s*(?:page\s*)?[\-\u2013\u2014\u00b7\u2022]*\s*(?:\u7b2c\s*)?"- r"(?P<value>\d{1,4}|[ivxlcdm]+|[\u3007\u96f6\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u4e24]+)"- r"(?:\s*(?:/|of|\u5171)\s*(?:\d{1,4}|[ivxlcdm]+|[\u3007\u96f6\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u4e24]+))?"- r"\s*(?:\u9875)?\s*[\-\u2013\u2014\u00b7\u2022]*\s*$",- re.IGNORECASE,-)---@dataclass(slots=True)-class _LineItem:- """保存单个可视文本行及其原始几何信息。"""-- text: str- bbox: BBox- angle: int- source_index: int- chars: list[Char] = field(default_factory=list)- visual_row_id: int | None = None- run_index: int = 0- effective_height: float = 0.0- font_signature: tuple[str, int] | None = None- font_coverage: float = 0.0- dominant_font_weight: float | None = None- median_glyph_width: float | None = None- split_from_row: bool = False- semantic_type: str | None = None---@dataclass(slots=True)-class _Fragment:- """保存表格规则使用的单元文本片段。"""-- text: str- bbox: BBox- local_bbox: BBox- line_index: int- visual_row_id: int | None = None---@dataclass(slots=True)-class _VisualRow:- """保存同一局部水平带内的表格片段。"""-- fragments: list[_Fragment]- center_y: float- bbox: BBox- visual_row_id: int | None = None---@dataclass(slots=True)-class _AxisLine:- """保存 PDF 路径中的横竖线。"""-- bbox: BBox- width: float- orientation: Literal["horizontal", "vertical"]---@dataclass(slots=True)-class _LocalAxisLine:- """保存转入当前文本方向后的横竖线。"""-- bbox: BBox- original_bbox: BBox- orientation: Literal["horizontal", "vertical"]- width: float---@dataclass(slots=True)-class _TableCandidate:- """保存已通过三横线与文本分布校验的表格候选。"""-- bbox: BBox- local_bbox: BBox- angle: int- score: float- core_bbox: BBox | None = None- line_indices: set[int] = field(default_factory=set)---@dataclass(slots=True)-class _GraphicCandidate:- """保存由紧凑绘图线组件形成的图形文本容器候选。"""-- core_bbox: BBox- lane_index: int- line_indices: set[int] = field(default_factory=set)---@dataclass(slots=True)-class _TextLane:- """保存同一文本方向下的局部栏带与已归属文本行。"""-- left: float- right: float- lines: list[tuple[_LineItem, BBox]] = field(default_factory=list)- is_span: bool = False---@dataclass(slots=True)-class _FormulaAnchor:- """保存公式右缘锚点及其是否落在正文密集区下方。"""-- line: _LineItem- bbox: BBox- detached_below_body: bool = False---@dataclass(slots=True)-class _PageSource:- """保存单页原生文本分析所需的文本、字符、绘图线和视觉容器。"""-- page_size: tuple[float, float]- lines: list[_LineItem]- chars: list[Char]- drawing_lines: list[_AxisLine]- image_bboxes: list[BBox] = field(default_factory=list)- form_bboxes: list[BBox] = field(default_factory=list)---@dataclass(slots=True)-class _PreparedPage:- """保存容器认领完成后、等待跨页与文本类型判定的轻量页面。"""-- page_size: tuple[float, float]- remaining_lines: list[_LineItem]- table_bboxes: list[BBox]- drawing_lines: list[_AxisLine]- fixed_blocks: list[dict[str, Any]]- page_footnote_groups: list[set[int]] = field(default_factory=list)---@dataclass(slots=True)-class _MarginalCandidate:- """保存页眉页脚带中的单行候选及其正向归一化几何。"""-- page_index: int- line: _LineItem- local_bbox: BBox- local_page_size: tuple[float, float]- region: Literal["header", "footer", "side"]---@dataclass(slots=True)-class _LaneBodyProfile:- """保存标题判定使用的栏带正文排版基线,不包含文本内容特征。"""-- body_height: float- body_font: tuple[str, int] | None- body_weight: float | None- regular_gap: float- style_support: dict[tuple[str, int], float]---def extract_pages_text(filepath: str, start_page: int = 0, end_page: int | None = None) -> list[str]:- """Extract plain text from each PDF page, preserving empty pages."""-- pages: list[str] = []- with PDFDocument(filepath) as pdf_doc:- page_count = pdf_doc.page_count- end = page_count if end_page is None else min(end_page, page_count)-- # 保留旧 Flash parser 依赖的逐页纯文本接口。- for page_idx in range(start_page, end):- pages.append(pdf_doc.get_page_text(page_idx))- return pages---def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]:- """逐页读取数字 PDF,并在轻量页面上完成跨页文本类型判定。"""-- prepared_pages: list[_PreparedPage] = []- for page_idx in range(pdf_doc.page_count):- page_size = pdf_doc.page_size(page_idx)- chars = pdf_doc.get_page_chars(page_idx)- lines = _build_native_line_items(- get_lines_from_chars(chars),- page_size,- page_rotation=pdf_doc.page_rotation(page_idx),- )- drawing_lines = _get_pdf_drawing_lines(pdf_doc, page_idx)- source = _PageSource(- page_size=page_size,- lines=lines,- chars=chars,- drawing_lines=drawing_lines,- image_bboxes=pdf_doc.get_page_image_bboxes(page_idx),- form_bboxes=pdf_doc.get_page_form_bboxes(page_idx),- )- prepared_pages.append(_prepare_page_source(source))-- _classify_repeated_page_marginals(prepared_pages)- return [- _finalize_prepared_page(prepared, page_index)- for page_index, prepared in enumerate(prepared_pages)- ]---def _build_native_line_items(- pdf_lines: Sequence[dict[str, Any]],- page_size: tuple[float, float],- *,- page_rotation: int = 0,-) -> list[_LineItem]:- """将 pdftext 粗行按字符间隙精修成 Flash 视觉 run。"""-- items: list[_LineItem] = []- for visual_row_id, pdf_line in enumerate(pdf_lines):- bbox = _clip_bbox(_coerce_bbox(pdf_line.get("bbox")), page_size)- if bbox is None:- continue- spans = pdf_line.get("spans") or []- chars = [char for span in spans for char in (span.get("chars") or []) if isinstance(char, dict)]- coarse_item = _LineItem(- text="".join(str(span.get("text") or "") for span in spans),- bbox=bbox,- angle=(_normalize_pdftext_angle(pdf_line.get("rotation")) + int(page_rotation or 0)) % 360,- source_index=-1,- chars=chars,- visual_row_id=visual_row_id,- )- items.extend(_split_native_visual_runs(coarse_item, page_size))-- merged_items = _merge_native_inline_scripts(items, page_size)- for source_index, item in enumerate(merged_items):- # source_index 必须在页内唯一,表格投影和失败回滚都依赖该精确成员标识。- item.source_index = source_index- return merged_items---def _split_native_visual_runs(- line: _LineItem,- page_size: tuple[float, float],-) -> list[_LineItem]:- """保留字符源顺序与空白信息,并将一个 pdftext 粗行拆成远距视觉 run。"""-- tokens: list[tuple[Char, str, BBox | None, BBox | None]] = []- for char in line.chars:- raw_char = str(char.get("char") or "")- if raw_char in {"\r", "\n"}:- continue- bbox = _clip_bbox(_coerce_bbox(char.get("bbox")), page_size)- local_bbox = _rotate_bbox_to_upright(bbox, page_size, line.angle) if bbox is not None else None- tokens.append((char, raw_char, bbox, local_bbox))-- visible_indices = [- index- for index, (_char, raw_char, _bbox, local_bbox) in enumerate(tokens)- if raw_char.isprintable() and not raw_char.isspace() and local_bbox is not None- ]- if not visible_indices:- text = _normalize_native_run_text(line.text)- if not text:- return []- local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, line.angle)- line.text = text- line.effective_height = max(0.1, local_bbox[3] - local_bbox[1])- return [line]-- glyph_widths = [- max(0.1, tokens[index][3][2] - tokens[index][3][0]) # type: ignore[index]- for index in visible_indices- ]- median_glyph_width = statistics.median(glyph_widths)- local_page_width = page_size[1] if line.angle in {90, 270} else page_size[0]- hard_gap_threshold = max(15.0, 3.0 * median_glyph_width, 0.02 * local_page_width)- adjacent_gaps: list[float] = []- for previous, current in zip(visible_indices, visible_indices[1:]):- previous_bbox = tokens[previous][3]- current_bbox = tokens[current][3]- if previous_bbox is None or current_bbox is None:- continue- gap = _horizontal_bbox_gap(previous_bbox, current_bbox)- if gap < hard_gap_threshold:- adjacent_gaps.append(gap)- # 少于三个相邻样本无法可靠代表“常规”字距;零间隙也是真实的紧排字距,- # 必须纳入统计,避免唯一的 15pt cell gap 反过来抬高软拆阈值。- median_regular_gap = statistics.median(adjacent_gaps) if len(adjacent_gaps) >= 3 else 0.0-- split_indices: list[int] = []- for previous, current in zip(visible_indices, visible_indices[1:]):- previous_bbox = tokens[previous][3]- current_bbox = tokens[current][3]- if previous_bbox is None or current_bbox is None:- continue- gap = _horizontal_bbox_gap(previous_bbox, current_bbox)- has_source_whitespace = any(tokens[index][1].isspace() for index in range(previous + 1, current))- soft_gap_threshold = max(- 8.0,- 2.2 * median_glyph_width,- 3.0 * median_regular_gap,- )- if gap >= hard_gap_threshold or (has_source_whitespace and gap >= soft_gap_threshold):- split_indices.append(current)-- ranges: list[tuple[int, int]] = []- start = 0- for split_index in split_indices:- ranges.append((start, split_index))- start = split_index- ranges.append((start, len(tokens)))-- output: list[_LineItem] = []- for run_index, (start, end) in enumerate(ranges):- run_tokens = tokens[start:end]- run_text = _normalize_native_run_text("".join(token[1] for token in run_tokens))- run_bboxes = [- token[2]- for token in run_tokens- if token[2] is not None and token[1].isprintable() and not token[1].isspace()- ]- if not run_text or not run_bboxes:- continue- run_chars = [token[0] for token in run_tokens]- run_item = _LineItem(- text=run_text,- bbox=_bbox_union_many(run_bboxes),- angle=line.angle,- source_index=-1,- chars=run_chars,- visual_row_id=line.visual_row_id,- run_index=run_index,- split_from_row=len(ranges) > 1,- )- _fill_native_typography(run_item, page_size)- output.append(run_item)- return output---def _horizontal_bbox_gap(first_bbox: BBox, second_bbox: BBox) -> float:- """返回两个局部 bbox 在 x 轴上的无方向净空,重叠时为零。"""-- return max(first_bbox[0] - second_bbox[2], second_bbox[0] - first_bbox[2], 0.0)---def _normalize_native_run_text(text: str) -> str:- """清理原生 run 文本,并把字母后的 PDF 软断词标记转换成 ASCII hyphen。"""-- normalized = text.replace("\r\n", "\n").replace("\r", "\n")- normalized = re.sub(r"(?<=[A-Za-z])\x02(?=\s*$)", "-", normalized)- normalized = _sanitize_pdf_control_text(normalized, preserve_newlines=False)- normalized = re.sub(r"[\t\f\v ]+", " ", normalized)- return normalized.strip()---def _sanitize_pdf_control_text(text: str, *, preserve_newlines: bool) -> str:- """删除 PDF 字体编码残留控制字符,并按调用场景决定是否保留物理换行。"""-- normalized = str(text or "").replace("\r\n", "\n").replace("\r", "\n")- normalized = re.sub(r"(?<=[A-Za-z])\x02(?=[\t ]*(?:\n|$))", "-", normalized)- normalized = normalized.replace("\t", " ")- if not preserve_newlines:- normalized = normalized.replace("\n", "")- return _PDF_CONTROL_CHAR_RE.sub("", normalized)---def _fill_native_typography(line: _LineItem, page_size: tuple[float, float]) -> None:- """使用非空字符 bbox 高度和 dominant font 填充原生行排版特征。"""-- heights: list[float] = []- glyph_widths: list[float] = []- font_counts: dict[tuple[str, int], int] = {}- font_weights: dict[tuple[str, int], list[float]] = {}- valid_font_chars = 0- for char in line.chars:- raw_char = str(char.get("char") or "")- if not raw_char.isprintable() or raw_char.isspace():- continue- bbox = _clip_bbox(_coerce_bbox(char.get("bbox")), page_size)- if bbox is None:- continue- local_bbox = _rotate_bbox_to_upright(bbox, page_size, line.angle)- heights.append(max(0.1, local_bbox[3] - local_bbox[1]))- glyph_widths.append(max(0.1, local_bbox[2] - local_bbox[0]))- font = char.get("font") or {}- font_name = str(font.get("name") or "")- if not font_name:- continue- try:- font_flags = int(font.get("flags") or 0)- except (TypeError, ValueError):- font_flags = 0- signature = (font_name, font_flags)- font_counts[signature] = font_counts.get(signature, 0) + 1- try:- font_weight = float(font.get("weight"))- except (TypeError, ValueError):- font_weight = math.nan- if math.isfinite(font_weight):- font_weights.setdefault(signature, []).append(font_weight)- valid_font_chars += 1-- local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, line.angle)- line.effective_height = statistics.median(heights) if heights else max(0.1, local_bbox[3] - local_bbox[1])- line.median_glyph_width = statistics.median(glyph_widths) if glyph_widths else None- if font_counts and valid_font_chars:- line.font_signature, dominant_count = max(font_counts.items(), key=lambda item: item[1])- line.font_coverage = dominant_count / valid_font_chars- dominant_weights = font_weights.get(line.font_signature, [])- line.dominant_font_weight = statistics.median(dominant_weights) if dominant_weights else None- else:- line.font_signature = None- line.font_coverage = 0.0- line.dominant_font_weight = None---def _merge_native_inline_scripts(- lines: list[_LineItem],- page_size: tuple[float, float],-) -> list[_LineItem]:- """以 mutual-nearest 规则把跨粗行的小字号前后置标记合入主体视觉行。"""-- candidates: list[tuple[float, int, int, Literal["prefix", "suffix"]]] = []- for small_index, small in enumerate(lines):- compact_text = "".join(char for char in small.text if not char.isspace())- if not compact_text:- continue- small_local_bbox = _rotate_bbox_to_upright(small.bbox, page_size, small.angle)- for base_index, base in enumerate(lines):- if small_index == base_index or small.angle != base.angle or small.visual_row_id == base.visual_row_id:- continue- if small.effective_height <= 0 or base.effective_height <= 0:- continue- height_ratio = small.effective_height / base.effective_height- if not 0.35 <= height_ratio <= 0.8:- continue- if len(compact_text) > 8 and small_local_bbox[2] - small_local_bbox[0] > 3.0 * base.effective_height:- continue- base_local_bbox = _rotate_bbox_to_upright(base.bbox, page_size, base.angle)- vertical_overlap = max(- 0.0,- min(small_local_bbox[3], base_local_bbox[3]) - max(small_local_bbox[1], base_local_bbox[1]),- )- small_height = max(0.1, small_local_bbox[3] - small_local_bbox[1])- overlap_ratio = vertical_overlap / small_height- if overlap_ratio < 0.5:- continue- center_offset = abs(_bbox_center_y(small_local_bbox) - _bbox_center_y(base_local_bbox))- if center_offset < max(0.5, 0.12 * base.effective_height):- # 同基线居中的小字号文本更可能是表格相邻 cell,而不是上下标。- continue- gap_limit = max(1.5, 0.35 * base.effective_height)- edge_options: list[tuple[float, Literal["prefix", "suffix"], float]] = []- for position, gap in (- ("prefix", base_local_bbox[0] - small_local_bbox[2]),- ("suffix", small_local_bbox[0] - base_local_bbox[2]),- ):- if -0.35 * base.effective_height <= gap <= gap_limit:- edge_options.append((abs(gap), position, gap))- if not edge_options:- continue- _edge_distance, position, gap = min(edge_options, key=lambda item: item[0])-- outside_offset = max(- base_local_bbox[1] - small_local_bbox[1],- small_local_bbox[3] - base_local_bbox[3],- )- tightly_attached = abs(gap) <= max(1.0, 0.1 * base.effective_height)- if outside_offset < max(0.5, 0.08 * base.effective_height) and not tightly_attached:- # 紧贴边缘的小字号上下标可能完全落入高字形 bbox;其余内嵌小字仍按普通 cell 排除。- continue- metric = abs(gap) + (1.0 - overlap_ratio) * base.effective_height- candidates.append((metric, small_index, base_index, position))-- best_base_for_small: dict[int, tuple[float, int, Literal["prefix", "suffix"]]] = {}- best_small_for_base: dict[tuple[int, str], tuple[float, int]] = {}- for metric, small_index, base_index, position in candidates:- if small_index not in best_base_for_small or metric < best_base_for_small[small_index][0]:- best_base_for_small[small_index] = (metric, base_index, position)- base_key = (base_index, position)- if base_key not in best_small_for_base or metric < best_small_for_base[base_key][0]:- best_small_for_base[base_key] = (metric, small_index)-- matches: dict[int, dict[str, int]] = {}- for small_index, (_metric, base_index, position) in best_base_for_small.items():- if best_small_for_base.get((base_index, position), (math.inf, -1))[1] == small_index:- matches.setdefault(base_index, {})[position] = small_index-- consumed_small_indices = {small_index for positions in matches.values() for small_index in positions.values()}- merged_base_indices: set[int] = set()-- def merge_children(base_index: int, visiting: set[int]) -> None:- """先合并更小的依赖标记,再把当前完整节点递归合入更大的主体行。"""-- if base_index in merged_base_indices or base_index in visiting:- return- visiting.add(base_index)- positions = matches.get(base_index, {})- for child_index in positions.values():- merge_children(child_index, visiting)- base = lines[base_index]- merged_bbox = base.bbox- merged_chars = list(base.chars)- if "prefix" in positions:- prefix_index = positions["prefix"]- prefix = lines[prefix_index]- base.text = f"{prefix.text.strip()} {base.text.lstrip()}"- merged_bbox = _bbox_union(merged_bbox, prefix.bbox)- merged_chars = [*prefix.chars, *merged_chars]- base.split_from_row = base.split_from_row or prefix.split_from_row- if "suffix" in positions:- suffix_index = positions["suffix"]- suffix = lines[suffix_index]- base.text = f"{base.text.rstrip()}{suffix.text.strip()}"- merged_bbox = _bbox_union(merged_bbox, suffix.bbox)- merged_chars.extend(suffix.chars)- base.split_from_row = base.split_from_row or suffix.split_from_row- base.bbox = merged_bbox- base.chars = merged_chars- _fill_native_typography(base, page_size)- visiting.remove(base_index)- merged_base_indices.add(base_index)-- # 从最终不会被消费的根主体开始,确保 small -> medium -> large 链不会丢失最小节点。- root_base_indices = [base_index for base_index in matches if base_index not in consumed_small_indices]- for base_index in root_base_indices:- merge_children(base_index, set())- for base_index in matches:- merge_children(base_index, set())-- output = [line for index, line in enumerate(lines) if index not in consumed_small_indices]- output.sort(key=lambda item: (item.visual_row_id if item.visual_row_id is not None else math.inf, item.run_index))- return output---def _normalize_pdftext_angle(value: Any) -> int:- """将 pdftext 弧度方向就近归一到四个标准角度。"""-- try:- angle_radians = float(value or 0.0)- except (TypeError, ValueError):- return 0- angle_degrees = math.degrees(angle_radians)- normalized = int(round(angle_degrees / 90.0) * 90) % 360- return normalized if normalized in {0, 90, 180, 270} else 0---def _get_pdf_drawing_lines(pdf_doc: PDFDocument, page_idx: int) -> list[_AxisLine]:- """读取 PDFDocument 的公共绘图线结果,并隔离具体 PDFium 类型。"""-- output: list[_AxisLine] = []- for drawing_line in pdf_doc.get_page_drawing_lines(page_idx):- bbox = _coerce_bbox(drawing_line.bbox)- if bbox is None:- continue- output.append(- _AxisLine(- bbox=bbox,- width=max(0.0, float(drawing_line.width)),- orientation=drawing_line.orientation,- )- )- return output---def _prepare_page_source(source: _PageSource) -> _PreparedPage:- """先认领视觉容器,再标注辅助文本并留下可跨页比较的轻量文本行。"""-- form_bboxes = _select_form_image_bboxes(source)- candidates = [- candidate- for candidate in _detect_table_candidates(source)- if not any(- _form_supersedes_nested_bbox(form_bbox, candidate.bbox)- for form_bbox in form_bboxes- )- ]- table_blocks, claimed_line_indices = _materialize_table_blocks(- source,- candidates,- )- table_bboxes = [block["bbox"] for block in table_blocks]- active_form_bboxes = [- form_bbox- for form_bbox in form_bboxes- if not any(- _bbox_overlap_in_smaller(form_bbox, table_bbox)- >= _IMAGE_CONTAINER_OVERLAP_THRESHOLD- for table_bbox in table_bboxes- )- ]- form_image_blocks, claimed_form_line_indices = _build_form_image_blocks(- source,- active_form_bboxes,- claimed_line_indices,- )- graphic_blocks, claimed_graphic_line_indices = _build_graphic_like_blocks(- source,- table_bboxes + active_form_bboxes,- claimed_line_indices | claimed_form_line_indices,- )- raster_image_blocks, claimed_raster_line_indices = _build_raster_image_blocks(- source,- table_blocks + form_image_blocks + graphic_blocks,- claimed_line_indices | claimed_form_line_indices | claimed_graphic_line_indices,- )- claimed_line_indices = (- claimed_line_indices- | claimed_form_line_indices- | claimed_graphic_line_indices- | claimed_raster_line_indices- )- remaining_lines = _merge_same_baseline_text_lines(- [line for line in source.lines if line.source_index not in claimed_line_indices],- source.page_size,- table_bboxes,- )- _compact_prepared_lines(remaining_lines, source.page_size)- prepared = _PreparedPage(- page_size=source.page_size,- remaining_lines=remaining_lines,- table_bboxes=table_bboxes,- drawing_lines=source.drawing_lines,- fixed_blocks=table_blocks + form_image_blocks + graphic_blocks + raster_image_blocks,- )- _classify_page_auxiliary_text(prepared)- return prepared---def _compact_prepared_lines(- lines: list[_LineItem],- page_size: tuple[float, float],-) -> None:- """缓存后续仍需的字符尺度并释放字符字典,限制跨页阶段内存占用。"""-- for line in lines:- if line.median_glyph_width is None:- line.median_glyph_width = _median_native_glyph_width(line, page_size)- line.chars.clear()---def _classify_page_auxiliary_text(prepared: _PreparedPage) -> None:- """在容器认领后仅按空间关系标注侧栏文字和页脚注。"""-- _classify_aside_text(prepared.remaining_lines, prepared.page_size)- prepared.page_footnote_groups = _classify_page_footnotes(- prepared.remaining_lines,- prepared.table_bboxes,- prepared.drawing_lines,- prepared.page_size,- )---def _classify_aside_text(- lines: list[_LineItem],- page_size: tuple[float, float],-) -> None:- """在横排正文占绝对多数时,以边缘带和物理尺寸识别垂直侧栏。"""-- available = [line for line in lines if line.semantic_type is None]- upright_lines = [line for line in available if line.angle == 0]- if len(upright_lines) < 4:- return-- support_by_angle = _geometric_text_support_by_angle(available, page_size)- total_support = sum(support_by_angle.values())- if total_support <= 0 or support_by_angle.get(0, 0.0) / total_support < 0.8:- return-- page_width, page_height = page_size- if page_width <= 0 or page_height <= 0:- return- # 侧栏必须完整位于 12% 边缘带,且兼具不超过 8% 的窄宽和至少 15% 的物理高度。- aside_source_indices = {- line.source_index- for line in available- if line.angle in {90, 270}- and line.bbox[2] - line.bbox[0] <= 0.08 * page_width- and line.bbox[3] - line.bbox[1] >= 0.15 * page_height- and (- line.bbox[2] <= 0.12 * page_width- or line.bbox[0] >= 0.88 * page_width- )- }- for line in available:- if line.source_index in aside_source_indices:- line.semantic_type = "aside_text"---def _geometric_text_support_by_angle(- lines: list[_LineItem],- page_size: tuple[float, float],-) -> dict[int, float]:- """按局部行宽乘有效行高累计各文字方向的纯几何支持度。"""-- support_by_angle: dict[int, float] = {}- for line in lines:- local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, line.angle)- local_width = max(0.1, local_bbox[2] - local_bbox[0])- support_by_angle[line.angle] = support_by_angle.get(line.angle, 0.0) + (- local_width * _line_effective_height(line, local_bbox)- )- return support_by_angle---def _classify_page_footnotes(- lines: list[_LineItem],- table_bboxes: list[BBox],- drawing_lines: list[_AxisLine],- page_size: tuple[float, float],-) -> list[set[int]]:- """识别主方向页脚注,并按触发分隔线返回来源编号分组。"""-- available = [line for line in lines if line.semantic_type is None]- if not available or not drawing_lines:- return []- support_by_angle = _geometric_text_support_by_angle(available, page_size)- if not support_by_angle:- return []- dominant_angle = max(- sorted(support_by_angle),- key=lambda angle: support_by_angle[angle],- )- line_geometry = [- (line, _rotate_bbox_to_upright(line.bbox, page_size, dominant_angle))- for line in available- if line.angle == dominant_angle- ]- if not line_geometry:- return []-- local_page_size = (- (page_size[1], page_size[0])- if dominant_angle in {90, 270}- else page_size- )- local_page_width, local_page_height = local_page_size- if local_page_width <= 0 or local_page_height <= 0:- return []- effective_heights = [- _line_effective_height(line, bbox)- for line, bbox in line_geometry- ]- median_height = statistics.median(effective_heights) if effective_heights else 1.0- lanes = _infer_text_lanes(line_geometry, local_page_width, median_height)- local_axis_lines = _transform_axis_lines(- drawing_lines,- page_size,- dominant_angle,- )-- candidate_groups: list[set[int]] = []- for axis_line in local_axis_lines:- if axis_line.orientation != "horizontal":- continue- # 分隔线中心必须进入页面下方 30%,上方的正文分隔线不参与脚注判定。- rule_center_y = _bbox_center_y(axis_line.bbox)- if rule_center_y < 0.7 * local_page_height:- continue- # 表格边界会产生断裂横线;除框内线段外,也排除与其同高且近邻的框外线段。- if _rule_belongs_to_confirmed_table(- axis_line,- local_axis_lines,- table_bboxes,- local_page_width,- ):- continue- rule_source_indices: set[int] = set()- for lane in lanes:- rule_source_indices.update(- _footnote_lane_members(- lane,- axis_line.bbox,- local_page_size,- )- )- if rule_source_indices:- candidate_groups.append(rule_source_indices)-- page_footnote_groups = _merge_overlapping_source_groups(candidate_groups)- footnote_source_indices = set().union(*page_footnote_groups) if page_footnote_groups else set()- for line in available:- if line.source_index in footnote_source_indices:- line.semantic_type = "page_footnote"- return page_footnote_groups---def _rule_belongs_to_confirmed_table(- candidate: _LocalAxisLine,- local_axis_lines: list[_LocalAxisLine],- table_bboxes: list[BBox],- local_page_width: float,-) -> bool:- """把表格框内横线及其同高近邻断裂段一并排除,避免框外残段触发脚注。"""-- if not table_bboxes:- return False- maximum_segment_gap = 0.04 * local_page_width- for table_line in local_axis_lines:- if table_line.orientation != "horizontal":- continue- table_margin = max(0.5, table_line.width)- if not any(- _bbox_intersects(- _expand_bbox(table_line.original_bbox, table_margin),- table_bbox,- )- for table_bbox in table_bboxes- ):- continue- center_tolerance = max(1.0, candidate.width, table_line.width)- if abs(_bbox_center_y(candidate.bbox) - _bbox_center_y(table_line.bbox)) > center_tolerance:- continue- if _horizontal_bbox_gap(candidate.bbox, table_line.bbox) <= maximum_segment_gap:- return True- return False---def _merge_overlapping_source_groups(groups: list[set[int]]) -> list[set[int]]:- """合并共享来源行的分隔线候选组,消除重复绘图线造成的重复分组。"""-- merged: list[set[int]] = []- for group in groups:- combined = set(group)- index = 0- while index < len(merged):- if combined & merged[index]:- combined.update(merged.pop(index))- index = 0- continue- index += 1- merged.append(combined)- return sorted(merged, key=lambda group: min(group))---def _footnote_lane_members(- lane: _TextLane,- rule_bbox: BBox,- local_page_size: tuple[float, float],-) -> set[int]:- """验证横线与单个栏带的对齐关系,并返回其下连续脚注行的来源编号。"""-- lane_lines = [item for item in lane.lines if item[0].semantic_type is None]- if not lane_lines:- return set()- lane_lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))- local_page_width, local_page_height = local_page_size- lane_width = max(0.1, lane.right - lane.left)- lane_heights = [_line_effective_height(line, bbox) for line, bbox in lane_lines]- median_height = statistics.median(lane_heights) if lane_heights else 1.0- rule_width = max(0.0, rule_bbox[2] - rule_bbox[0])- # 同时限制绝对短线、相对长线和左缘偏移,排除图标、公式线及跨栏正文分隔线。- if rule_width < max(4.0 * median_height, 0.04 * local_page_width):- return set()- if rule_width > 0.65 * lane_width:- return set()- if abs(rule_bbox[0] - lane.left) > max(2.0 * median_height, 0.04 * lane_width):- return set()-- # 首行采用较宽的 3.5% 页高窗口;命中后仅按紧凑的连续净空向下扩展。- first_gap_limit = max(3.0 * median_height, 0.035 * local_page_height)- first_index: int | None = None- for index, (_line, bbox) in enumerate(lane_lines):- rule_gap = bbox[1] - rule_bbox[3]- if rule_gap < -0.5 * median_height:- continue- if rule_gap <= first_gap_limit:- first_index = index- break- if first_index is None:- return set()-- continuation_gap_limit = max(1.25 * median_height, 0.01 * local_page_height)- members = [lane_lines[first_index]]- for current in lane_lines[first_index + 1 :]:- if _effective_text_row_gap(members[-1], current) > continuation_gap_limit:- break- members.append(current)- return {line.source_index for line, _bbox in members}---def _finalize_prepared_page(- prepared: _PreparedPage,- page_index: int,-) -> list[dict[str, Any]]:- """按预分类语义、公式、标题、正文的优先级完成单页文本并排序。"""-- semantic_lines = [line for line in prepared.remaining_lines if line.semantic_type is not None]- formula_input = [line for line in prepared.remaining_lines if line.semantic_type is None]- formula_blocks, remaining_lines = _build_formula_like_blocks(- formula_input,- prepared.table_bboxes,- prepared.page_size,- )- remaining_lines = _restore_dense_split_visual_rows(- remaining_lines,- prepared.page_size,- prepared.table_bboxes,- )- _classify_page_titles(- remaining_lines,- prepared.page_size,- page_index=page_index,- container_bboxes=[block["bbox"] for block in prepared.fixed_blocks],- )- remaining_lines = _merge_title_resolved_visual_rows(- remaining_lines,- prepared.page_size,- )- remaining_lines = _merge_post_semantic_text_runs(- remaining_lines,- prepared.page_size,- prepared.table_bboxes,- )- text_blocks = _build_text_blocks(- semantic_lines + remaining_lines,- prepared.table_bboxes,- prepared.page_size,- prepared.drawing_lines,- page_footnote_groups=prepared.page_footnote_groups,- )- absolute_blocks = prepared.fixed_blocks + formula_blocks + text_blocks- sorted_blocks = _sort_blocks_with_visual_row_groups(absolute_blocks, prepared.page_size)- return [- normalized- for block in sorted_blocks- if (normalized := _normalize_output_block(block, prepared.page_size)) is not None- ]---def _analyze_page_source(source: _PageSource) -> list[dict[str, Any]]:- """兼容单页测试入口;单页不凭边缘位置猜测页眉、页脚或页码。"""-- if not source.lines and not source.image_bboxes:- return []- return _finalize_prepared_page(_prepare_page_source(source), page_index=0)---def _classify_repeated_page_marginals(pages: list[_PreparedPage]) -> None:- """仅用相邻或同奇偶页的重复证据标注页码、页眉和页脚。"""-- if len(pages) < 2:- return- candidates = [- candidate- for page_index, page in enumerate(pages)- for line in page.remaining_lines- if (candidate := _build_marginal_candidate(page_index, line, page.page_size)) is not None- ]-- for left_index, left in enumerate(candidates):- left_value = _parse_page_number_value(left.line.text)- if left_value is None:- continue- for right in candidates[left_index + 1 :]:- page_delta = right.page_index - left.page_index- if page_delta > 2:- break- right_value = _parse_page_number_value(right.line.text)- if (- page_delta > 0- and right_value is not None- and right_value - left_value == page_delta- and _page_number_candidates_match(left, right)- ):- left.line.semantic_type = "page_number"- right.line.semantic_type = "page_number"-- for left_index, left in enumerate(candidates):- if left.line.semantic_type == "page_number":- continue- for right in candidates[left_index + 1 :]:- page_delta = right.page_index - left.page_index- if page_delta > 2:- break- if (- page_delta > 0- and left.region != "side"- and right.region != "side"- and right.line.semantic_type != "page_number"- and _marginal_geometry_matches(left, right)- and _marginal_text_matches(left.line.text, right.line.text)- ):- left.line.semantic_type = left.region- right.line.semantic_type = right.region---def _build_marginal_candidate(- page_index: int,- line: _LineItem,- page_size: tuple[float, float],-) -> _MarginalCandidate | None:- """把页面上下百分之十五内的常规小行转换成跨页比较候选。"""-- if line.semantic_type is not None:- return None- local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, line.angle)- local_page_size = (page_size[1], page_size[0]) if line.angle in {90, 270} else page_size- local_page_width, local_page_height = local_page_size- if local_page_width <= 0 or local_page_height <= 0:- return None- normalized_center_y = _bbox_center_y(local_bbox) / local_page_height- normalized_center_x = _bbox_center_x(local_bbox) / local_page_width- if normalized_center_y <= 0.15:- region: Literal["header", "footer", "side"] = "header"- elif normalized_center_y >= 0.85:- region = "footer"- elif (- normalized_center_y <= 0.18- or normalized_center_y >= 0.82- or (- (normalized_center_x <= 0.15 or normalized_center_x >= 0.85)- and (normalized_center_y <= 0.3 or normalized_center_y >= 0.7)- )- ):- # 仅页码递增逻辑会消费 side;稳定文本不会被侧栏位置猜成页眉页脚。- region = "side"- else:- return None- if _line_effective_height(line, local_bbox) > 0.06 * local_page_height:- return None- return _MarginalCandidate(- page_index=page_index,- line=line,- local_bbox=local_bbox,- local_page_size=local_page_size,- region=region,- )---def _page_number_candidates_match(- first: _MarginalCandidate,- second: _MarginalCandidate,-) -> bool:- """校验连续页码的同边缘几何,横竖版切换时允许边缘位置随版面改变。"""-- if _marginal_geometry_matches(first, second):- return True- first_landscape = first.local_page_size[0] > first.local_page_size[1]- second_landscape = second.local_page_size[0] > second.local_page_size[1]- if first_landscape == second_landscape or first.line.angle != second.line.angle:- return False- first_height = _line_effective_height(first.line, first.local_bbox) / first.local_page_size[1]- second_height = _line_effective_height(second.line, second.local_bbox) / second.local_page_size[1]- return min(first_height, second_height) > 0 and max(first_height, second_height) / min(- first_height,- second_height,- ) <= 1.5---def _marginal_geometry_matches(- first: _MarginalCandidate,- second: _MarginalCandidate,-) -> bool:- """比较边缘候选的方向、纵向带、字号以及同侧或镜像横向位置。"""-- if first.region != second.region or first.line.angle != second.line.angle:- return False- first_width, first_height = first.local_page_size- second_width, second_height = second.local_page_size- first_y = _bbox_center_y(first.local_bbox) / first_height- second_y = _bbox_center_y(second.local_bbox) / second_height- if abs(first_y - second_y) > 0.025:- return False- first_line_height = _line_effective_height(first.line, first.local_bbox) / first_height- second_line_height = _line_effective_height(second.line, second.local_bbox) / second_height- if min(first_line_height, second_line_height) <= 0 or max(first_line_height, second_line_height) / min(- first_line_height,- second_line_height,- ) > 1.35:- return False- if (- first.line.font_signature is not None- and second.line.font_signature is not None- and first.line.font_coverage >= 0.75- and second.line.font_coverage >= 0.75- and first.line.font_signature != second.line.font_signature- ):- return False-- first_normalized_bbox = (- first.local_bbox[0] / first_width,- first.local_bbox[1] / first_height,- first.local_bbox[2] / first_width,- first.local_bbox[3] / first_height,- )- second_normalized_bbox = (- second.local_bbox[0] / second_width,- second.local_bbox[1] / second_height,- second.local_bbox[2] / second_width,- second.local_bbox[3] / second_height,- )- same_side = (- _bbox_axis_overlap_ratio(first_normalized_bbox, second_normalized_bbox, axis="x") >= 0.4- or abs(_bbox_center_x(first_normalized_bbox) - _bbox_center_x(second_normalized_bbox)) <= 0.08- )- mirrored = abs(- _bbox_center_x(first_normalized_bbox) + _bbox_center_x(second_normalized_bbox) - 1.0- ) <= 0.12- return same_side or mirrored---def _parse_page_number_value(text: str) -> int | None:- """解析整行阿拉伯、罗马或中文页码;混有稳定正文的行不作为纯页码。"""-- normalized = unicodedata.normalize("NFKC", str(text or ""))- match = _PAGE_NUMBER_RE.fullmatch(normalized)- if match is None:- return None- value = match.group("value")- if value.isdecimal():- return int(value)- if re.fullmatch(r"[ivxlcdm]+", value, re.IGNORECASE):- return _roman_number_to_int(value)- return _chinese_page_number_to_int(value)---def _roman_number_to_int(value: str) -> int | None:- """把页码中的规范罗马数字转换成整数,非法组合返回空。"""-- roman_values = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}- normalized = value.upper()- total = 0- previous = 0- for char in reversed(normalized):- current = roman_values.get(char)- if current is None:- return None- total += -current if current < previous else current- previous = max(previous, current)- if total <= 0 or total > 4999:- return None- return total---def _chinese_page_number_to_int(value: str) -> int | None:- """把常见百位以内中文页码转换成整数,供跨页递增校验使用。"""-- digits = {"〇": 0, "零": 0, "一": 1, "二": 2, "两": 2, "三": 3, "四": 4, "五": 5, "六": 6, "七": 7, "八": 8, "九": 9}- if all(char in digits for char in value):- try:- return int("".join(str(digits[char]) for char in value))- except ValueError:- return None- total = 0- current_digit = 0- for char in value:- if char in digits:- current_digit = digits[char]- elif char == "十":- total += (current_digit or 1) * 10- current_digit = 0- elif char == "百":- total += (current_digit or 1) * 100- current_digit = 0- else:- return None- return total + current_digit if total + current_digit > 0 else None---def _marginal_text_matches(first_text: str, second_text: str) -> bool:- """在屏蔽变化数字后比较边缘稳定文本,短文本只接受完全一致。"""-- first = _normalize_marginal_text(first_text)- second = _normalize_marginal_text(second_text)- if not first or not second:- return False- if first == second:- return True- if min(len(first), len(second)) < 8:- return False- return SequenceMatcher(a=first, b=second, autojunk=False).ratio() >= 0.92---def _normalize_marginal_text(text: str) -> str:- """统一边缘重复文本的宽窄字符、大小写、空白和可变数字。"""-- normalized = unicodedata.normalize("NFKC", str(text or "")).casefold()- normalized = re.sub(r"\d+", "#", normalized)- return re.sub(r"\s+", "", normalized).strip()---def _classify_page_titles(- lines: list[_LineItem],- page_size: tuple[float, float],- *,- page_index: int,- container_bboxes: list[BBox],-) -> None:- """只用页面几何与字体排版标注首页文档标题和各页段落标题。"""-- for angle in sorted({line.angle for line in lines if line.semantic_type is None}):- line_geometry = [- (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))- for line in lines- if line.angle == angle and line.semantic_type is None- ]- if not line_geometry:- continue- median_height = statistics.median(- _line_effective_height(line, bbox) for line, bbox in line_geometry- )- local_page_width = page_size[1] if angle in {90, 270} else page_size[0]- local_page_height = page_size[0] if angle in {90, 270} else page_size[1]- lanes = _infer_text_lanes(line_geometry, local_page_width, median_height)- for lane in lanes:- lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))-- document_title_bottom: float | None = None- if page_index == 0:- document_title_bottom = _classify_document_title(- lanes,- local_page_height,- )- preserve_front_matter_boundaries = _document_title_uses_page_fallback(- lanes,- )-- local_container_bboxes = [- _rotate_bbox_to_upright(bbox, page_size, angle)- for bbox in container_bboxes- ]- for lane in lanes:- profile = _infer_lane_body_profile(lane)- _classify_paragraph_titles_in_lane(- lane,- profile,- local_page_height,- local_container_bboxes,- document_title_bottom=document_title_bottom,- preserve_front_matter_boundaries=preserve_front_matter_boundaries,- )---def _infer_lane_body_profile(lane: _TextLane) -> _LaneBodyProfile:- """从栏带的长行主体估计正文行高、主字体、字重、常规行距和样式占比。"""-- available = [item for item in lane.lines if item[0].semantic_type is None]- if not available:- return _LaneBodyProfile(1.0, None, None, 0.35, {})- lane_width = max(0.1, lane.right - lane.left)- long_lines = [item for item in available if item[1][2] - item[1][0] >= 0.45 * lane_width]- body_rows = long_lines or available- body_line_ids = {id(line) for line, _bbox in body_rows}- body_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in body_rows)-- font_support: dict[tuple[str, int], float] = {}- style_support: dict[tuple[str, int], float] = {}- total_style_width = 0.0- for line, bbox in available:- if line.font_signature is None or line.font_coverage < 0.75:- continue- line_width = max(0.1, bbox[2] - bbox[0])- style_support[line.font_signature] = style_support.get(line.font_signature, 0.0) + line_width- total_style_width += line_width- if id(line) in body_line_ids and 0.75 <= _line_effective_height(line, bbox) / body_height <= 1.35:- font_support[line.font_signature] = font_support.get(line.font_signature, 0.0) + line_width- body_font = max(font_support, key=font_support.get) if font_support else None- if total_style_width > 0:- style_support = {signature: width / total_style_width for signature, width in style_support.items()}-- body_weights = [- line.dominant_font_weight- for line, bbox in body_rows- if line.dominant_font_weight is not None- and (body_font is None or line.font_signature == body_font)- and 0.75 <= _line_effective_height(line, bbox) / body_height <= 1.35- ]- regular_gap, _gap_mad = _estimate_lane_gap(lane)- return _LaneBodyProfile(- body_height=max(0.1, body_height),- body_font=body_font,- body_weight=statistics.median(body_weights) if body_weights else None,- regular_gap=regular_gap,- style_support=style_support,- )---def _classify_document_title(- lanes: list[_TextLane],- local_page_height: float,-) -> 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)- )- 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]- for row_index, item in enumerate(available[:5]):- line, bbox = item- reference_height = min(profile.body_height, 1.25 * document_body_height)- height_ratio = _line_effective_height(line, bbox) / max(0.1, reference_height)- document_height_ratio = _line_effective_height(line, bbox) / max(- 0.1,- document_body_height,- )- width_ratio = (bbox[2] - bbox[0]) / lane_width- centered = abs(_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) <= 0.15 * lane_width- spans_columns_fallback = (- lane.is_span- and centered- and width_ratio >= 0.65- and document_height_ratio >= 1.3- )- if (- _bbox_center_y(bbox) > 0.45 * local_page_height- or (height_ratio < 1.4 and not spans_columns_fallback)- or width_ratio < 0.2- or (not centered and height_ratio < 1.7)- ):- continue- top_preference = max(0.0, 0.45 - _bbox_center_y(bbox) / local_page_height)- score = height_ratio + (0.75 if centered else 0.0) + top_preference - 0.05 * row_index- candidates.append((score, lane, row_index, item))- if not candidates:- return None-- _score, lane, _row_index, anchor = max(candidates, key=lambda item: item[0])- anchor_line, anchor_bbox = anchor- anchor_height = _line_effective_height(anchor_line, anchor_bbox)- anchor_line.semantic_type = "doc_title"- selected = [anchor]- ordered = lane.lines- anchor_index = ordered.index(anchor)- for direction in (-1, 1):- index = anchor_index + direction- previous_bbox = anchor_bbox- while 0 <= index < len(ordered):- candidate_line, candidate_bbox = ordered[index]- if candidate_line.semantic_type is not None:- break- candidate_height = _line_effective_height(candidate_line, candidate_bbox)- if not 0.8 <= candidate_height / anchor_height <= 1.25:- break- if not _title_fonts_compatible(anchor_line, candidate_line):- break- vertical_gap = max(candidate_bbox[1] - previous_bbox[3], previous_bbox[1] - candidate_bbox[3], 0.0)- lane_width = max(0.1, lane.right - lane.left)- centered = abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(anchor_bbox)) <= 0.18 * lane_width- aligned = abs(candidate_bbox[0] - anchor_bbox[0]) <= 0.75 * anchor_height- if vertical_gap > 1.1 * anchor_height or not (centered or aligned):- break- candidate_line.semantic_type = "doc_title"- selected.append((candidate_line, candidate_bbox))- previous_bbox = candidate_bbox- index += direction- return max(bbox[3] for _line, bbox in selected)---def _document_title_uses_page_fallback(lanes: list[_TextLane]) -> bool:- """判断首页标题是否依赖跨栏 1.30 倍全文正文行高兜底。"""-- title_heights = [- _line_effective_height(line, bbox)- for lane in lanes- for line, bbox in lane.lines- if line.semantic_type == "doc_title"- ]- column_body_heights = [- _infer_lane_body_profile(lane).body_height- for lane in lanes- if not lane.is_span- ]- if not title_heights or not column_body_heights:- return False- document_body_height = statistics.median(column_body_heights)- return any(- 1.3 <= title_height / max(0.1, document_body_height) < 1.4- for title_height in title_heights- )---def _classify_paragraph_titles_in_lane(- lane: _TextLane,- profile: _LaneBodyProfile,- local_page_height: float,- container_bboxes: list[BBox],- *,- document_title_bottom: float | None,- preserve_front_matter_boundaries: bool,-) -> None:- """以字号、样式、留白、对齐、栏宽和容器邻接判定段落标题。"""-- lane_width = max(0.1, lane.right - lane.left)- rows = lane.lines- selected_indices: set[int] = set()- front_matter_boundary = _infer_front_matter_boundary(- lane,- profile,- local_page_height,- document_title_bottom=document_title_bottom,- )- for index, (line, bbox) in enumerate(rows):- if line.semantic_type is not None:- continue- if not 0.07 * local_page_height <= _bbox_center_y(bbox) <= 0.93 * local_page_height:- continue- inside_front_matter = (- front_matter_boundary is not None- and _bbox_center_y(bbox) <= front_matter_boundary- )- if inside_front_matter and not preserve_front_matter_boundaries:- continue- if _line_near_visual_container(bbox, container_bboxes, profile.body_height):- continue-- line_height = _line_effective_height(line, bbox)- height_ratio = line_height / profile.body_height- width_ratio = (bbox[2] - bbox[0]) / lane_width- centered = abs(_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) <= 0.12 * lane_width- left_aligned = abs(bbox[0] - lane.left) <= 0.65 * profile.body_height- style_differs = (- profile.body_font is not None- and line.font_signature is not None- and line.font_coverage >= 0.75- and line.font_signature != profile.body_font- )- style_support = profile.style_support.get(line.font_signature, 1.0) if line.font_signature is not None else 1.0- weight_emphasized = (- profile.body_weight is not None- and line.dominant_font_weight is not None- and line.dominant_font_weight >= max(profile.body_weight + 100.0, 1.15 * profile.body_weight)- )- gap_above = _normalized_title_gap(rows, index, direction=-1, body_height=profile.body_height)- gap_below = _normalized_title_gap(rows, index, direction=1, body_height=profile.body_height)- has_spacing_signal = gap_above >= 0.35-- if _visual_row_has_body_style_sibling(rows, index):- continue- if _is_near_full_mixed_inline_row(- rows,- index,- lane_width,- profile,- ):- continue- if (- index > 0- and rows[index - 1][0].semantic_type == "paragraph_title"- and width_ratio >= 0.85- and gap_above < 1.0- and not _title_fonts_compatible(rows[index - 1][0], line)- ):- continue- if height_ratio < 0.9 and not inside_front_matter and not _has_following_body_row(- rows,- index,- lane_width,- profile,- ):- continue- if width_ratio >= 0.9 and height_ratio < 1.15 and not (- style_differs and gap_above >= 0.65- ):- continue- score = 0.0- if style_differs:- score += 2.0- if style_support <= 0.2:- score += 0.75- if weight_emphasized:- score += 1.0- if height_ratio >= 1.18:- score += 2.0- elif height_ratio <= 0.9 and centered:- score += 0.75- if width_ratio <= 0.78:- score += 0.75- if centered and width_ratio <= 0.85:- score += 1.25- if gap_above >= 0.65:- score += 1.25- elif gap_above >= 0.35:- score += 0.5- if gap_below >= 0.35:- score += 0.75- if left_aligned:- score += 0.25-- strong_layout_signal = (- height_ratio >= 1.18- or style_differs- or weight_emphasized- or (centered and width_ratio <= 0.7 and gap_above >= 0.35 and gap_below >= 0.2)- )- if score >= 4.0 and has_spacing_signal and strong_layout_signal:- if _is_full_width_inline_heading(- rows,- index,- lane_width,- profile,- ):- continue- line.semantic_type = "paragraph_title"- selected_indices.add(index)-- _unify_visual_row_title_types(- lane,- selected_indices,- )- _expand_paragraph_title_neighbors(- lane,- selected_indices,- profile,- )- if front_matter_boundary is not None and preserve_front_matter_boundaries:- _protect_front_matter_title_types(- lane,- profile,- front_matter_boundary,- )---def _protect_front_matter_title_types(- lane: _TextLane,- profile: _LaneBodyProfile,- front_matter_boundary: float,-) -> None:- """把作者区误命中的标题降为正文,并仅保留原本需要跨行聚合的内部标记。"""-- front_title_indices = [- index- for index, (line, bbox) in enumerate(lane.lines)- if line.semantic_type == "paragraph_title"- and _bbox_center_y(bbox) <= front_matter_boundary- ]- connected_indices: set[int] = set()- for position, first_index in enumerate(front_title_indices):- for second_index in front_title_indices[position + 1 :]:- if _should_connect_semantic_rows(- lane.lines[first_index],- lane.lines[second_index],- lane,- profile.regular_gap,- [],- [],- ):- connected_indices.update((first_index, second_index))- for index in front_title_indices:- lane.lines[index][0].semantic_type = (- "text" if index in connected_indices else None- )---def _visual_row_has_body_style_sibling(- rows: list[tuple[_LineItem, BBox]],- index: int,-) -> bool:- """检查同一完整视觉行是否同时包含标题样式与正文样式 run。"""-- line, _bbox = rows[index]- if line.visual_row_id is None:- return False- siblings = [- sibling- for sibling, _sibling_bbox in rows- if sibling is not line and sibling.visual_row_id == line.visual_row_id- ]- return any(not _title_fonts_compatible(line, sibling) for sibling in siblings)---def _is_near_full_mixed_inline_row(- rows: list[tuple[_LineItem, BBox]],- index: int,- lane_width: float,- profile: _LaneBodyProfile,-) -> bool:- """识别近满栏混合字体行内强调,避免把粗体条目头单独标成标题。"""-- line, bbox = rows[index]- line_height = _line_effective_height(line, bbox)- if (- line.font_coverage >= 0.95- or (bbox[2] - bbox[0]) < 0.85 * lane_width- or not 0.85 <= line_height / profile.body_height <= 1.15- or index + 1 >= len(rows)- ):- return False- next_line, next_bbox = rows[index + 1]- next_height = _line_effective_height(next_line, next_bbox)- gap_below = _effective_text_row_gap(rows[index], rows[index + 1])- return (- next_line.semantic_type is None- and 0.8 <= next_height / profile.body_height <= 1.2- and gap_below <= profile.regular_gap + 0.25 * profile.body_height- )---def _is_full_width_inline_heading(- rows: list[tuple[_LineItem, BBox]],- index: int,- lane_width: float,- profile: _LaneBodyProfile,-) -> bool:- """识别后接常规正文续行的满栏正常字号行内标题。"""-- line, bbox = rows[index]- line_height = _line_effective_height(line, bbox)- if (- not 0.85 <= line_height / profile.body_height <= 1.15- or (bbox[2] - bbox[0]) < 0.9 * lane_width- or index + 1 >= len(rows)- ):- return False-- next_line, next_bbox = rows[index + 1]- next_height = _line_effective_height(next_line, next_bbox)- next_uses_body_font = (- profile.body_font is None- or next_line.font_signature is None- or next_line.font_coverage < 0.75- or next_line.font_signature == profile.body_font- )- return (- next_line.semantic_type is None- and next_uses_body_font- and 0.75 <= next_height / profile.body_height <= 1.15- and (next_bbox[2] - next_bbox[0]) >= 0.75 * lane_width- and _effective_text_row_gap(rows[index], rows[index + 1])- <= profile.regular_gap + 0.25 * profile.body_height- )---def _has_following_body_row(- rows: list[tuple[_LineItem, BBox]],- index: int,- lane_width: float,- profile: _LaneBodyProfile,-) -> bool:- """检查小字号候选下方是否仍有正常字号的正文续行。"""-- for line, bbox in rows[index + 1 :]:- height_ratio = _line_effective_height(line, bbox) / profile.body_height- width_ratio = (bbox[2] - bbox[0]) / lane_width- if 0.9 <= height_ratio <= 1.2 and width_ratio >= 0.45:- return True- return False---def _unify_visual_row_title_types(- lane: _TextLane,- selected_indices: set[int],-) -> None:- """按完整 visual_row_id 统一标题类型:同样式整行晋升,混合样式整行降级。"""-- row_indices: dict[int, list[int]] = {}- for index, (line, _bbox) in enumerate(lane.lines):- if line.visual_row_id is not None:- row_indices.setdefault(line.visual_row_id, []).append(index)- for indices in row_indices.values():- title_indices = [- index- for index in indices- if lane.lines[index][0].semantic_type == "paragraph_title"- ]- if not title_indices:- continue- anchor_line, anchor_bbox = lane.lines[title_indices[0]]- anchor_height = _line_effective_height(anchor_line, anchor_bbox)- compatible = all(- 0.75- <= _line_effective_height(lane.lines[index][0], lane.lines[index][1])- / anchor_height- <= 1.25- and _title_fonts_compatible(anchor_line, lane.lines[index][0])- for index in indices- )- if compatible:- for index in indices:- lane.lines[index][0].semantic_type = "paragraph_title"- selected_indices.add(index)- continue- for index in title_indices:- lane.lines[index][0].semantic_type = None- selected_indices.discard(index)---def _infer_front_matter_boundary(- lane: _TextLane,- profile: _LaneBodyProfile,- local_page_height: float,- *,- document_title_bottom: float | None,-) -> float | None:- """用短行后衔接满栏正文的几何转折点界定首页作者等前置信息。"""-- if document_title_bottom is None:- return None- default_boundary = max(- document_title_bottom + 2.5 * profile.body_height,- 0.39 * local_page_height,- )- lane_width = max(0.1, lane.right - lane.left)- for index, (line, bbox) in enumerate(lane.lines[:-1]):- if bbox[1] <= document_title_bottom:- continue- next_line, next_bbox = lane.lines[index + 1]- width_ratio = (bbox[2] - bbox[0]) / lane_width- next_width_ratio = (next_bbox[2] - next_bbox[0]) / lane_width- left_aligned = abs(bbox[0] - lane.left) <= 0.65 * profile.body_height- centered = abs(- _bbox_center_x(bbox) - (lane.left + lane.right) / 2.0- ) <= 0.12 * lane_width- next_height_ratio = _line_effective_height(next_line, next_bbox) / profile.body_height- gap_below = max(0.0, _effective_text_row_gap((line, bbox), (next_line, next_bbox)))- if (- width_ratio <= 0.35- and next_width_ratio >= 0.75- and (left_aligned or centered)- and 0.75 <= next_height_ratio <= 1.35- and gap_below <= 1.5 * profile.body_height- ):- return min(default_boundary, bbox[1] - 0.1)- return default_boundary---def _normalized_title_gap(- rows: list[tuple[_LineItem, BBox]],- index: int,- *,- direction: Literal[-1, 1],- body_height: float,-) -> float:- """返回标题候选与相邻物理行之间按正文行高归一化的有效净空。"""-- neighbor_index = index + direction- if not 0 <= neighbor_index < len(rows):- return 0.5- if direction < 0:- gap = _effective_text_row_gap(rows[neighbor_index], rows[index])- else:- gap = _effective_text_row_gap(rows[index], rows[neighbor_index])- return max(0.0, gap) / max(0.1, body_height)---def _line_near_visual_container(- line_bbox: BBox,- container_bboxes: list[BBox],- body_height: float,-) -> bool:- """检查短行是否紧邻图、表等容器,以纯几何方式抑制 caption 误判。"""-- for container_bbox in container_bboxes:- if _bbox_axis_overlap_ratio(line_bbox, container_bbox, axis="x") < 0.35:- continue- vertical_gap = max(line_bbox[1] - container_bbox[3], container_bbox[1] - line_bbox[3], 0.0)- if vertical_gap <= 1.5 * body_height:- return True- return False---def _title_fonts_compatible(first: _LineItem, second: _LineItem) -> bool:- """检查标题字体和字重是否兼容;低字体覆盖率时仍保留可靠字重证据。"""-- font_conflicts = (- first.font_signature is not None- and second.font_signature is not None- and first.font_coverage >= 0.75- and second.font_coverage >= 0.75- and first.font_signature != second.font_signature- )- weight_conflicts = (- first.dominant_font_weight is not None- and second.dominant_font_weight is not None- and abs(first.dominant_font_weight - second.dominant_font_weight) >= 100.0- and max(first.dominant_font_weight, second.dominant_font_weight)- >= 1.15 * min(first.dominant_font_weight, second.dominant_font_weight)- )- return not (font_conflicts or weight_conflicts)---def _expand_paragraph_title_neighbors(- lane: _TextLane,- selected_indices: set[int],- profile: _LaneBodyProfile,-) -> None:- """用相邻行的字体、尺寸、对齐和紧凑净空补齐折行段落标题。"""-- if not selected_indices:- return- rows = lane.lines- lane_width = max(0.1, lane.right - lane.left)- pending = list(selected_indices)- while pending:- selected_index = pending.pop()- selected_line, selected_bbox = rows[selected_index]- selected_height = _line_effective_height(selected_line, selected_bbox)- for candidate_index in (selected_index - 1, selected_index + 1):- if not 0 <= candidate_index < len(rows) or candidate_index in selected_indices:- continue- candidate_line, candidate_bbox = rows[candidate_index]- if candidate_line.semantic_type is not None:- continue- candidate_height = _line_effective_height(candidate_line, candidate_bbox)- if not 0.75 <= candidate_height / selected_height <= 1.25:- continue- if candidate_bbox[2] - candidate_bbox[0] > 0.8 * lane_width:- continue- if not _title_fonts_compatible(selected_line, candidate_line):- continue- vertical_gap = max(- candidate_bbox[1] - selected_bbox[3],- selected_bbox[1] - candidate_bbox[3],- 0.0,- )- centers_align = abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(selected_bbox)) <= 0.15 * lane_width- left_edges_align = abs(candidate_bbox[0] - selected_bbox[0]) <= 0.75 * profile.body_height- wrapped_indent = abs(candidate_bbox[0] - selected_bbox[0]) <= 2.0 * profile.body_height- if vertical_gap > 0.65 * profile.body_height or not (- centers_align or left_edges_align or wrapped_indent- ):- continue- candidate_line.semantic_type = "paragraph_title"- selected_indices.add(candidate_index)- pending.append(candidate_index)---def _detect_table_candidates(source: _PageSource) -> list[_TableCandidate]:- """按文本方向融合三条长横线与规则文本分布,生成表格候选。"""-- candidates: list[_TableCandidate] = []- angles = sorted({line.angle for line in source.lines})- for angle in angles:- angle_lines = [line for line in source.lines if line.angle == angle]- if not angle_lines:- continue- fragments = _build_fragments(angle_lines, source.page_size)- if not fragments:- continue- median_height = _median_fragment_height(fragments)- rows = _cluster_fragment_rows(fragments, median_height)- local_axis_lines = _transform_axis_lines(- source.drawing_lines,- source.page_size,- angle,- )- candidates.extend(- _build_rule_table_candidates(- rows,- angle_lines,- source.page_size,- angle,- median_height,- local_axis_lines,- )- )- return _merge_table_candidates(candidates)---def _build_fragments(- lines: list[_LineItem],- page_size: tuple[float, float],-) -> list[_Fragment]:- """将精修后的原生 run 转换成表格单元候选。"""-- fragments: list[_Fragment] = []- for line in lines:- local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, line.angle)- fragments.append(- _Fragment(- text=line.text,- bbox=line.bbox,- local_bbox=local_bbox,- line_index=line.source_index,- # 复用原生粗行身份,避免同一字符行内不同 cell- # 因轻微基线差异被误拆成多行。- visual_row_id=line.visual_row_id,- )- )- return fragments---def _cluster_fragment_rows(- fragments: list[_Fragment],- median_height: float,-) -> list[_VisualRow]:- """优先复用原生视觉行身份,其余片段按中心线容差聚成表格行。"""-- tolerance = max(2.0, median_height * 0.5)- native_groups: dict[int, list[_Fragment]] = {}- geometric_fragments: list[_Fragment] = []- for fragment in fragments:- if fragment.visual_row_id is None:- geometric_fragments.append(fragment)- else:- native_groups.setdefault(fragment.visual_row_id, []).append(fragment)-- # 先锁定同一原生粗行拆出的 run,再允许不同粗行按基线几何合并;- # 旋转表格常把同一数据行的各 cell 分成多个 pdftext 粗行,不能只依赖 row id。- seed_groups = [*native_groups.values(), *[[fragment] for fragment in geometric_fragments]]- seed_groups.sort(- key=lambda group: (- statistics.fmean(_bbox_center_y(item.local_bbox) for item in group),- min(item.local_bbox[0] for item in group),- )- )- grouped: list[list[_Fragment]] = []- for seed_group in seed_groups:- center_y = statistics.fmean(_bbox_center_y(item.local_bbox) for item in seed_group)- target_group: list[_Fragment] | None = None- for group in grouped:- group_center = statistics.fmean(_bbox_center_y(item.local_bbox) for item in group)- if abs(center_y - group_center) <= tolerance:- target_group = group- break- if target_group is None:- grouped.append(list(seed_group))- else:- target_group.extend(seed_group)-- rows: list[_VisualRow] = []- for group in grouped:- group.sort(key=lambda item: item.local_bbox[0])- bbox = _bbox_union_many([item.local_bbox for item in group])- visual_row_ids = {item.visual_row_id for item in group if item.visual_row_id is not None}- rows.append(- _VisualRow(- fragments=group,- center_y=sum(_bbox_center_y(item.local_bbox) for item in group) / len(group),- bbox=bbox,- visual_row_id=next(iter(visual_row_ids)) if len(visual_row_ids) == 1 else None,- )- )- rows.sort(key=lambda row: row.center_y)- return rows---def _build_rule_table_candidates(- rows: list[_VisualRow],- lines: list[_LineItem],- page_size: tuple[float, float],- angle: int,- median_height: float,- axis_lines: list[_LocalAxisLine],-) -> list[_TableCandidate]:- """用三条长横线确定区域,再以连续多列文本分布确认表格。"""-- candidates: list[_TableCandidate] = []- for rule_group in _group_long_horizontal_rules(axis_lines, median_height):- rule_bbox = _bbox_union_many([line.bbox for line in rule_group])- core_rows: list[_VisualRow] = []- for row in rows:- clipped_row = _clip_visual_row_to_corridor(row, rule_bbox, margin=0.0)- if clipped_row is not None and rule_bbox[1] <= clipped_row.center_y <= rule_bbox[3]:- core_rows.append(clipped_row)-- dense_rows = _longest_dense_multi_cell_rows(core_rows, median_height)- if len(dense_rows) < 3:- continue- stable_columns, column_coverage = _count_stable_columns(dense_rows, median_height)- if stable_columns < 2 or column_coverage < 0.5:- continue-- caption_line = _find_table_caption(lines, rule_bbox, page_size, angle, median_height)- candidate = _expand_rule_table_candidate(- rule_group,- core_rows,- rows,- page_size,- angle,- median_height,- caption_line,- )- candidate.score = float(len(rule_group) + len(dense_rows) + stable_columns)- candidates.append(candidate)- return candidates---def _group_long_horizontal_rules(- axis_lines: list[_LocalAxisLine],- median_height: float,-) -> list[list[_LocalAxisLine]]:- """按近似左右端点和纵向距离聚合长横线,并去除同位置重复路径。"""-- minimum_length = max(40.0, 10.0 * median_height)- horizontal_lines = [- line for line in axis_lines if line.orientation == "horizontal" and line.bbox[2] - line.bbox[0] >= minimum_length- ]- endpoint_tolerance = max(4.0, 2.0 * median_height)- span_groups: list[list[_LocalAxisLine]] = []- for line in sorted(horizontal_lines, key=lambda item: (item.bbox[0], item.bbox[2], item.bbox[1])):- target = next(- (- group- for group in span_groups- if abs(line.bbox[0] - group[0].bbox[0]) <= endpoint_tolerance- and abs(line.bbox[2] - group[0].bbox[2]) <= endpoint_tolerance- ),- None,- )- if target is None:- span_groups.append([line])- else:- target.append(line)-- output: list[list[_LocalAxisLine]] = []- maximum_vertical_gap = 24.0 * median_height- for span_group in span_groups:- vertical_groups: list[list[_LocalAxisLine]] = []- for line in sorted(span_group, key=lambda item: _bbox_center_y(item.bbox)):- if (- not vertical_groups- or _bbox_center_y(line.bbox) - _bbox_center_y(vertical_groups[-1][-1].bbox) > maximum_vertical_gap- ):- vertical_groups.append([line])- else:- vertical_groups[-1].append(line)-- for vertical_group in vertical_groups:- unique_lines: list[_LocalAxisLine] = []- for line in vertical_group:- if any(abs(_bbox_center_y(line.bbox) - _bbox_center_y(item.bbox)) <= 1.0 for item in unique_lines):- continue- unique_lines.append(line)- if len(unique_lines) >= 3:- output.append(unique_lines)- return output---def _clip_visual_row_to_corridor(- row: _VisualRow,- corridor_bbox: BBox,- *,- margin: float,-) -> _VisualRow | None:- """仅保留横向走廊内的片段,避免同基线的另一栏文本污染表格区域。"""-- fragments = [- fragment- for fragment in row.fragments- if corridor_bbox[0] - margin <= _bbox_center_x(fragment.local_bbox) <= corridor_bbox[2] + margin- ]- if not fragments:- return None- fragments.sort(key=lambda fragment: fragment.local_bbox[0])- return _VisualRow(- fragments=fragments,- center_y=sum(_bbox_center_y(fragment.local_bbox) for fragment in fragments) / len(fragments),- bbox=_bbox_union_many([fragment.local_bbox for fragment in fragments]),- visual_row_id=row.visual_row_id,- )---def _longest_dense_multi_cell_rows(- rows: list[_VisualRow],- median_height: float,-) -> list[_VisualRow]:- """返回行距不超过四倍行高的最长连续多单元格文本段。"""-- segments: list[list[_VisualRow]] = []- for row in (item for item in rows if len(item.fragments) >= 2):- if not segments or row.center_y - segments[-1][-1].center_y > 4.0 * median_height:- segments.append([row])- else:- segments[-1].append(row)- return max(segments, key=len, default=[])---def _expand_rule_table_candidate(- rule_group: list[_LocalAxisLine],- core_rows: list[_VisualRow],- all_rows: list[_VisualRow],- page_size: tuple[float, float],- angle: int,- median_height: float,- caption_line: _LineItem | None,-) -> _TableCandidate:- """合并横线核心、上方标题和下方脚注,构造统一投影候选。"""-- rule_bbox = _bbox_union_many([line.bbox for line in rule_group])- core_line_indices = {fragment.line_index for row in core_rows for fragment in row.fragments}- caption_rows = _collect_caption_rows(all_rows, caption_line, rule_bbox, median_height)- footnote_rows = _collect_footnote_rows(- all_rows,- rule_bbox,- median_height,- core_line_indices,- )- included_rows = [*caption_rows, *core_rows, *footnote_rows]- core_local_bbox = _bbox_union(rule_bbox, _bbox_union_many([row.bbox for row in core_rows]))- local_bbox = _bbox_union(core_local_bbox, _bbox_union_many([row.bbox for row in included_rows]))- return _TableCandidate(- bbox=_rotate_bbox_from_upright(local_bbox, page_size, angle),- local_bbox=local_bbox,- angle=angle,- score=0.0,- core_bbox=_rotate_bbox_from_upright(core_local_bbox, page_size, angle),- line_indices={fragment.line_index for row in included_rows for fragment in row.fragments},- )---def _collect_caption_rows(- rows: list[_VisualRow],- caption_line: _LineItem | None,- rule_bbox: BBox,- median_height: float,-) -> list[_VisualRow]:- """收集显式标题所在行及其到表格上边界之间的连续换行。"""-- if caption_line is None:- return []- caption_row_index = next(- (- index- for index, row in enumerate(rows)- if any(fragment.line_index == caption_line.source_index for fragment in row.fragments)- ),- None,- )- if caption_row_index is None:- return []-- output: list[_VisualRow] = []- previous_bbox: BBox | None = None- margin = 2.0 * median_height- for index, row in enumerate(rows[caption_row_index:], start=caption_row_index):- clipped_row = _clip_visual_row_to_corridor(row, rule_bbox, margin=margin)- if clipped_row is None:- continue- if index > caption_row_index and clipped_row.center_y >= rule_bbox[1]:- break- if previous_bbox is not None and max(0.0, clipped_row.bbox[1] - previous_bbox[3]) > 2.0 * median_height:- break- output.append(clipped_row)- previous_bbox = clipped_row.bbox-- if not output or rule_bbox[1] - output[-1].bbox[3] > 2.0 * median_height:- return []- return output---def _collect_footnote_rows(- rows: list[_VisualRow],- rule_bbox: BBox,- median_height: float,- core_line_indices: set[int],-) -> list[_VisualRow]:- """从表格下边界开始吸收带通用标记的脚注及其连续换行。"""-- output: list[_VisualRow] = []- bottom = rule_bbox[3]- note_chain_started = False- margin = 2.0 * median_height- selected_line_indices = set(core_line_indices)- for row in rows:- clipped_row = _clip_visual_row_to_corridor(row, rule_bbox, margin=margin)- if clipped_row is None or clipped_row.bbox[3] <= bottom:- continue- line_indices = {fragment.line_index for fragment in clipped_row.fragments}- if line_indices.issubset(selected_line_indices):- bottom = max(bottom, clipped_row.bbox[3])- continue- if max(0.0, clipped_row.bbox[1] - bottom) > 1.5 * median_height:- break- if not note_chain_started and not _is_table_note_text(_visual_row_text(clipped_row)):- break- output.append(clipped_row)- selected_line_indices.update(line_indices)- bottom = max(bottom, clipped_row.bbox[3])- note_chain_started = True- return output---def _visual_row_text(row: _VisualRow) -> str:- """按局部 x 顺序拼接视觉行文本,供拆分脚注标记判断。"""-- return " ".join(fragment.text.strip() for fragment in row.fragments if fragment.text.strip())---def _is_table_note_text(text: str) -> bool:- """判断表后首行是否具有明确的注释、来源或脚注标记。"""-- return bool(_TABLE_NOTE_RE.match(str(text or "").strip()))---def _find_table_caption(- lines: list[_LineItem],- core_bbox: BBox,- page_size: tuple[float, float],- angle: int,- median_height: float,-) -> _LineItem | None:- """在核心表格上方最多十二倍行高内查找显式 Table/表标题。"""-- candidates: list[tuple[float, _LineItem]] = []- for line in lines:- text = line.text.strip()- caption_match = _TABLE_CAPTION_RE.match(text)- is_split_label = text.lower().rstrip(".") in {"table", "tab", "表", "表格"}- if caption_match is None and not is_split_label:- continue- if caption_match is not None:- suffix = caption_match.group("suffix").strip(" .:–—-")- # 小写连续句通常是“Table 5 also ...”这类正文,不应作为标题。- if suffix and suffix[0].islower():- continue- local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, angle)- if _bbox_axis_overlap_ratio(local_bbox, core_bbox, axis="x") < 0.05:- continue- if is_split_label:- has_number_peer = bool(- _find_caption_number_peers(- line,- lines,- page_size,- angle,- median_height,- )- )- if not has_number_peer:- continue- gap = core_bbox[1] - local_bbox[3]- if -median_height <= gap <= 12.0 * median_height:- candidates.append((abs(gap), line))- if not candidates:- return None- return min(candidates, key=lambda item: item[0])[1]---def _find_caption_number_peers(- caption_line: _LineItem,- lines: list[_LineItem],- page_size: tuple[float, float],- angle: int,- median_height: float,-) -> list[_LineItem]:- """查找与拆分 Table/表 标签同一视觉行的编号文本。"""-- caption_local_bbox = _rotate_bbox_to_upright(caption_line.bbox, page_size, angle)- peers: list[_LineItem] = []- for peer in lines:- if peer.source_index == caption_line.source_index:- continue- if not _TABLE_SPLIT_NUMBER_RE.match(peer.text.strip()):- continue- peer_local_bbox = _rotate_bbox_to_upright(peer.bbox, page_size, angle)- gap = peer_local_bbox[0] - caption_local_bbox[2]- if _bbox_axis_overlap_ratio(caption_local_bbox, peer_local_bbox, axis="y") >= 0.5 and 0.0 <= gap <= 4.0 * median_height:- peers.append(peer)- return sorted(- peers,- key=lambda peer: _rotate_bbox_to_upright(peer.bbox, page_size, angle)[0],- )---def _count_stable_columns(- rows: list[_VisualRow],- median_height: float,-) -> tuple[int, float]:- """分别聚类片段左边界、中心和右边界,返回最稳定的列分布。"""-- tolerance = max(3.0, median_height * 0.75)- best_result = (0, 0.0)- # 三种对齐方式分别聚类,避免把同一片段的不同锚点混算为多列。- for alignment in ("left", "center", "right"):- clusters: list[dict[str, Any]] = []- for row_index, row in enumerate(rows):- for fragment in row.fragments:- left, _top, right, _bottom = fragment.local_bbox- if alignment == "left":- anchor = left- elif alignment == "center":- anchor = (left + right) / 2- else:- anchor = right- cluster = next(- (item for item in clusters if abs(anchor - float(item["mean"])) <= tolerance),- None,- )- if cluster is None:- clusters.append({"mean": anchor, "values": [anchor], "rows": {row_index}})- else:- cluster["values"].append(anchor)- cluster["rows"].add(row_index)- cluster["mean"] = sum(cluster["values"]) / len(cluster["values"])- stable_coverages = [- len(cluster["rows"]) / len(rows)- for cluster in clusters- if len(cluster["rows"]) / len(rows) >= 0.5- ]- result = (- len(stable_coverages),- min(stable_coverages) if stable_coverages else 0.0,- )- # 仅在结果严格更优时更新,平局时保留既有的左对齐优先级。- if result > best_result:- best_result = result- return best_result---def _transform_axis_lines(- lines: list[_AxisLine],- page_size: tuple[float, float],- angle: int,-) -> list[_LocalAxisLine]:- """将原页面横竖线转入当前文本方向的局部坐标。"""-- output: list[_LocalAxisLine] = []- for line in lines:- local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, angle)- orientation: Literal["horizontal", "vertical"] = (- "horizontal" if local_bbox[2] - local_bbox[0] >= local_bbox[3] - local_bbox[1] else "vertical"- )- output.append(- _LocalAxisLine(- bbox=local_bbox,- original_bbox=line.bbox,- orientation=orientation,- width=line.width,- )- )- return output---def _merge_table_candidates(candidates: list[_TableCandidate]) -> list[_TableCandidate]:- """合并同方向且明显重叠的横线候选,避免同一表格重复输出。"""-- merged: list[_TableCandidate] = []- for candidate in sorted(candidates, key=lambda item: item.score, reverse=True):- target = next(- (- item- for item in merged- if item.angle == candidate.angle and _bbox_overlap_in_smaller(candidate.bbox, item.bbox) >= 0.2- ),- None,- )- if target is None:- merged.append(candidate)- continue- target.bbox = _bbox_union(target.bbox, candidate.bbox)- target.local_bbox = _bbox_union(target.local_bbox, candidate.local_bbox)- if target.core_bbox is None:- target.core_bbox = candidate.core_bbox- elif candidate.core_bbox is not None:- target.core_bbox = _bbox_union(target.core_bbox, candidate.core_bbox)- target.line_indices.update(candidate.line_indices)- target.score = max(target.score, candidate.score)- return sorted(merged, key=lambda item: (item.bbox[1], item.bbox[0]))---def _materialize_table_blocks(- source: _PageSource,- candidates: list[_TableCandidate],-) -> tuple[list[dict[str, Any]], set[int]]:- """为候选生成空间投影 content,仅认领投影成功的文本行。"""-- blocks: list[dict[str, Any]] = []- claimed: set[int] = set()- for candidate in sorted(candidates, key=lambda item: item.score, reverse=True):- if any(_bbox_overlap_in_smaller(candidate.bbox, block["bbox"]) >= 0.5 for block in blocks):- continue- output_angle = candidate.angle- projection_line_indices = _candidate_projection_line_indices(source, candidate)- try:- candidate_chars = [- char for line in source.lines if line.source_index in projection_line_indices for char in line.chars- ]- content = project_pdf_table_text(- candidate_chars,- candidate.bbox,- angle=candidate.angle,- )- except Exception as exc:- # 单个表格的字符投影异常只撤销该候选,不能中止整页提取。- logger.warning(f"Flash table projection failed and rolled back: bbox={candidate.bbox}, error={exc}")- continue- if not content or not content.strip():- continue- blocks.append(- {- "type": "table",- "bbox": candidate.bbox,- "angle": output_angle,- "content": content,- }- )- # 只认领候选明确接纳的视觉行,避免远标题与表格之间的正文被矩形 bbox 连带删除。- claimed.update(projection_line_indices)- blocks.sort(key=lambda block: (block["bbox"][1], block["bbox"][0]))- return blocks, claimed---def _bbox_overlap_in_first(first: BBox, second: BBox) -> float:- """计算交集面积占第一个 bbox 面积的比例。"""-- width = max(0.0, min(first[2], second[2]) - max(first[0], second[0]))- height = max(0.0, min(first[3], second[3]) - max(first[1], second[1]))- first_area = _bbox_area(first)- return width * height / first_area if first_area > 0 else 0.0---def _form_supersedes_nested_bbox(form_bbox: BBox, nested_bbox: BBox) -> bool:- """判断 Form 是否应整体吞并其内部面积明显更小的候选容器。"""-- form_area = _bbox_area(form_bbox)- nested_area = _bbox_area(nested_bbox)- return (- form_area > 0- and nested_area < 0.5 * form_area- and _bbox_overlap_in_first(nested_bbox, form_bbox) >= 0.9- )---def _select_form_image_bboxes(source: _PageSource) -> list[BBox]:- """按页面占比、行高和内部视觉证据筛选矢量 Form 图片候选。"""-- page_area = max(0.0, source.page_size[0]) * max(0.0, source.page_size[1])- if page_area <= 0 or not source.form_bboxes:- return []- effective_heights = [- _line_effective_height(line, line.bbox)- for line in source.lines- if line.angle == 0- ]- median_height = statistics.median(effective_heights) if effective_heights else 1.0- output: list[BBox] = []- for raw_bbox in source.form_bboxes:- bbox = _clip_bbox(_coerce_bbox(raw_bbox), source.page_size)- if bbox is None:- continue- width = bbox[2] - bbox[0]- height = bbox[3] - bbox[1]- area_ratio = _bbox_area(bbox) / page_area- if not (- _MIN_FORM_IMAGE_PAGE_AREA_RATIO <= area_ratio <= _MAX_FORM_IMAGE_PAGE_AREA_RATIO- and width >= 4.0 * median_height- and height >= 4.0 * median_height- ):- continue-- member_rows = {- line.visual_row_id if line.visual_row_id is not None else line.source_index- for line in source.lines- if _bbox_overlap_in_first(line.bbox, bbox) >= 0.9- }- internal_drawing_count = sum(- _bbox_overlap_in_first(drawing_line.bbox, bbox) >= 0.9- for drawing_line in source.drawing_lines- )- if len(member_rows) < 2 and internal_drawing_count < 4:- continue- output.append(bbox)- return sorted(output, key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]))---def _build_form_image_blocks(- source: _PageSource,- form_bboxes: list[BBox],- claimed_line_indices: set[int],-) -> tuple[list[dict[str, Any]], set[int]]:- """把 Form 及其完整内含文本输出为 image,并保持 source_index 唯一认领。"""-- if not form_bboxes:- return [], set()- members_by_candidate: list[list[_LineItem]] = [[] for _ in form_bboxes]- claimed: set[int] = set()- for line in source.lines:- if line.source_index in claimed_line_indices:- continue- matching_indices = [- candidate_index- for candidate_index, bbox in enumerate(form_bboxes)- if _bbox_overlap_in_first(line.bbox, bbox) >= 0.9- ]- if not matching_indices:- continue- candidate_index = min(- matching_indices,- key=lambda index: (_bbox_area(form_bboxes[index]), index),- )- members_by_candidate[candidate_index].append(line)- claimed.add(line.source_index)-- blocks = [- {- "type": "image",- "bbox": bbox,- "angle": 0,- "content": _image_members_to_content(members, source.page_size),- }- for bbox, members in zip(form_bboxes, members_by_candidate, strict=True)- ]- blocks.sort(key=lambda block: (block["bbox"][1], block["bbox"][0]))- return blocks, claimed---def _build_graphic_like_blocks(- source: _PageSource,- table_bboxes: list[BBox],- claimed_line_indices: set[int],-) -> tuple[list[dict[str, Any]], set[int]]:- """在表格认领后把紧凑绘图组件及其短标签聚成内部图形文本块。"""-- lines = [line for line in source.lines if line.source_index not in claimed_line_indices]- if len(lines) < 2 or len(source.drawing_lines) < 4:- return [], set()-- effective_heights = [- max(- 0.1,- line.effective_height- or min(- max(0.1, line.bbox[2] - line.bbox[0]),- max(0.1, line.bbox[3] - line.bbox[1]),- ),- )- for line in lines- ]- median_height = statistics.median(effective_heights)- lanes = _infer_graphic_text_lanes(lines, source.page_size, median_height)- candidates = _detect_graphic_candidates(- source.drawing_lines,- source.page_size,- median_height,- lanes,- table_bboxes,- )- if not candidates:- return [], set()-- row_groups: dict[tuple[int, int, int, int], list[_LineItem]] = {}- for line in lines:- lane_index = _graphic_lane_index(line.bbox, lanes)- if line.visual_row_id is None:- row_kind, row_identity = 1, line.source_index- else:- row_kind, row_identity = 0, line.visual_row_id- row_groups.setdefault(- (line.angle, row_kind, row_identity, lane_index),- [],- ).append(line)-- for row_lines in row_groups.values():- row_lane_index = _graphic_lane_index(row_lines[0].bbox, lanes)- matches: list[tuple[int, float, int]] = []- for candidate_index, candidate in enumerate(candidates):- if candidate.lane_index != row_lane_index:- continue- member_flags = [- _is_graphic_label_member(line, candidate.core_bbox, median_height)- for line in row_lines- ]- # 同一 pdftext 视觉行必须整体归属或整体保留,避免只吞掉 caption 的短碎片。- if not all(member_flags):- continue- inside_count = sum(- _point_in_bbox(- (_bbox_center_x(line.bbox), _bbox_center_y(line.bbox)),- candidate.core_bbox,- )- for line in row_lines- )- mean_distance = statistics.fmean(- _bbox_distance(line.bbox, candidate.core_bbox) for line in row_lines- )- matches.append((-inside_count, mean_distance, candidate_index))- if not matches:- continue- candidate_index = min(matches)[2]- candidates[candidate_index].line_indices.update(line.source_index for line in row_lines)-- blocks: list[dict[str, Any]] = []- claimed: set[int] = set()- lines_by_index = {line.source_index: line for line in lines}- for candidate in candidates:- members = [- lines_by_index[source_index]- for source_index in sorted(candidate.line_indices)- if source_index in lines_by_index- ]- if len(members) < 2:- continue- block = _graphic_members_to_block(candidate, members, source.page_size)- if block is None:- continue- blocks.append(block)- claimed.update(line.source_index for line in members)-- blocks.sort(key=lambda block: (block["bbox"][1], block["bbox"][0]))- return blocks, claimed---def _infer_graphic_text_lanes(- lines: list[_LineItem],- page_size: tuple[float, float],- median_height: float,-) -> list[_TextLane]:- """用横排正文推断页内栏带,供不同角度的图形标签共享栏归属。"""-- line_geometry = [(line, line.bbox) for line in lines if line.angle == 0]- if not line_geometry:- return [_TextLane(left=0.0, right=page_size[0])]- angle_heights = [_line_effective_height(line, bbox) for line, bbox in line_geometry]- angle_median_height = statistics.median(angle_heights) if angle_heights else median_height- lanes = [- lane- for lane in _infer_text_lanes(- line_geometry,- page_size[0],- angle_median_height,- )- if not lane.is_span- ]- return lanes or [_TextLane(left=0.0, right=page_size[0])]---def _graphic_lane_index(bbox: BBox, lanes: list[_TextLane]) -> int:- """按中心点、水平覆盖和距离为 bbox 选择唯一栏带。"""-- center_x = _bbox_center_x(bbox)- best_index = 0- best_score = (-1, -1.0, -math.inf)- for lane_index, lane in enumerate(lanes):- inside = int(lane.left <= center_x <= lane.right)- overlap = max(0.0, min(bbox[2], lane.right) - max(bbox[0], lane.left))- if inside:- distance = 0.0- else:- distance = min(abs(center_x - lane.left), abs(center_x - lane.right))- score = (inside, overlap, -distance)- if score > best_score:- best_score = score- best_index = lane_index- return best_index---def _detect_graphic_candidates(- drawing_lines: list[_AxisLine],- page_size: tuple[float, float],- median_height: float,- lanes: list[_TextLane],- table_bboxes: list[BBox],-) -> list[_GraphicCandidate]:- """从非表格绘图线连通分量中筛选尺寸受限的图形容器。"""-- tolerance = max(2.0, 0.75 * median_height)- candidates: list[_GraphicCandidate] = []- for component in _connected_drawing_line_components(drawing_lines, tolerance):- horizontal_count = sum(line.orientation == "horizontal" for line in component)- vertical_count = len(component) - horizontal_count- core_bbox = _bbox_union_many([line.bbox for line in component])- width = core_bbox[2] - core_bbox[0]- height = core_bbox[3] - core_bbox[1]- if (- len(component) < 4- or horizontal_count < 2- or vertical_count < 2- or width < 4.0 * median_height- or height < 3.0 * median_height- or width > 0.5 * page_size[0]- or height > 0.5 * page_size[1]- ):- continue- if any(_bbox_overlap_in_smaller(core_bbox, table_bbox) >= 0.5 for table_bbox in table_bboxes):- continue- candidates.append(- _GraphicCandidate(- core_bbox=core_bbox,- lane_index=_graphic_lane_index(core_bbox, lanes),- )- )- return candidates---def _connected_drawing_line_components(- drawing_lines: list[_AxisLine],- tolerance: float,-) -> list[list[_AxisLine]]:- """按 bbox 间距连接相邻绘图线,并返回互不重叠的连通分量。"""-- parents = list(range(len(drawing_lines)))-- def find(index: int) -> int:- """查找绘图线连通分量的根节点。"""-- while parents[index] != index:- parents[index] = parents[parents[index]]- index = parents[index]- return index-- def union(first_index: int, second_index: int) -> None:- """合并两个距离满足条件的绘图线分量。"""-- first_root = find(first_index)- second_root = find(second_index)- if first_root != second_root:- parents[second_root] = first_root-- for first_index, first in enumerate(drawing_lines):- for second_index in range(first_index + 1, len(drawing_lines)):- if _bbox_distance(first.bbox, drawing_lines[second_index].bbox) <= tolerance:- union(first_index, second_index)-- components: dict[int, list[_AxisLine]] = {}- for line_index, line in enumerate(drawing_lines):- components.setdefault(find(line_index), []).append(line)- return list(components.values())---def _is_graphic_label_member(- line: _LineItem,- core_bbox: BBox,- median_height: float,-) -> bool:- """判断短文本是否位于图形核心内部或对应轴向的邻近标签区。"""-- center = (_bbox_center_x(line.bbox), _bbox_center_y(line.bbox))- if _point_in_bbox(center, core_bbox):- return True-- line_height = max(- 0.1,- line.effective_height- or min(- max(0.1, line.bbox[2] - line.bbox[0]),- max(0.1, line.bbox[3] - line.bbox[1]),- ),- )- if line.angle in {90, 270}:- primary_length = line.bbox[3] - line.bbox[1]- core_primary_length = core_bbox[3] - core_bbox[1]- else:- primary_length = line.bbox[2] - line.bbox[0]- core_primary_length = core_bbox[2] - core_bbox[0]- if primary_length > min(5.0 * line_height, 0.5 * core_primary_length):- return False-- horizontal_gap = max(core_bbox[0] - line.bbox[2], line.bbox[0] - core_bbox[2], 0.0)- vertical_gap = max(core_bbox[1] - line.bbox[3], line.bbox[1] - core_bbox[3], 0.0)- if _bbox_axis_overlap_ratio(line.bbox, core_bbox, axis="x") >= 0.15:- return vertical_gap <= 2.5 * median_height- if _bbox_axis_overlap_ratio(line.bbox, core_bbox, axis="y") >= 0.15:- horizontal_limit = max(2.5 * median_height, 0.2 * (core_bbox[2] - core_bbox[0]))- return horizontal_gap <= horizontal_limit- return False---def _image_members_to_content(- members: list[_LineItem],- page_size: tuple[float, float],-) -> str:- """按视觉行和页内位置生成图片内部文本,保留不同视觉行之间的换行。"""-- row_groups: dict[tuple[int, int, int], list[_LineItem]] = {}- for line in members:- if line.visual_row_id is None:- row_kind, row_identity = 1, line.source_index- else:- row_kind, row_identity = 0, line.visual_row_id- row_groups.setdefault((line.angle, row_kind, row_identity), []).append(line)-- rows: list[tuple[BBox, str]] = []- for row_lines in row_groups.values():- row_bbox = _bbox_union_many([line.bbox for line in row_lines])- angle = row_lines[0].angle- local_geometry = [- (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))- for line in row_lines- ]- content = _join_formula_visual_row(local_geometry, page_size)- if content:- rows.append((row_bbox, content))- rows.sort(key=lambda item: (item[0][1], item[0][0]))- return _sanitize_pdf_control_text(- "\n".join(row_content for _row_bbox, row_content in rows),- preserve_newlines=True,- ).strip()---def _graphic_members_to_block(- candidate: _GraphicCandidate,- members: list[_LineItem],- page_size: tuple[float, float],-) -> dict[str, Any] | None:- """生成含内部文本的矢量图 image block,并合并绘图核心与标签 bbox。"""-- content = _image_members_to_content(members, page_size)- if not content:- return None- return {- "type": "image",- "bbox": _bbox_union(candidate.core_bbox, _bbox_union_many([line.bbox for line in members])),- "angle": 0,- "content": content,- }---def _bbox_area(bbox: BBox) -> float:- """返回合法 bbox 的非负面积。"""-- return max(0.0, bbox[2] - bbox[0]) * max(0.0, bbox[3] - bbox[1])---def _build_raster_image_blocks(- source: _PageSource,- container_blocks: list[dict[str, Any]],- claimed_line_indices: set[int],-) -> tuple[list[dict[str, Any]], set[int]]:- """过滤点阵图、避让高优先级容器,并唯一认领图片内部的原生文本。"""-- page_area = max(0.0, source.page_size[0]) * max(0.0, source.page_size[1])- if page_area <= 0:- return [], set()-- container_bboxes = [- bbox- for block in container_blocks- if (bbox := _coerce_bbox(block.get("bbox"))) is not None- ]- candidate_bboxes: list[BBox] = []- for raw_bbox in source.image_bboxes:- bbox = _clip_bbox(_coerce_bbox(raw_bbox), source.page_size)- if bbox is None or _bbox_area(bbox) / page_area < _MIN_RASTER_IMAGE_PAGE_AREA_RATIO:- continue- if any(- _bbox_overlap_in_smaller(bbox, container_bbox) >= _IMAGE_CONTAINER_OVERLAP_THRESHOLD- for container_bbox in container_bboxes- ):- continue- candidate_bboxes.append(bbox)- if not candidate_bboxes:- return [], set()-- members_by_candidate: list[list[_LineItem]] = [[] for _ in candidate_bboxes]- claimed: set[int] = set()- for line in source.lines:- if line.source_index in claimed_line_indices:- continue- center = (_bbox_center_x(line.bbox), _bbox_center_y(line.bbox))- matching_indices = [- candidate_index- for candidate_index, bbox in enumerate(candidate_bboxes)- if _point_in_bbox(center, bbox)- ]- if not matching_indices:- continue- # 重叠点阵图共享内部文本时归属最小容器,避免 content 重复。- candidate_index = min(- matching_indices,- key=lambda index: (_bbox_area(candidate_bboxes[index]), index),- )- members_by_candidate[candidate_index].append(line)- claimed.add(line.source_index)-- blocks = [- {- "type": "image",- "bbox": bbox,- "angle": 0,- "content": _image_members_to_content(members, source.page_size),- }- for bbox, members in zip(candidate_bboxes, members_by_candidate, strict=True)- ]- blocks.sort(key=lambda block: (block["bbox"][1], block["bbox"][0]))- return blocks, claimed---def _candidate_projection_line_indices(- source: _PageSource,- candidate: _TableCandidate,-) -> set[int]:- """合并核心成员、同基线续段及非零角度表格的表头文本。"""-- line_indices = set(candidate.line_indices)- if candidate.core_bbox is not None:- for line in source.lines:- if _point_in_bbox(- (_bbox_center_x(line.bbox), _bbox_center_y(line.bbox)),- candidate.core_bbox,- ):- line_indices.add(line.source_index)- if candidate.angle == 0:- _expand_candidate_same_baseline_members(source, candidate, line_indices)- return line_indices- if candidate.core_bbox is None:- return line_indices-- candidate_local_bbox = _rotate_bbox_to_upright(- candidate.bbox,- source.page_size,- candidate.angle,- )- core_local_bbox = _rotate_bbox_to_upright(- candidate.core_bbox,- source.page_size,- candidate.angle,- )- for line in source.lines:- if line.angle != candidate.angle:- continue- page_center = (_bbox_center_x(line.bbox), _bbox_center_y(line.bbox))- if not _point_in_bbox(page_center, candidate.bbox):- continue- local_bbox = _rotate_bbox_to_upright(- line.bbox,- source.page_size,- candidate.angle,- )- local_center_y = _bbox_center_y(local_bbox)- if not candidate_local_bbox[1] <= local_center_y <= candidate_local_bbox[3]:- continue- if _bbox_axis_overlap_ratio(local_bbox, core_local_bbox, axis="x") < 0.05:- continue- line_indices.add(line.source_index)- return line_indices---def _expand_candidate_same_baseline_members(- source: _PageSource,- candidate: _TableCandidate,- line_indices: set[int],-) -> None:- """迭代吸收完整候选框内与已认领成员同基线相邻的 angle=0 续段。"""-- local_bboxes = {- line.source_index: _rotate_bbox_to_upright(- line.bbox,- source.page_size,- candidate.angle,- )- for line in source.lines- if line.angle == candidate.angle- }- changed = True- while changed:- changed = False- selected_lines = [- line- for line in source.lines- if line.angle == candidate.angle and line.source_index in line_indices- ]- for line in source.lines:- if line.angle != candidate.angle or line.source_index in line_indices:- continue- if not _point_in_bbox(- (_bbox_center_x(line.bbox), _bbox_center_y(line.bbox)),- candidate.bbox,- ):- continue- line_bbox = local_bboxes[line.source_index]- line_height = _line_effective_height(line, line_bbox)- for selected in selected_lines:- if (- line.font_signature is not None- and selected.font_signature is not None- and line.font_signature != selected.font_signature- ):- continue- selected_bbox = local_bboxes[selected.source_index]- if not _same_baseline_geometry(- line_bbox,- line_height,- selected_bbox,- _line_effective_height(selected, selected_bbox),- ):- continue- line_indices.add(line.source_index)- changed = True- break---def _merge_same_baseline_text_lines(- lines: list[_LineItem],- page_size: tuple[float, float],- table_bboxes: list[BBox],-) -> list[_LineItem]:- """在表格认领后合并同基线、同字体且水平邻近的正文 run。"""-- if len(lines) < 2:- return list(lines)- local_bboxes = [_rotate_bbox_to_upright(line.bbox, page_size, line.angle) for line in lines]- parents = list(range(len(lines)))-- def find(index: int) -> int:- """查找同行合并并查集的根节点。"""-- while parents[index] != index:- parents[index] = parents[parents[index]]- index = parents[index]- return index-- def union(left_index: int, right_index: int) -> None:- """合并两个满足同行条件的文本 run。"""-- left_root = find(left_index)- right_root = find(right_index)- if left_root != right_root:- parents[right_root] = left_root-- for left_index, left_line in enumerate(lines):- for right_index in range(left_index + 1, len(lines)):- right_line = lines[right_index]- if _can_merge_same_baseline_pair(- left_line,- local_bboxes[left_index],- right_line,- local_bboxes[right_index],- table_bboxes,- ):- union(left_index, right_index)-- groups: dict[int, list[int]] = {}- for index in range(len(lines)):- groups.setdefault(find(index), []).append(index)-- output: list[_LineItem] = []- for indices in groups.values():- if len(indices) == 1:- output.append(lines[indices[0]])- continue- indices.sort(key=lambda index: (local_bboxes[index][0], local_bboxes[index][1], lines[index].source_index))- output.append(_merge_same_baseline_group(indices, lines, local_bboxes, page_size))- output.sort(- key=lambda line: (- line.angle,- _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[1],- _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[0],- line.source_index,- )- )- return output---def _merge_post_semantic_text_runs(- lines: list[_LineItem],- page_size: tuple[float, float],- table_bboxes: list[BBox],-) -> list[_LineItem]:- """在容器、公式和标题结束后合并紧贴同基线的普通混合字体 run。"""-- if len(lines) < 2:- return list(lines)- local_bboxes = [- _rotate_bbox_to_upright(line.bbox, page_size, line.angle)- for line in lines- ]- parents = list(range(len(lines)))-- def find(index: int) -> int:- """查找后处理同行合并分量的根节点。"""-- while parents[index] != index:- parents[index] = parents[parents[index]]- index = parents[index]- return index-- def union(first_index: int, second_index: int) -> None:- """合并两个后处理同行分量。"""-- first_root = find(first_index)- second_root = find(second_index)- if first_root != second_root:- parents[second_root] = first_root-- for first_index, first_line in enumerate(lines):- if first_line.semantic_type is not None:- continue- first_bbox = local_bboxes[first_index]- first_height = _line_effective_height(first_line, first_bbox)- for second_index in range(first_index + 1, len(lines)):- second_line = lines[second_index]- if second_line.semantic_type is not None or first_line.angle != second_line.angle:- continue- if _connection_crosses_table(- first_line.bbox,- second_line.bbox,- table_bboxes,- ):- continue- second_bbox = local_bboxes[second_index]- second_height = _line_effective_height(second_line, second_bbox)- if _post_semantic_same_baseline_geometry(- first_bbox,- first_height,- second_bbox,- second_height,- ):- union(first_index, second_index)-- groups: dict[int, list[int]] = {}- for index in range(len(lines)):- groups.setdefault(find(index), []).append(index)- output: list[_LineItem] = []- for indices in groups.values():- if len(indices) == 1:- output.append(lines[indices[0]])- continue- indices.sort(- key=lambda index: (- local_bboxes[index][0],- local_bboxes[index][1],- lines[index].source_index,- )- )- output.append(- _merge_same_baseline_group(- indices,- lines,- local_bboxes,- page_size,- )- )- output.sort(- key=lambda line: (- line.angle,- _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[1],- _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[0],- line.source_index,- )- )- return output---def _post_semantic_same_baseline_geometry(- first_bbox: BBox,- first_height: float,- second_bbox: BBox,- second_height: float,-) -> bool:- """放宽上下标字号差异,仅合并水平紧贴且垂直充分交叠的普通 run。"""-- pair_height = max(first_height, second_height)- if min(first_height, second_height) <= 0 or pair_height / min(- first_height,- second_height,- ) > 1.6:- return False- y_overlap = max(- 0.0,- min(first_bbox[3], second_bbox[3]) - max(first_bbox[1], second_bbox[1]),- )- shorter_bbox_height = max(- 0.1,- min(first_bbox[3] - first_bbox[1], second_bbox[3] - second_bbox[1]),- )- if y_overlap / shorter_bbox_height < 0.7:- return False- left_bbox, right_bbox = sorted((first_bbox, second_bbox), key=lambda bbox: bbox[0])- horizontal_gap = right_bbox[0] - left_bbox[2]- return -0.2 * pair_height <= horizontal_gap <= max(2.0, 0.35 * pair_height)---def _can_merge_same_baseline_pair(- first: _LineItem,- first_bbox: BBox,- second: _LineItem,- second_bbox: BBox,- table_bboxes: list[BBox],-) -> bool:- """判断两个剩余文本 run 是否属于同一条物理基线。"""-- if first.angle != second.angle:- return False- if first.semantic_type != second.semantic_type:- return False- if first.visual_row_id == second.visual_row_id and (first.split_from_row or second.split_from_row):- return False- if _connection_crosses_table(first.bbox, second.bbox, table_bboxes):- return False- first_height = _line_effective_height(first, first_bbox)- second_height = _line_effective_height(second, second_bbox)- has_compatible_dominant_font = not (- first.font_signature is None- or second.font_signature is None- or first.font_coverage < 0.75- or second.font_coverage < 0.75- or first.font_signature != second.font_signature- )- if has_compatible_dominant_font and _same_baseline_geometry(- first_bbox,- first_height,- second_bbox,- second_height,- ):- return True- return _touching_same_baseline_geometry(- first_bbox,- first_height,- second_bbox,- second_height,- )---def _touching_same_baseline_geometry(- first_bbox: BBox,- first_height: float,- second_bbox: BBox,- second_height: float,-) -> bool:- """为低字体覆盖率 run 提供严格的紧贴同基线几何兜底。"""-- pair_height = max(first_height, second_height)- y_overlap = max(0.0, min(first_bbox[3], second_bbox[3]) - max(first_bbox[1], second_bbox[1]))- smaller_bbox_height = max(- 0.1,- min(first_bbox[3] - first_bbox[1], second_bbox[3] - second_bbox[1]),- )- if y_overlap / smaller_bbox_height < 0.7:- return False- if abs(_bbox_center_y(first_bbox) - _bbox_center_y(second_bbox)) > 0.5 * pair_height:- return False- left_bbox, right_bbox = sorted((first_bbox, second_bbox), key=lambda bbox: bbox[0])- signed_gap = right_bbox[0] - left_bbox[2]- return -0.15 * pair_height <= signed_gap <= 0.75---def _same_baseline_geometry(- first_bbox: BBox,- first_height: float,- second_bbox: BBox,- second_height: float,- *,- maximum_gap: float | None = None,-) -> bool:- """仅依据行高、垂直交叠和水平净空判断两个局部 bbox 是否同基线相邻。"""-- pair_height = max(first_height, second_height)- if min(first_height, second_height) <= 0 or pair_height / min(first_height, second_height) > 1.35:- return False- y_overlap = max(0.0, min(first_bbox[3], second_bbox[3]) - max(first_bbox[1], second_bbox[1]))- shorter_bbox_height = max(- 0.1,- min(first_bbox[3] - first_bbox[1], second_bbox[3] - second_bbox[1]),- )- if y_overlap / shorter_bbox_height < 0.7 and abs(first_bbox[3] - second_bbox[3]) > 0.25 * pair_height:- return False- left_bbox, right_bbox = sorted((first_bbox, second_bbox), key=lambda bbox: bbox[0])- signed_gap = right_bbox[0] - left_bbox[2]- gap_limit = max(3.0, 0.75 * pair_height) if maximum_gap is None else maximum_gap- return -0.25 * pair_height <= signed_gap <= gap_limit---def _merge_same_baseline_group(- indices: list[int],- lines: list[_LineItem],- local_bboxes: list[BBox],- page_size: tuple[float, float],-) -> _LineItem:- """按局部 x 顺序合并一个同基线分量,并保留全部字符与几何信息。"""-- members = [lines[index] for index in indices]- content_parts = [members[0].text.strip()]- for previous_index, current_index in zip(indices, indices[1:]):- previous_bbox = local_bboxes[previous_index]- current_bbox = local_bboxes[current_index]- signed_gap = current_bbox[0] - previous_bbox[2]- glyph_width = statistics.median(- [- width- for member in (lines[previous_index], lines[current_index])- if (width := _median_native_glyph_width(member, page_size)) is not None- ]- or [1.0]- )- separator = "" if signed_gap <= max(0.5, 0.25 * glyph_width) else " "- content_parts.extend([separator, lines[current_index].text.strip()])-- merged = _LineItem(- text="".join(content_parts).strip(),- bbox=_bbox_union_many([member.bbox for member in members]),- angle=members[0].angle,- source_index=min(member.source_index for member in members),- chars=[char for member in members for char in member.chars],- visual_row_id=min(- (member.visual_row_id for member in members if member.visual_row_id is not None),- default=None,- ),- run_index=min(member.run_index for member in members),- effective_height=statistics.median(member.effective_height for member in members),- font_signature=members[0].font_signature,- font_coverage=min(member.font_coverage for member in members),- dominant_font_weight=statistics.median(- member.dominant_font_weight- for member in members- if member.dominant_font_weight is not None- )- if any(member.dominant_font_weight is not None for member in members)- else None,- median_glyph_width=statistics.median(- member.median_glyph_width- for member in members- if member.median_glyph_width is not None- )- if any(member.median_glyph_width is not None for member in members)- else None,- split_from_row=any(member.split_from_row for member in members),- semantic_type=members[0].semantic_type,- )- if merged.chars:- _fill_native_typography(merged, page_size)- return merged---def _median_native_glyph_width(line: _LineItem, page_size: tuple[float, float]) -> float | None:- """返回单个原生 run 的可见字符中位宽度,缺少字符时返回空。"""-- if line.median_glyph_width is not None:- return line.median_glyph_width- widths: list[float] = []- for char in line.chars:- raw_char = str(char.get("char") or "")- bbox = _clip_bbox(_coerce_bbox(char.get("bbox")), page_size)- if not raw_char.isprintable() or raw_char.isspace() or bbox is None:- continue- local_bbox = _rotate_bbox_to_upright(bbox, page_size, line.angle)- widths.append(max(0.1, local_bbox[2] - local_bbox[0]))- line.median_glyph_width = statistics.median(widths) if widths else None- return line.median_glyph_width---def _build_formula_like_blocks(- lines: list[_LineItem],- table_bboxes: list[BBox],- page_size: tuple[float, float],-) -> tuple[list[dict[str, Any]], list[_LineItem]]:- """仅依据栏带、右侧短锚点和空间连通关系聚合公式状区域。"""-- blocks: list[dict[str, Any]] = []- claimed_source_indices: set[int] = set()- for angle in sorted({line.angle for line in lines}):- angle_geometry = [- (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))- for line in lines- if line.angle == angle- ]- if len(angle_geometry) < 2:- continue- effective_heights = [_line_effective_height(line, bbox) for line, bbox in angle_geometry]- median_height = statistics.median(effective_heights) if effective_heights else 1.0- local_page_width = page_size[1] if angle in {90, 270} else page_size[0]- lanes = _infer_text_lanes(angle_geometry, local_page_width, median_height)- for lane in lanes:- if lane.is_span or len(lane.lines) < 2:- continue- lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))- dominant_body_font = _infer_formula_body_font(lane, median_height)- anchors = _find_formula_spatial_anchors(- lane,- median_height,- dominant_body_font,- )- if not anchors:- continue- anchor_centers = [_bbox_center_y(anchor.bbox) for anchor in anchors]- lane_top = min(bbox[1] for _line, bbox in lane.lines)- lane_bottom = max(bbox[3] for _line, bbox in lane.lines)- for anchor_index, anchor in enumerate(anchors):- anchor_line = anchor.line- if anchor_line.source_index in claimed_source_indices:- continue- band_top = lane_top- band_bottom = lane_bottom- if anchor_index > 0:- band_top = max(- band_top,- (anchor_centers[anchor_index - 1] + anchor_centers[anchor_index]) / 2.0,- )- if anchor_index + 1 < len(anchors):- band_bottom = min(- band_bottom,- (anchor_centers[anchor_index] + anchor_centers[anchor_index + 1]) / 2.0,- )- members = _grow_formula_spatial_component(- lane,- anchor,- band_top,- band_bottom,- claimed_source_indices,- table_bboxes,- dominant_body_font,- median_height,- )- if len(members) < 2:- continue- if len(members) == 2 and _bbox_axis_overlap_ratio(- members[0][1],- members[1][1],- axis="y",- ) < 0.2:- continue- block = _formula_members_to_block(- members,- page_size,- angle,- anchor_source_index=anchor_line.source_index,- )- if block is None:- continue- blocks.append(block)- claimed_source_indices.update(line.source_index for line, _bbox in members)-- remaining_lines = [line for line in lines if line.source_index not in claimed_source_indices]- return blocks, remaining_lines+"""Flash PDF 公共提取入口。+原生文本处理位于 native_pdf 内部包;需要 OCR 时统一委托 Hybrid low。+"""-def _find_formula_spatial_anchors(- lane: _TextLane,- median_height: float,- dominant_body_font: tuple[str, int] | None = None,-) -> list[_FormulaAnchor]:- """查找栏带右缘短块或带编号后缀的非正文字体公式锚点。"""-- lane_width = max(0.1, lane.right - lane.left)- body_interval = _formula_lane_body_interval(lane, median_height)- if body_interval is None:- return []- body_top, body_bottom = body_interval- anchors: list[_FormulaAnchor] = []- for line, bbox in lane.lines:- line_height = _line_effective_height(line, bbox)- line_width = bbox[2] - bbox[0]- is_short_right_anchor = line_width <= max(4.0 * line_height, 0.12 * lane_width)- has_formula_number_suffix = _split_trailing_formula_number(line.text) is not None- is_wide_numbered_anchor = (- has_formula_number_suffix- and line_width <= 0.75 * lane_width- and dominant_body_font is not None- and (- line.font_signature != dominant_body_font- or line.font_coverage < 0.75- )- )- if not is_short_right_anchor and not is_wide_numbered_anchor:- continue- same_row_fragments = [- other_line- for other_line, _other_bbox in lane.lines- if line.visual_row_id is not None- and other_line.visual_row_id == line.visual_row_id- and (line.split_from_row or other_line.split_from_row)- ]- if len(same_row_fragments) >= 3 and not any(- other_line.font_coverage < 0.75- or (- dominant_body_font is not None- and other_line.font_signature != dominant_body_font- )- for other_line in same_row_fragments- if other_line.source_index != line.source_index- ):- # 一条粗行被多个大空格拆成密集词组时更像普通排版行,不能把末词当作公式编号锚点。- continue- if abs(lane.right - bbox[2]) > max(3.0, 0.02 * lane_width):- continue- center_y = _bbox_center_y(bbox)- detached_below_body = body_bottom < center_y <= body_bottom + 6.0 * median_height- if not body_top <= center_y <= body_bottom and not detached_below_body:- continue- has_left_peer = any(- other_line.source_index != line.source_index- and other_bbox[2] - other_bbox[0] <= 0.75 * lane_width- and _bbox_center_x(other_bbox) < bbox[0]- and (- _formula_detached_seed_vertical_match(- bbox,- line_height,- other_bbox,- _line_effective_height(other_line, other_bbox),- )- if detached_below_body- else _formula_seed_vertical_match(- bbox,- line_height,- other_bbox,- _line_effective_height(other_line, other_bbox),- )- )- for other_line, other_bbox in lane.lines- )- if has_left_peer:- anchors.append(- _FormulaAnchor(- line=line,- bbox=bbox,- detached_below_body=detached_below_body,- )- )- return _deduplicate_formula_anchors(anchors, median_height)---def _infer_formula_body_font(- lane: _TextLane,- median_height: float,-) -> tuple[str, int] | None:- """从栏内常规宽正文行推断 dominant font,供公式扩张排除正文前缀。"""-- lane_width = max(0.1, lane.right - lane.left)- font_counts: dict[tuple[str, int], int] = {}- for line, bbox in lane.lines:- line_height = _line_effective_height(line, bbox)- if bbox[2] - bbox[0] < 0.35 * lane_width:- continue- if not 0.8 * median_height <= line_height <= 1.25 * median_height:- continue- if line.font_signature is None or line.font_coverage < 0.75:- continue- font_counts[line.font_signature] = font_counts.get(line.font_signature, 0) + 1- if not font_counts:- return None- return max(font_counts.items(), key=lambda item: (item[1], item[0]))[0]---def _formula_lane_body_interval(- lane: _TextLane,- median_height: float,-) -> tuple[float, float] | None:- """用连续出现的常规宽行确定栏带正文纵向范围,排除孤立页眉。"""-- lane_width = max(0.1, lane.right - lane.left)- body_lines = sorted(- (- item- for item in lane.lines- if item[1][2] - item[1][0]- >= max(4.0 * _line_effective_height(*item), 0.35 * lane_width)- ),- key=lambda item: (item[1][1], item[1][0]),- )- if len(body_lines) < 3:- return None- dense_lines: list[tuple[_LineItem, BBox]] = []- for index, item in enumerate(body_lines):- has_close_previous = index > 0 and item[1][1] - body_lines[index - 1][1][3] <= 1.5 * median_height- has_close_next = (- index + 1 < len(body_lines)- and body_lines[index + 1][1][1] - item[1][3] <= 1.5 * median_height- )- if has_close_previous or has_close_next:- dense_lines.append(item)- if len(dense_lines) < 3:- return None- return (- min(bbox[1] for _line, bbox in dense_lines),- max(bbox[3] for _line, bbox in dense_lines),- )---def _deduplicate_formula_anchors(- anchors: list[_FormulaAnchor],- median_height: float,-) -> list[_FormulaAnchor]:- """同一高度出现多个右缘短块时只保留最靠右的空间锚点。"""-- if not anchors:- return []- output: list[_FormulaAnchor] = []- tolerance = max(1.5, 0.35 * median_height)- for anchor in sorted(anchors, key=lambda item: (_bbox_center_y(item.bbox), -item.bbox[2])):- if output and abs(_bbox_center_y(anchor.bbox) - _bbox_center_y(output[-1].bbox)) <= tolerance:- if (anchor.bbox[2], -anchor.bbox[0]) > (output[-1].bbox[2], -output[-1].bbox[0]):- output[-1] = anchor- continue- output.append(anchor)- return output---def _grow_formula_spatial_component(- lane: _TextLane,- anchor: _FormulaAnchor,- band_top: float,- band_bottom: float,- claimed_source_indices: set[int],- table_bboxes: list[BBox],- dominant_body_font: tuple[str, int] | None,- median_height: float,-) -> list[tuple[_LineItem, BBox]]:- """从右缘锚点的左侧首批成员出发,按二维邻接扩展公式分量。"""-- anchor_line, anchor_bbox = anchor.line, anchor.bbox- anchor_geometry = (anchor_line, anchor_bbox)- lane_width = max(0.1, lane.right - lane.left)- candidates = [- item- for item in lane.lines- if item[0].source_index not in claimed_source_indices- and item[1][2] - item[1][0] <= 0.8 * lane_width- and band_top <= _bbox_center_y(item[1]) <= band_bottom- and not _is_formula_body_barrier(- item,- lane,- dominant_body_font,- median_height,- )- and not _is_formula_body_prefix(- item,- lane,- anchor_geometry,- dominant_body_font,- median_height,- )- ]- seeds = [- item- for item in candidates- if item[0].source_index != anchor_line.source_index- and _bbox_center_x(item[1]) < anchor_bbox[0]- and (- _formula_detached_seed_vertical_match(- anchor_bbox,- _line_effective_height(anchor_line, anchor_bbox),- item[1],- _line_effective_height(*item),- )- if anchor.detached_below_body- else _formula_seed_vertical_match(- anchor_bbox,- _line_effective_height(anchor_line, anchor_bbox),- item[1],- _line_effective_height(*item),- )- )- and not _connection_crosses_table(anchor_line.bbox, item[0].bbox, table_bboxes)- ]- if not seeds:- return []-- members = [anchor_geometry, *seeds]- member_sources = {line.source_index for line, _bbox in members}- changed = True- while changed:- changed = False- for candidate in candidates:- candidate_line, candidate_bbox = candidate- if candidate_line.source_index in member_sources:- continue- if any(- _formula_lines_are_connected(- member_line,- member_bbox,- candidate_line,- candidate_bbox,- table_bboxes,- )- for member_line, member_bbox in members- ):- members.append(candidate)- member_sources.add(candidate_line.source_index)- changed = True- return members---def _is_formula_body_barrier(- candidate: tuple[_LineItem, BBox],- lane: _TextLane,- dominant_body_font: tuple[str, int] | None,- median_height: float,-) -> bool:- """识别近满栏、高置信正文行,阻止公式连通分量跨越正文边界。"""-- if dominant_body_font is None:- return False- line, bbox = candidate- lane_width = max(0.1, lane.right - lane.left)- line_height = _line_effective_height(line, bbox)- return (- line.font_signature == dominant_body_font- and bbox[2] - bbox[0] >= 0.85 * lane_width- and 0.8 * median_height <= line_height <= 1.25 * median_height- )---def _is_formula_body_prefix(- candidate: tuple[_LineItem, BBox],- lane: _TextLane,- anchor: tuple[_LineItem, BBox],- dominant_body_font: tuple[str, int] | None,- median_height: float,-) -> bool:- """识别锚点上方左对齐的常规正文行,防止公式空间扩张越界认领。"""-- if dominant_body_font is None:- return False- line, bbox = candidate- anchor_line, anchor_bbox = anchor- line_height = _line_effective_height(line, bbox)- anchor_height = _line_effective_height(anchor_line, anchor_bbox)- if _bbox_center_y(bbox) > _bbox_center_y(anchor_bbox) - 0.2 * max(line_height, anchor_height):- return False- if abs(bbox[0] - lane.left) > max(3.0, 0.75 * median_height):- return False- return (- line.font_signature == dominant_body_font- and line.font_coverage >= 0.75- and 0.8 * median_height <= line_height <= 1.25 * median_height- )---def _formula_detached_seed_vertical_match(- anchor_bbox: BBox,- anchor_height: float,- candidate_bbox: BBox,- candidate_height: float,-) -> bool:- """放宽正文密集区下方锚点的同高匹配,以接纳多行分段公式底部。"""-- has_vertical_overlap = min(anchor_bbox[3], candidate_bbox[3]) > max(anchor_bbox[1], candidate_bbox[1])- center_difference = abs(_bbox_center_y(anchor_bbox) - _bbox_center_y(candidate_bbox))- return has_vertical_overlap or center_difference <= max(anchor_height, candidate_height)---def _formula_seed_vertical_match(- anchor_bbox: BBox,- anchor_height: float,- candidate_bbox: BBox,- candidate_height: float,-) -> bool:- """判断左侧短行是否与右缘锚点处在同一公式高度带。"""-- overlap_ratio = _bbox_axis_overlap_ratio(anchor_bbox, candidate_bbox, axis="y")- center_difference = abs(_bbox_center_y(anchor_bbox) - _bbox_center_y(candidate_bbox))- return overlap_ratio >= 0.3 or center_difference <= 0.6 * max(anchor_height, candidate_height)---def _formula_lines_are_connected(- first_line: _LineItem,- first_bbox: BBox,- second_line: _LineItem,- second_bbox: BBox,- table_bboxes: list[BBox],-) -> bool:- """按垂直接近和水平覆盖判断两个公式成员是否空间连通。"""-- if first_line.angle != second_line.angle:- return False- if _connection_crosses_table(first_line.bbox, second_line.bbox, table_bboxes):- return False- first_height = _line_effective_height(first_line, first_bbox)- second_height = _line_effective_height(second_line, second_bbox)- pair_height = max(first_height, second_height)- vertical_overlap = _bbox_axis_overlap_ratio(first_bbox, second_bbox, axis="y")- vertical_gap = max(first_bbox[1] - second_bbox[3], second_bbox[1] - first_bbox[3], 0.0)- if vertical_overlap < 0.2 and vertical_gap > 0.6 * pair_height:- return False- horizontal_overlap = _bbox_axis_overlap_ratio(first_bbox, second_bbox, axis="x")- horizontal_gap = max(first_bbox[0] - second_bbox[2], second_bbox[0] - first_bbox[2], 0.0)- return horizontal_overlap > 0.0 or horizontal_gap <= 1.5 * pair_height---def _is_detached_formula_sidecar(- anchor: tuple[_LineItem, BBox],- members: list[tuple[_LineItem, BBox]],- median_height: float,-) -> bool:- """仅依据 bbox 判断右侧锚点是否为与公式主体分离的窄幅 sidecar。"""-- anchor_line, anchor_bbox = anchor- body_bboxes = [- bbox- for line, bbox in members- if line.source_index != anchor_line.source_index- ]- if not body_bboxes:- return False-- body_bbox = _bbox_union_many(body_bboxes)- component_bbox = _bbox_union(body_bbox, anchor_bbox)- effective_height = max(0.1, median_height)- anchor_width = max(0.0, anchor_bbox[2] - anchor_bbox[0])- component_width = max(0.1, component_bbox[2] - component_bbox[0])- horizontal_gap = anchor_bbox[0] - body_bbox[2]- right_tolerance = max(0.5, 0.1 * effective_height)- minimum_gap = max(2.5 * effective_height, 0.08 * component_width)-- return (- anchor_bbox[0] >= body_bbox[2]- and anchor_bbox[2] >= component_bbox[2] - right_tolerance- and anchor_width <= 2.0 * effective_height- and horizontal_gap > minimum_gap- )---def _split_trailing_formula_number(text: str) -> tuple[str, str] | None:- """拆出右缘文本末尾的圆括号公式序号,并保留序号前的标点或正文。"""-- match = _FORMULA_NUMBER_SUFFIX_RE.fullmatch(str(text or "").strip())- if match is None:- return None- return match.group("prefix").rstrip(), match.group("marker").strip()---def _formula_members_to_block(- members: list[tuple[_LineItem, BBox]],- page_size: tuple[float, float],- angle: int,- *,- anchor_source_index: int,-) -> dict[str, Any] | None:- """把公式空间分量按视觉行聚类,并将非末视觉行的离散右侧 sidecar 后置。"""-- heights = [_line_effective_height(line, bbox) for line, bbox in members]- median_height = statistics.median(heights) if heights else 1.0- row_tolerance = max(1.5, 0.35 * median_height)- rows: list[list[tuple[_LineItem, BBox]]] = []- for member in sorted(members, key=lambda item: (_bbox_center_y(item[1]), item[1][0], item[0].source_index)):- if not rows:- rows.append([member])- continue- row_center = statistics.median(_bbox_center_y(bbox) for _line, bbox in rows[-1])- if abs(_bbox_center_y(member[1]) - row_center) <= row_tolerance:- rows[-1].append(member)- else:- rows.append([member])-- trailing_sidecar_content: str | None = None- # 右侧 sidecar 按视觉 y 常落在分式中部;仅在其后仍有公式行时转为逻辑末行。- for row_index, row in enumerate(rows[:-1]):- anchor_member = next(- (member for member in row if member[0].source_index == anchor_source_index),- None,- )- if anchor_member is None:- continue- formula_number_parts = _split_trailing_formula_number(anchor_member[0].text)- if formula_number_parts is not None:- prefix, marker = formula_number_parts- rows[row_index] = [- (- (replace(member[0], text=prefix), member[1])- if member[0].source_index == anchor_source_index and prefix- else member- )- for member in row- if member[0].source_index != anchor_source_index or prefix- ]- trailing_sidecar_content = marker- elif _is_detached_formula_sidecar(anchor_member, members, median_height):- rows[row_index] = [- member for member in row if member[0].source_index != anchor_source_index- ]- trailing_sidecar_content = anchor_member[0].text.strip()- break-- row_contents = [_join_formula_visual_row(row, page_size) for row in rows if row]- if trailing_sidecar_content is not None:- row_contents.append(trailing_sidecar_content)- content = _sanitize_pdf_control_text("\n".join(filter(None, row_contents)), preserve_newlines=True)- if not content.strip():- return None- return {- "type": "equation",- "bbox": _bbox_union_many([line.bbox for line, _bbox in members]),- "angle": angle,- "content": content,- }---def _join_formula_visual_row(- row: list[tuple[_LineItem, BBox]],- page_size: tuple[float, float],-) -> str:- """将一个公式视觉行按局部 x 排序,并按字宽估计几何空格。"""-- ordered = sorted(row, key=lambda item: (item[1][0], item[1][1], item[0].source_index))- if not ordered:- return ""- parts = [ordered[0][0].text.strip()]- for previous, current in zip(ordered, ordered[1:]):- previous_line, previous_bbox = previous- current_line, current_bbox = current- gap = current_bbox[0] - previous_bbox[2]- pair_height = max(- _line_effective_height(previous_line, previous_bbox),- _line_effective_height(current_line, current_bbox),- )- glyph_widths = [- width- for line in (previous_line, current_line)- if (width := _median_native_glyph_width(line, page_size)) is not None- ]- glyph_width = statistics.median(glyph_widths) if glyph_widths else max(1.0, 0.5 * pair_height)- if gap <= max(0.5, 0.2 * pair_height):- separator = ""- else:- separator = " " * max(1, min(8, int(round(gap / glyph_width))))- parts.extend([separator, current_line.text.strip()])- return "".join(parts).strip()---def _restore_dense_split_visual_rows(- lines: list[_LineItem],- page_size: tuple[float, float],- table_bboxes: list[BBox],-) -> list[_LineItem]:- """在公式认领后恢复同一栏带内被均匀大空格拆开的密集原生视觉行。"""-- if len(lines) < 3:- return list(lines)- lane_keys: dict[int, tuple[int, int]] = {}- for angle in sorted({line.angle for line in lines}):- line_geometry = [- (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))- for line in lines- if line.angle == angle- ]- if not line_geometry:- continue- median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in line_geometry)- local_page_width = page_size[1] if angle in {90, 270} else page_size[0]- lanes = _infer_text_lanes(line_geometry, local_page_width, median_height)- for lane_index, lane in enumerate(lanes):- if lane.is_span:- continue- for line, _bbox in lane.lines:- lane_keys[line.source_index] = (angle, lane_index)-- row_groups: dict[tuple[int, int], list[_LineItem]] = {}- for line in lines:- if line.visual_row_id is None:- continue- row_groups.setdefault((line.angle, line.visual_row_id), []).append(line)-- consumed_source_indices: set[int] = set()- restored_lines: list[_LineItem] = []- for members in row_groups.values():- if not _can_restore_dense_split_visual_row(- members,- page_size,- table_bboxes,- lane_keys,- ):- continue- restored_lines.append(_merge_dense_split_visual_row(members, page_size))- consumed_source_indices.update(member.source_index for member in members)-- output = [line for line in lines if line.source_index not in consumed_source_indices]- output.extend(restored_lines)- output.sort(- key=lambda line: (- line.angle,- _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[1],- _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[0],- line.source_index,- )- )- return output---def _merge_title_resolved_visual_rows(- lines: list[_LineItem],- page_size: tuple[float, float],-) -> list[_LineItem]:- """在标题判定后合并同行标题或已降级的混合字体正文 run。"""-- row_groups: dict[tuple[int, int], list[_LineItem]] = {}- for line in lines:- if line.visual_row_id is None:- continue- row_groups.setdefault((line.angle, line.visual_row_id), []).append(line)-- consumed_source_indices: set[int] = set()- merged_rows: list[_LineItem] = []- for members in row_groups.values():- if len(members) < 2 or not all(member.split_from_row for member in members):- continue- semantic_types = {member.semantic_type for member in members}- if len(semantic_types) != 1:- continue- semantic_type = next(iter(semantic_types))- font_signatures = {member.font_signature for member in members}- dense_same_font_text = _is_dense_same_font_two_run_row(- members,- page_size,- )- if semantic_type != "paragraph_title" and not (- semantic_type is None- and (len(font_signatures) > 1 or dense_same_font_text)- ):- continue- local_geometry = [- (- member,- _rotate_bbox_to_upright(member.bbox, page_size, member.angle),- )- for member in members- ]- local_geometry.sort(key=lambda item: (item[1][0], item[1][1], item[0].source_index))- if any(- not _same_baseline_geometry(- previous[1],- _line_effective_height(*previous),- current[1],- _line_effective_height(*current),- maximum_gap=3.0- * max(- _line_effective_height(*previous),- _line_effective_height(*current),- ),- )- for previous, current in zip(local_geometry, local_geometry[1:])- ):- continue- merged_rows.append(_merge_dense_split_visual_row(members, page_size))- consumed_source_indices.update(member.source_index for member in members)-- output = [- line for line in lines if line.source_index not in consumed_source_indices- ]- output.extend(merged_rows)- output.sort(- key=lambda line: (- line.angle,- _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[1],- _rotate_bbox_to_upright(line.bbox, page_size, line.angle)[0],- line.source_index,- )- )- return output---def _is_dense_same_font_two_run_row(- members: list[_LineItem],- page_size: tuple[float, float],-) -> bool:- """检查两个普通文本 run 是否为同字体且占用充分的完整视觉行。"""-- if (- len(members) != 2- or not all(member.split_from_row for member in members)- or any(member.semantic_type is not None for member in members)- or any(member.font_signature is None for member in members)- or any(member.font_coverage < 0.75 for member in members)- ):- return False- ordered = sorted(members, key=lambda member: member.run_index)- if [member.run_index for member in ordered] != [0, 1]:- return False- if ordered[0].font_signature != ordered[1].font_signature:- return False-- local_geometry = [- (- member,- _rotate_bbox_to_upright(member.bbox, page_size, member.angle),- )- for member in ordered- ]- local_geometry.sort(- key=lambda item: (item[1][0], item[1][1], item[0].source_index)- )- first, second = local_geometry- pair_height = max(- _line_effective_height(*first),- _line_effective_height(*second),- )- if not _same_baseline_geometry(- first[1],- _line_effective_height(*first),- second[1],- _line_effective_height(*second),- maximum_gap=3.0 * pair_height,- ):- return False-- union_bbox = _bbox_union_many([bbox for _member, bbox in local_geometry])- occupied_width = sum(- bbox[2] - bbox[0] for _member, bbox in local_geometry- )- return occupied_width / max(0.1, union_bbox[2] - union_bbox[0]) >= 0.85---def _can_restore_dense_split_visual_row(- members: list[_LineItem],- page_size: tuple[float, float],- table_bboxes: list[BBox],- lane_keys: dict[int, tuple[int, int]],-) -> bool:- """检查 hard-split run 是否构成同栏、同字体且占用充分的完整视觉行。"""-- if len(members) < 3 or not all(member.split_from_row for member in members):- return False- if len({member.semantic_type for member in members}) != 1:- return False- ordered = sorted(members, key=lambda member: member.run_index)- if [member.run_index for member in ordered] != list(range(len(ordered))):- return False- member_lane_keys = {lane_keys.get(member.source_index) for member in ordered}- if None in member_lane_keys or len(member_lane_keys) != 1:- return False- font_signatures = {member.font_signature for member in ordered}- if len(font_signatures) != 1:- return False- if any(- _bbox_intersects(member.bbox, table_bbox)- for member in ordered- for table_bbox in table_bboxes- ):- return False-- local_geometry = [- (- member,- _rotate_bbox_to_upright(member.bbox, page_size, member.angle),- )- for member in ordered- ]- local_geometry.sort(key=lambda item: (item[1][0], item[1][1], item[0].source_index))- heights = [_line_effective_height(member, bbox) for member, bbox in local_geometry]- median_height = statistics.median(heights)- glyph_widths = [- width- for member, _bbox in local_geometry- if (width := _median_native_glyph_width(member, page_size)) is not None- ]- median_glyph_width = statistics.median(glyph_widths) if glyph_widths else 0.0- gap_limit = max(12.0, 1.75 * median_height, 3.0 * median_glyph_width)- for previous, current in zip(local_geometry, local_geometry[1:]):- if not _same_baseline_geometry(- previous[1],- _line_effective_height(*previous),- current[1],- _line_effective_height(*current),- maximum_gap=gap_limit,- ):- return False-- union_bbox = _bbox_union_many([bbox for _member, bbox in local_geometry])- occupied_width = sum(bbox[2] - bbox[0] for _member, bbox in local_geometry)- return occupied_width / max(0.1, union_bbox[2] - union_bbox[0]) >= 0.65---def _merge_dense_split_visual_row(- members: list[_LineItem],- page_size: tuple[float, float],-) -> _LineItem:- """按局部 x 顺序恢复密集视觉行,正净空使用单空格,重叠片段直接连接。"""-- ordered_geometry = sorted(- (- (- member,- _rotate_bbox_to_upright(member.bbox, page_size, member.angle),- )- for member in members- ),- key=lambda item: (item[1][0], item[1][1], item[0].source_index),- )- content_parts = [ordered_geometry[0][0].text.strip()]- for previous, current in zip(ordered_geometry, ordered_geometry[1:]):- separator = "" if current[1][0] <= previous[1][2] else " "- content_parts.extend([separator, current[0].text.strip()])-- ordered_members = [member for member, _bbox in ordered_geometry]- merged = _LineItem(- text="".join(content_parts).strip(),- bbox=_bbox_union_many([member.bbox for member in ordered_members]),- angle=ordered_members[0].angle,- source_index=min(member.source_index for member in ordered_members),- chars=[char for member in ordered_members for char in member.chars],- visual_row_id=ordered_members[0].visual_row_id,- run_index=0,- effective_height=statistics.median(- _line_effective_height(member, bbox)- for member, bbox in ordered_geometry- ),- font_signature=ordered_members[0].font_signature,- font_coverage=min(member.font_coverage for member in ordered_members),- dominant_font_weight=statistics.median(- member.dominant_font_weight- for member in ordered_members- if member.dominant_font_weight is not None- )- if any(member.dominant_font_weight is not None for member in ordered_members)- else None,- median_glyph_width=statistics.median(- member.median_glyph_width- for member in ordered_members- if member.median_glyph_width is not None- )- if any(member.median_glyph_width is not None for member in ordered_members)- else None,- split_from_row=False,- semantic_type=ordered_members[0].semantic_type,- )- if merged.chars:- _fill_native_typography(merged, page_size)- return merged---def _build_hanging_indent_group_map(- lane: _TextLane,- table_bboxes: list[BBox],- axis_lines: list[_LocalAxisLine],-) -> dict[int, int]:- """仅按重复的左突首行和稳定续行缩进识别悬挂缩进条目。"""-- if lane.is_span or len(lane.lines) < 4:- return {}- rows = sorted(- (item for item in lane.lines if item[0].semantic_type is None),- key=lambda item: (item[1][1], item[1][0], item[0].source_index),- )- if len(rows) < 4:- return {}- median_height = statistics.median(- _line_effective_height(line, bbox) for line, bbox in rows- )- start_tolerance = max(5.0, 0.65 * median_height)- minimum_indent = max(7.0, 0.8 * median_height)- continuation_tolerance = max(4.0, 0.55 * median_height)-- def rows_are_adjacent(- previous: tuple[_LineItem, BBox],- current: tuple[_LineItem, BBox],- ) -> bool:- """检查相邻行的净空和几何障碍是否允许组成同一缩进序列。"""-- effective_gap = _effective_text_row_gap(previous, current)- if not -0.6 * median_height <= effective_gap <= 1.3 * median_height:- return False- if _connection_crosses_table(- previous[0].bbox,- current[0].bbox,- table_bboxes,- ):- return False- return not _horizontal_rule_separates_rows(- previous[1],- current[1],- lane,- axis_lines,- )-- def consume_entry(- start_index: int,- start_left: float,- expected_continuation_left: float | None,- *,- require_next_start: bool,- ) -> tuple[int, float] | None:- """消费一个左突首行及其续行,并返回下一条首行位置。"""-- continuation_index = start_index + 1- if continuation_index >= len(rows):- return None- first_continuation = rows[continuation_index]- if not rows_are_adjacent(rows[start_index], first_continuation):- return None- continuation_left = first_continuation[1][0]- if continuation_left < start_left + minimum_indent:- return None- if (- expected_continuation_left is not None- and abs(continuation_left - expected_continuation_left) > continuation_tolerance- ):- return None-- continuation_index += 1- while continuation_index < len(rows):- previous = rows[continuation_index - 1]- current = rows[continuation_index]- current_left = current[1][0]- if not rows_are_adjacent(previous, current):- break- if current_left < start_left + minimum_indent:- break- if abs(current_left - continuation_left) > continuation_tolerance:- break- continuation_index += 1-- if not require_next_start:- return continuation_index, continuation_left- if continuation_index >= len(rows):- return None- if not rows_are_adjacent(rows[continuation_index - 1], rows[continuation_index]):- return None- if abs(rows[continuation_index][1][0] - start_left) > start_tolerance:- return None- return continuation_index, continuation_left-- group_map: dict[int, int] = {}- group_index = 0- row_index = 0- while row_index < len(rows) - 3:- start_left = rows[row_index][1][0]- first_entry = consume_entry(- row_index,- start_left,- None,- require_next_start=True,- )- if first_entry is None:- row_index += 1- continue-- next_start_index, continuation_left = first_entry- start_indices = [row_index, next_start_index]- current_start_index = next_start_index- while True:- next_entry = consume_entry(- current_start_index,- start_left,- continuation_left,- require_next_start=True,- )- if next_entry is None:- break- next_start_index, _continuation_left = next_entry- start_indices.append(next_start_index)- current_start_index = next_start_index-- final_entry = consume_entry(- start_indices[-1],- start_left,- continuation_left,- require_next_start=False,- )- if final_entry is None:- row_index += 1- continue- end_index, _continuation_left = final_entry-- entry_ranges = [- (start, end)- for start, end in zip(- start_indices,- [*start_indices[1:], end_index],- strict=True,- )- ]- for start, end in entry_ranges:- for line, _bbox in rows[start:end]:- group_map[line.source_index] = group_index- group_index += 1- row_index = end_index-- return group_map---def _build_grouped_page_footnote_blocks(- lines: list[_LineItem],- source_groups: Sequence[set[int]],- page_size: tuple[float, float],-) -> tuple[list[dict[str, Any]], set[int]]:- """按分隔线组切分几何脚注条目,并返回已消费的来源编号。"""-- footnote_by_source = {- line.source_index: line- for line in lines- if line.semantic_type == "page_footnote"- }- blocks: list[dict[str, Any]] = []- consumed_source_indices: set[int] = set()- for source_group in source_groups:- group_lines = [- footnote_by_source[source_index]- for source_index in source_group- if source_index in footnote_by_source- ]- for angle in sorted({line.angle for line in group_lines}):- directional_lines = [line for line in group_lines if line.angle == angle]- tight_bboxes = _tight_page_footnote_bboxes(- directional_lines,- page_size,- )- for entry_lines in _split_page_footnote_entries(- directional_lines,- page_size,- ):- ordered_lines = sorted(- entry_lines,- key=lambda line: (- _rotate_bbox_to_upright(line.bbox, page_size, angle)[1],- _rotate_bbox_to_upright(line.bbox, page_size, angle)[0],- line.source_index,- ),- )- content = _merge_text_line_content([line.text for line in ordered_lines])- if not content:- continue- visual_row_ids = {- line.visual_row_id- for line in ordered_lines- if line.visual_row_id is not None- }- single_run_row_id = (- ordered_lines[0].visual_row_id- if len(ordered_lines) == 1- and ordered_lines[0].split_from_row- and ordered_lines[0].visual_row_id is not None- else None- )- blocks.append(- {- "type": "page_footnote",- "bbox": _bbox_union_many(- [tight_bboxes[line.source_index] for line in ordered_lines]- ),- "angle": angle,- "content": content,- "_visual_row_ids": visual_row_ids,- "_single_run_row_id": single_run_row_id,- }- )- consumed_source_indices.update(- line.source_index for line in ordered_lines- )- return blocks, consumed_source_indices---def _split_page_footnote_entries(- lines: list[_LineItem],- page_size: tuple[float, float],-) -> list[list[_LineItem]]:- """按首行或续行缩进模式,把同一分隔线下的脚注行切成条目。"""-- if not lines:- return []- angle = lines[0].angle- line_geometry = [- (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))- for line in lines- ]- line_geometry.sort(- key=lambda item: (item[1][1], item[1][0], item[0].source_index)- )- if len(line_geometry) == 1:- return [[line_geometry[0][0]]]-- effective_heights = [- _line_effective_height(line, bbox)- for line, bbox in line_geometry- ]- median_height = statistics.median(effective_heights)- glyph_widths = [- line.median_glyph_width- for line, _bbox in line_geometry- if line.median_glyph_width is not None- ]- median_glyph_width = (- statistics.median(glyph_widths)- if glyph_widths- else 0.5 * median_height- )- indent_threshold = max(1.5 * median_height, 2.0 * median_glyph_width)- base_left = min(bbox[0] for _line, bbox in line_geometry)- maximum_row_width = max(bbox[2] - bbox[0] for _line, bbox in line_geometry)- first_line_is_indented = line_geometry[0][1][0] - base_left > indent_threshold-- entries: list[list[_LineItem]] = [[line_geometry[0][0]]]- for previous, current in zip(line_geometry, line_geometry[1:]):- previous_width = previous[1][2] - previous[1][0]- previous_is_near_full = previous_width >= 0.8 * maximum_row_width- current_is_indented = current[1][0] - base_left > indent_threshold- # 满行后必然续接;其余行按首页观测到的首行/续行缩进模式决定边界。- continues_previous = previous_is_near_full or (- not current_is_indented- if first_line_is_indented- else current_is_indented- )- if continues_previous:- entries[-1].append(current[0])- else:- entries.append([current[0]])- return entries---def _tight_page_footnote_bboxes(- lines: list[_LineItem],- page_size: tuple[float, float],-) -> dict[int, BBox]:- """以有效行高和相邻行距收紧脚注框,避免异常字体框跨入相邻条目。"""-- if not lines:- return {}- angle = lines[0].angle- line_geometry = [- (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))- for line in lines- ]- line_geometry.sort(- key=lambda item: (item[1][1], item[1][0], item[0].source_index)- )- median_height = statistics.median(- _line_effective_height(line, bbox)- for line, bbox in line_geometry- )- row_pitches = [- current[1][1] - previous[1][1]- for previous, current in zip(line_geometry, line_geometry[1:])- if current[1][1] - previous[1][1] > 0.25 * median_height- ]- median_pitch = statistics.median(row_pitches) if row_pitches else None-- output: dict[int, BBox] = {}- for line, bbox in line_geometry:- tight_height = min(- bbox[3] - bbox[1],- _line_effective_height(line, bbox),- )- if median_pitch is not None:- tight_height = min(tight_height, 0.9 * median_pitch)- tight_height = max(0.1, tight_height)- center_y = _bbox_center_y(bbox)- tight_local_bbox = (- bbox[0],- center_y - 0.5 * tight_height,- bbox[2],- center_y + 0.5 * tight_height,- )- output[line.source_index] = _rotate_bbox_from_upright(- tight_local_bbox,- page_size,- angle,- )- return output---def _build_text_blocks(- lines: list[_LineItem],- table_bboxes: list[BBox],- page_size: tuple[float, float],- drawing_lines: list[_AxisLine] | None = None,- *,- page_footnote_groups: Sequence[set[int]] | None = None,-) -> list[dict[str, Any]]:- """先构建分组脚注,再按类型屏障、栏带和自然段边界聚合其余文本。"""-- blocks, grouped_footnote_indices = _build_grouped_page_footnote_blocks(- lines,- page_footnote_groups or [],- page_size,- )- lines = [- line- for line in lines- if line.source_index not in grouped_footnote_indices- ]- for angle in sorted({line.angle for line in lines}):- line_geometry = [(line, _rotate_bbox_to_upright(line.bbox, page_size, angle)) for line in lines if line.angle == angle]- if not line_geometry:- continue- line_geometry.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))- effective_heights = [_line_effective_height(line, bbox) for line, bbox in line_geometry]- median_height = statistics.median(effective_heights) if effective_heights else 1.0- local_page_width = page_size[1] if angle in {90, 270} else page_size[0]- lanes = _infer_text_lanes(line_geometry, local_page_width, median_height)- local_axis_lines = _transform_axis_lines(drawing_lines or [], page_size, angle)-- for lane in lanes:- lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))- if not lane.lines:- continue- regular_gap, gap_mad = _estimate_lane_gap(lane)- hanging_indent_groups = _build_hanging_indent_group_map(- lane,- table_bboxes,- local_axis_lines,- )- component: list[tuple[_LineItem, BBox]] = [lane.lines[0]]- components: list[list[tuple[_LineItem, BBox]]] = []- for previous, current in zip(lane.lines, lane.lines[1:]):- previous_type = previous[0].semantic_type- current_type = current[0].semantic_type- if previous_type != current_type:- should_connect = False- elif previous_type is not None:- should_connect = _should_connect_semantic_rows(- previous,- current,- lane,- regular_gap,- table_bboxes,- local_axis_lines,- )- else:- previous_group = hanging_indent_groups.get(previous[0].source_index)- current_group = hanging_indent_groups.get(current[0].source_index)- if previous_group is not None or current_group is not None:- should_connect = previous_group is not None and previous_group == current_group- else:- should_connect = _should_connect_text_rows(- previous,- current,- lane,- regular_gap,- gap_mad,- table_bboxes,- local_axis_lines,- )- if should_connect:- component.append(current)- else:- components.append(component)- component = [current]- components.append(component)-- for component_geometry in components:- component_lines = [item[0] for item in component_geometry]- content = _merge_text_line_content([line.text for line in component_lines])- if not content:- continue- visual_row_ids = {- line.visual_row_id for line in component_lines if line.visual_row_id is not None- }- single_run_row_id = (- component_lines[0].visual_row_id- if len(component_lines) == 1- and component_lines[0].split_from_row- and component_lines[0].visual_row_id is not None- else None- )- blocks.append(- {- "type": component_lines[0].semantic_type or "text",- "bbox": _bbox_union_many([line.bbox for line in component_lines]),- "angle": angle,- "content": content,- "_visual_row_ids": visual_row_ids,- "_single_run_row_id": single_run_row_id,- }- )- return blocks---def _should_connect_semantic_rows(- previous: tuple[_LineItem, BBox],- current: tuple[_LineItem, BBox],- lane: _TextLane,- regular_gap: float,- table_bboxes: list[BBox],- axis_lines: list[_LocalAxisLine],-) -> bool:- """只用几何、字体和障碍连接同类型语义行,避免标题内容影响聚合。"""-- previous_line, previous_bbox = previous- current_line, current_bbox = current- if previous_line.semantic_type != current_line.semantic_type:- return False- if _connection_crosses_table(previous_line.bbox, current_line.bbox, table_bboxes):- return False- if _horizontal_rule_separates_rows(previous_bbox, current_bbox, lane, axis_lines):- return False- previous_height = _line_effective_height(previous_line, previous_bbox)- current_height = _line_effective_height(current_line, current_bbox)- pair_height = max(previous_height, current_height)- if max(previous_height, current_height) / min(previous_height, current_height) > 1.35:- return False- vertical_gap = _effective_text_row_gap(previous, current)- if not -0.25 * pair_height <= vertical_gap <= max(1.25 * pair_height, regular_gap + 0.75 * pair_height):- return False- if (- previous_line.semantic_type == "paragraph_title"- and vertical_gap > 0.65 * pair_height- ):- return False- if (- previous_line.font_signature is not None- and current_line.font_signature is not None- and previous_line.font_coverage >= 0.75- and current_line.font_coverage >= 0.75- and previous_line.font_signature != current_line.font_signature- ):- return False- lane_width = max(0.1, lane.right - lane.left)- centered_pair = (- abs(_bbox_center_x(previous_bbox) - _bbox_center_x(current_bbox)) <= 0.15 * lane_width- )- aligned_pair = abs(previous_bbox[0] - current_bbox[0]) <= 0.75 * pair_height- overlapping_pair = _bbox_axis_overlap_ratio(previous_bbox, current_bbox, axis="x") >= 0.35- return centered_pair or aligned_pair or overlapping_pair---def _line_effective_height(line: _LineItem, local_bbox: BBox) -> float:- """返回字符统计得到的有效行高,缺失时回退到局部 bbox 高度。"""-- return max(0.1, line.effective_height or (local_bbox[3] - local_bbox[1]))---def _effective_text_row_gap(- previous: tuple[_LineItem, BBox],- current: tuple[_LineItem, BBox],-) -> float:- """按前一行顶边与有效行高计算净空,避免高数学字形拉长 bbox 底边。"""-- previous_line, previous_bbox = previous- _current_line, current_bbox = current- return current_bbox[1] - (previous_bbox[1] + _line_effective_height(previous_line, previous_bbox))---def _infer_text_lanes(- line_geometry: list[tuple[_LineItem, BBox]],- local_page_width: float,- median_height: float,-) -> list[_TextLane]:- """从重复左右边缘推断稳定栏带,并把跨栏行放入独立 span lane。"""-- anchor_tolerance = max(3.0, 0.75 * median_height)- regular_lines = [- item- for item in line_geometry- if item[1][2] - item[1][0] >= max(4.0 * _line_effective_height(*item), 0.15 * local_page_width)- ]- left_clusters: list[list[tuple[_LineItem, BBox]]] = []- for item in sorted(regular_lines, key=lambda value: value[1][0]):- if not left_clusters:- left_clusters.append([item])- continue- cluster_left = statistics.median(member[1][0] for member in left_clusters[-1])- if abs(item[1][0] - cluster_left) <= anchor_tolerance:- left_clusters[-1].append(item)- else:- left_clusters.append([item])-- supported_intervals = [- (- statistics.median(item[1][0] for item in cluster),- statistics.median(item[1][2] for item in cluster),- len(cluster),- )- for cluster in left_clusters- if len(cluster) >= 3- ]- supported_intervals.sort(key=lambda interval: interval[0])- filtered_intervals: list[tuple[float, float, int]] = []- for interval in supported_intervals:- if not filtered_intervals:- filtered_intervals.append(interval)- continue- previous = filtered_intervals[-1]- minimum_gutter = max(6.0, 0.75 * median_height)- if interval[0] - previous[1] >= minimum_gutter:- filtered_intervals.append(interval)- elif interval[2] > previous[2]:- filtered_intervals[-1] = interval-- if not filtered_intervals:- source = regular_lines or line_geometry- filtered_intervals = [- (- min(item[1][0] for item in source),- max(item[1][2] for item in source),- len(source),- )- ]-- lanes = [_TextLane(left=left, right=right) for left, right, _support in filtered_intervals]- span_lines: list[tuple[_LineItem, BBox]] = []- for item in line_geometry:- bbox = item[1]- line_width = max(0.1, bbox[2] - bbox[0])- scored_lanes = [- (- max(0.0, min(bbox[2], lane.right) - max(bbox[0], lane.left)) / line_width,- lane,- )- for lane in lanes- ]- coverage_scores = sorted(- (coverage for coverage, _lane in scored_lanes),- reverse=True,- )- # 同时覆盖两个稳定正文栏的短尾行仍属于跨栏内容,不能按中心点落回单栏。- if len(coverage_scores) > 1 and coverage_scores[1] >= 0.2:- span_lines.append(item)- continue- best_coverage, best_lane = max(scored_lanes, key=lambda value: value[0])- if len(lanes) == 1 or (- best_coverage >= 0.5- and best_lane.left - anchor_tolerance- <= _bbox_center_x(bbox)- <= best_lane.right + anchor_tolerance- ):- best_lane.lines.append(item)- else:- span_lines.append(item)-- if span_lines:- lanes.append(- _TextLane(- left=min(item[1][0] for item in span_lines),- right=max(item[1][2] for item in span_lines),- lines=span_lines,- is_span=True,- )- )- _reattach_span_lane_continuations(lanes, median_height)- return lanes---def _reattach_span_lane_continuations(- lanes: list[_TextLane],- median_height: float,-) -> None:- """把紧随稳定跨栏多行之后的单栏宽短尾行迁回对应 span lane。"""-- regular_lanes = [lane for lane in lanes if not lane.is_span]- span_lanes = [lane for lane in lanes if lane.is_span]- if len(regular_lanes) < 2 or not span_lanes:- return-- for span_lane in span_lanes:- span_lane.lines.sort(- key=lambda item: (item[1][1], item[1][0], item[0].source_index)- )- if len(span_lane.lines) < 2:- continue- previous, last = span_lane.lines[-2:]- previous_height = _line_effective_height(*previous)- last_height = _line_effective_height(*last)- if (- previous[0].semantic_type != last[0].semantic_type- or abs(previous[1][0] - last[1][0]) > 0.75 * median_height- or max(previous_height, last_height) / min(previous_height, last_height) > 1.35- or not _title_fonts_compatible(previous[0], last[0])- or not -0.25 * median_height- <= _effective_text_row_gap(previous, last)- <= 0.75 * median_height- ):- continue-- while True:- candidates: list[- tuple[- float,- float,- _TextLane,- tuple[_LineItem, BBox],- ]- ] = []- for regular_lane in regular_lanes:- for candidate in regular_lane.lines:- candidate_line, candidate_bbox = candidate- if (- candidate_line.semantic_type != last[0].semantic_type- or candidate_bbox[1] <= last[1][1]- ):- continue- gap = _effective_text_row_gap(last, candidate)- candidate_height = _line_effective_height(*candidate)- if (- not -0.25 * median_height <= gap <= 0.75 * median_height- or abs(candidate_bbox[0] - last[1][0]) > 0.75 * median_height- or max(last_height, candidate_height)- / min(last_height, candidate_height)- > 1.35- or not _title_fonts_compatible(last[0], candidate_line)- ):- continue- has_parallel_peer = any(- other_line is not candidate_line- and _bbox_axis_overlap_ratio(- candidate_bbox,- other_bbox,- axis="y",- )- >= 0.5- for lane in regular_lanes- for other_line, other_bbox in lane.lines- )- if has_parallel_peer:- continue- candidates.append(- (- max(0.0, gap),- candidate_bbox[1],- regular_lane,- candidate,- )- )- if not candidates:- break- _gap, _top, regular_lane, candidate = min(- candidates,- key=lambda item: (item[0], item[1]),- )- regular_lane.lines.remove(candidate)- span_lane.lines.append(candidate)- span_lane.left = min(span_lane.left, candidate[1][0])- span_lane.right = max(span_lane.right, candidate[1][2])- span_lane.lines.sort(- key=lambda item: (item[1][1], item[1][0], item[0].source_index)- )- last = candidate- last_height = _line_effective_height(*last)---def _estimate_lane_gap(lane: _TextLane) -> tuple[float, float]:- """从栏带内兼容相邻行的较小间隙簇估计常规净空和 MAD。"""-- lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))- heights = [_line_effective_height(line, bbox) for line, bbox in lane.lines]- median_height = statistics.median(heights) if heights else 1.0- gaps: list[float] = []- for previous, current in zip(lane.lines, lane.lines[1:]):- previous_line, previous_bbox = previous- current_line, current_bbox = current- if previous_line.visual_row_id == current_line.visual_row_id and (- previous_line.split_from_row or current_line.split_from_row- ):- continue- previous_height = _line_effective_height(previous_line, previous_bbox)- current_height = _line_effective_height(current_line, current_bbox)- if max(previous_height, current_height) / min(previous_height, current_height) > 1.35:- continue- pair_height = max(previous_height, current_height)- gap = _effective_text_row_gap(previous, current)- if gap < -0.25 * pair_height or gap > 2.0 * pair_height:- continue- if _bbox_axis_overlap_ratio(previous_bbox, current_bbox, axis="x") < 0.5 and abs(- previous_bbox[0] - current_bbox[0]- ) > 1.5 * median_height:- continue- # PDF 字符框常在相邻基线间产生极小重叠;按零净空计入常规行距统计。- gaps.append(max(0.0, gap))-- if not gaps:- return 0.35 * median_height, 0.0- sorted_gaps = sorted(gaps)- lower_count = max(1, math.ceil(len(sorted_gaps) * 0.6))- lower_gaps = sorted_gaps[:lower_count]- regular_gap = statistics.median(lower_gaps)- gap_mad = statistics.median(abs(gap - regular_gap) for gap in lower_gaps)- return regular_gap, gap_mad---def _should_connect_text_rows(- previous: tuple[_LineItem, BBox],- current: tuple[_LineItem, BBox],- lane: _TextLane,- regular_gap: float,- gap_mad: float,- table_bboxes: list[BBox],- axis_lines: list[_LocalAxisLine],-) -> bool:- """综合局部间距、首行缩进、字体和障碍判断两个相邻视觉行是否同段。"""-- previous_line, previous_bbox = previous- current_line, current_bbox = current- previous_height = _line_effective_height(previous_line, previous_bbox)- current_height = _line_effective_height(current_line, current_bbox)- pair_height = max(previous_height, current_height)- lane_width = max(0.1, lane.right - lane.left)- previous_width = previous_bbox[2] - previous_bbox[0]- current_width = current_bbox[2] - current_bbox[0]- vertical_gap = _effective_text_row_gap(previous, current)- if previous_line.visual_row_id == current_line.visual_row_id and (- previous_line.split_from_row or current_line.split_from_row- ):- return False- if (- current_height < 0.88 * previous_height- and vertical_gap > regular_gap + 0.25 * previous_height- ):- return False- height_ratio = max(previous_height, current_height) / min(previous_height, current_height)- if height_ratio > 1.35:- both_fill_lane = previous_width >= 0.8 * lane_width and current_width >= 0.8 * lane_width- aligned_left_edges = abs(previous_bbox[0] - current_bbox[0]) <= 0.5 * pair_height- font_style_changed = (- previous_line.font_signature is not None- and current_line.font_signature is not None- and previous_line.font_signature[1] != current_line.font_signature[1]- )- # 满栏混合字体可跨字号续接,但显式正体/斜体等样式边界仍保持原分段语义。- if not both_fill_lane or not aligned_left_edges or font_style_changed:- return False-- if vertical_gap < -0.25 * pair_height:- return False- if _bbox_axis_overlap_ratio(previous_bbox, current_bbox, axis="x") < 0.5 and abs(- previous_bbox[0] - current_bbox[0]- ) > 1.5 * pair_height:- return False- if _connection_crosses_table(previous_line.bbox, current_line.bbox, table_bboxes):- return False- if _horizontal_rule_separates_rows(previous_bbox, current_bbox, lane, axis_lines):- return False-- gap_limit = max(- regular_gap + max(0.5 * pair_height, 3.0 * gap_mad),- 1.1 * pair_height,- )- # 排版断词可以跳过缩进、字体和短行规则,但仍须限制在邻近物理行内,- # 避免页内远距离的 “cross-” 与后续标题被误拼为同一段。- if is_hyphen_at_line_end(previous_line.text):- return vertical_gap <= max(gap_limit, 1.8 * pair_height)- if vertical_gap > gap_limit:- return False-- terminal_previous = bool(re.search(r"[.!?。!?::;;][\]\)})】》”’'\"]*$", previous_line.text.rstrip()))- if terminal_previous and vertical_gap > regular_gap + 0.5 * pair_height:- return False-- # 局部版心可能比整栏推断边界更靠左,缩进需同时参考上一物理行。- local_lane_left = min(lane.left, previous_bbox[0])- local_lane_width = max(0.1, lane.right - local_lane_left)- next_indent = current_bbox[0] - local_lane_left- previous_fill = max(0.0, previous_bbox[2] - local_lane_left) / local_lane_width- if next_indent >= max(5.0, 0.65 * pair_height) and (previous_fill <= 0.8 or terminal_previous):- return False-- abnormal_gap = vertical_gap > regular_gap + 0.25 * pair_height- if (- previous_line.font_signature is not None- and current_line.font_signature is not None- and previous_line.font_coverage >= 0.75- and current_line.font_coverage >= 0.75- and previous_line.font_signature != current_line.font_signature- and (abnormal_gap or min(previous_width, current_width) <= 0.7 * lane_width)- ):- return False- if abnormal_gap and min(previous_width, current_width) <= 0.65 * lane_width:- return False- return True---def _horizontal_rule_separates_rows(- previous_bbox: BBox,- current_bbox: BBox,- lane: _TextLane,- axis_lines: list[_LocalAxisLine],-) -> bool:- """检查两个相邻文本行之间是否存在覆盖当前栏带的长水平规则线。"""-- if current_bbox[1] <= previous_bbox[3]:- return False- lane_width = max(0.1, lane.right - lane.left)- for axis_line in axis_lines:- if axis_line.orientation != "horizontal":- continue- line_y = _bbox_center_y(axis_line.bbox)- if not previous_bbox[3] <= line_y <= current_bbox[1]:- continue- overlap = max(0.0, min(axis_line.bbox[2], lane.right) - max(axis_line.bbox[0], lane.left))- if overlap / lane_width >= 0.6:- return True- return False---def _merge_text_line_content(line_texts: Sequence[str]) -> str:- """按 Hybrid 语言与行末连字规则折叠普通文本行。"""-- normalized_lines = [_normalize_native_run_text(str(text or "")) for text in line_texts]- normalized_lines = [text for text in normalized_lines if text]- if not normalized_lines:- return ""- try:- block_language = detect_lang("".join(normalized_lines))- except Exception:- block_language = ""- content_parts = [normalized_lines[0]]- for current_line in normalized_lines[1:]:- processed_previous, separator = resolve_text_line_boundary(- content_parts[-1],- block_language=block_language,- next_starts_with_lowercase=current_line[0].islower(),- )- content_parts[-1] = processed_previous- content_parts.extend([separator, current_line])- return "".join(content_parts).strip()---def _connection_crosses_table(- first_bbox: BBox,- second_bbox: BBox,- table_bboxes: list[BBox],-) -> bool:- """检查两行中心连接区域是否穿过已确认表格。"""-- first_center = (_bbox_center_x(first_bbox), _bbox_center_y(first_bbox))- second_center = (_bbox_center_x(second_bbox), _bbox_center_y(second_bbox))- connector = _coerce_bbox(- (- min(first_center[0], second_center[0]) - 0.1,- min(first_center[1], second_center[1]) - 0.1,- max(first_center[0], second_center[0]) + 0.1,- max(first_center[1], second_center[1]) + 0.1,- )- )- return connector is not None and any(_bbox_intersects(connector, table_bbox) for table_bbox in table_bboxes)---def _sort_blocks_with_visual_row_groups(- blocks: list[dict[str, Any]],- page_size: tuple[float, float],-) -> list[dict[str, Any]]:- """把同一粗行拆出的单行 block 包装成虚拟项排序,再按局部 x 顺序展开。"""-- grouped_indices: dict[int, list[int]] = {}- for index, block in enumerate(blocks):- row_id = block.get("_single_run_row_id")- if isinstance(row_id, int):- grouped_indices.setdefault(row_id, []).append(index)-- virtual_groups: dict[int, dict[str, Any]] = {}- consumed_indices: set[int] = set()- for row_id, indices in grouped_indices.items():- if len(indices) < 2:- continue- members = [blocks[index] for index in indices]- virtual_group = {- "type": "_xycut_visual_row_group",- "bbox": _bbox_union_many([member["bbox"] for member in members]),- "angle": members[0].get("angle", 0),- "content": "",- "_members": members,- }- virtual_groups[row_id] = virtual_group- consumed_indices.update(indices)-- sortable_blocks = [block for index, block in enumerate(blocks) if index not in consumed_indices]- sortable_blocks.extend(virtual_groups.values())- sorted_payloads = sort_entries(sortable_blocks)- output: list[dict[str, Any]] = []- for payload in sorted_payloads:- members = payload.get("_members")- if not isinstance(members, list):- output.append(payload)- continue- angle = int(payload.get("angle", 0) or 0) % 360- members.sort(- key=lambda member: (- _rotate_bbox_to_upright(member["bbox"], page_size, angle)[0],- _rotate_bbox_to_upright(member["bbox"], page_size, angle)[1],- )- )- output.extend(members)- return output---def _normalize_output_block(- block: dict[str, Any],- page_size: tuple[float, float],-) -> dict[str, Any] | None:- """在排序完成后将绝对 bbox 裁剪并归一化为 model_list 坐标。"""-- page_width, page_height = page_size- bbox = _clip_bbox(_coerce_bbox(block.get("bbox")), page_size)- if bbox is None or page_width <= 0 or page_height <= 0:- return None- content = block.get("content")- if not isinstance(content, str):- return None- content = _sanitize_pdf_control_text(content, preserve_newlines=True)- block_type = block.get("type")- normalized_type = block_type if block_type in _OUTPUT_BLOCK_TYPES else "text"- if normalized_type != "image" and not content.strip():- return None- normalized_bbox = _normalize_bbox_to_thousandths(bbox, page_size)- return {- "type": normalized_type,- "bbox": normalized_bbox,- "angle": 0 if normalized_type == "image" else int(block.get("angle", 0) or 0) % 360,- "content": content,- }---def _normalize_bbox_to_thousandths(- bbox: BBox,- page_size: tuple[float, float],-) -> list[float]:- """将绝对 bbox 转成千分位刻度,并保证舍入后的宽高至少各占一个刻度。"""-- page_width, page_height = page_size- ticks = [- max(0, min(1000, int(round(bbox[0] / page_width * 1000)))),- max(0, min(1000, int(round(bbox[1] / page_height * 1000)))),- max(0, min(1000, int(round(bbox[2] / page_width * 1000)))),- max(0, min(1000, int(round(bbox[3] / page_height * 1000)))),- ]- if ticks[2] <= ticks[0]:- if ticks[0] < 1000:- ticks[2] = ticks[0] + 1- else:- ticks[0] = max(0, ticks[2] - 1)- if ticks[3] <= ticks[1]:- if ticks[1] < 1000:- ticks[3] = ticks[1] + 1- else:- ticks[1] = max(0, ticks[3] - 1)- return [tick / 1000 for tick in ticks]---def _rotate_bbox_to_upright(- bbox: BBox,- page_size: tuple[float, float],- angle: int,-) -> BBox:- """将页面 bbox 转到当前文本方向的正向局部坐标。"""-- page_width, page_height = page_size- x0, y0, x1, y1 = bbox- if angle == 270:- return (page_height - y1, x0, page_height - y0, x1)- if angle == 90:- return (y0, page_width - x1, y1, page_width - x0)- if angle == 180:- return (page_width - x1, page_height - y1, page_width - x0, page_height - y0)- return bbox---def _rotate_bbox_from_upright(- bbox: BBox,- page_size: tuple[float, float],- angle: int,-) -> BBox:- """将正向局部 bbox 逆变换回 PDF 页面坐标。"""-- page_width, page_height = page_size- x0, y0, x1, y1 = bbox- if angle == 270:- return (y0, page_height - x1, y1, page_height - x0)- if angle == 90:- return (page_width - y1, x0, page_width - y0, x1)- if angle == 180:- return (page_width - x1, page_height - y1, page_width - x0, page_height - y0)- return bbox---def _median_fragment_height(fragments: list[_Fragment]) -> float:- """返回正向文本片段高度的中位数。"""-- heights = [- fragment.local_bbox[3] - fragment.local_bbox[1]- for fragment in fragments- if fragment.local_bbox[3] > fragment.local_bbox[1]- ]- return max(0.1, float(statistics.median(heights)) if heights else 1.0)---def _coerce_bbox(value: Any) -> BBox | None:- """将任意四元 bbox 规范成非退化浮点坐标。"""-- try:- x0, y0, x1, y1 = [float(item) for item in value]- except (TypeError, ValueError):- return None- left, right = sorted((x0, x1))- top, bottom = sorted((y0, y1))- if not all(math.isfinite(item) for item in (left, top, right, bottom)):- return None- if right <= left or bottom <= top:- return None- return (left, top, right, bottom)---def _clip_bbox(- bbox: BBox | None,- page_size: tuple[float, float],-) -> BBox | None:- """将 bbox 裁剪到页面范围,退化框返回 None。"""-- if bbox is None:- return None- page_width, page_height = page_size- return _coerce_bbox(- (- max(0.0, min(page_width, bbox[0])),- max(0.0, min(page_height, bbox[1])),- max(0.0, min(page_width, bbox[2])),- max(0.0, min(page_height, bbox[3])),- )- )---def _bbox_union(first: BBox, second: BBox) -> BBox:- """返回两个 bbox 的外接并集框。"""-- return (- min(first[0], second[0]),- min(first[1], second[1]),- max(first[2], second[2]),- max(first[3], second[3]),- )---def _bbox_union_many(bboxes: Sequence[BBox]) -> BBox:- """返回非空 bbox 序列的外接并集框。"""-- if not bboxes:- raise ValueError("bbox sequence must not be empty")- result = bboxes[0]- for bbox in bboxes[1:]:- result = _bbox_union(result, bbox)- return result---def _expand_bbox(bbox: BBox, margin: float) -> BBox:- """向四周扩展 bbox,仅供几何容差判定使用。"""-- return (- bbox[0] - margin,- bbox[1] - margin,- bbox[2] + margin,- bbox[3] + margin,- )---def _bbox_center_x(bbox: BBox) -> float:- """返回 bbox 的水平中心。"""-- return (bbox[0] + bbox[2]) / 2.0---def _bbox_center_y(bbox: BBox) -> float:- """返回 bbox 的垂直中心。"""-- return (bbox[1] + bbox[3]) / 2.0---def _bbox_intersects(first: BBox, second: BBox) -> bool:- """检查两个 bbox 是否存在正面积交叠。"""-- return min(first[2], second[2]) > max(first[0], second[0]) and min(first[3], second[3]) > max(first[1], second[1])---def _bbox_distance(first: BBox, second: BBox) -> float:- """返回两个 bbox 的欧氏净空距离,交叠或相接时为零。"""-- horizontal_gap = max(first[0] - second[2], second[0] - first[2], 0.0)- vertical_gap = max(first[1] - second[3], second[1] - first[3], 0.0)- return math.hypot(horizontal_gap, vertical_gap)-+from __future__ import annotations-def _bbox_overlap_in_smaller(first: BBox, second: BBox) -> float:- """计算交集面积占较小 bbox 面积的比例。"""+from typing import Any, Literal- width = max(0.0, min(first[2], second[2]) - max(first[0], second[0]))- height = max(0.0, min(first[3], second[3]) - max(first[1], second[1]))- intersection = width * height- first_area = (first[2] - first[0]) * (first[3] - first[1])- second_area = (second[2] - second[0]) * (second[3] - second[1])- smaller_area = min(first_area, second_area)- return intersection / smaller_area if smaller_area > 0 else 0.0+from loguru import logger+from mineru.cli_old.common import read_fn+from mineru.utils.pdf_document import PDFDocument-def _bbox_axis_overlap_ratio(- first: BBox,- second: BBox,- *,- axis: Literal["x", "y"],-) -> float:- """计算指定轴上的交叠长度占较短轴长的比例。"""+__all__ = ["doc_analyze", "extract_pages_text"]- if axis == "x":- first_start, first_end = first[0], first[2]- second_start, second_end = second[0], second[2]- else:- first_start, first_end = first[1], first[3]- second_start, second_end = second[1], second[3]- overlap = max(0.0, min(first_end, second_end) - max(first_start, second_start))- shorter = min(first_end - first_start, second_end - second_start)- return overlap / shorter if shorter > 0 else 0.0+def extract_pages_text(+ filepath: str,+ start_page: int = 0,+ end_page: int | None = None,+) -> list[str]:+ """逐页提取 PDF 原生纯文本,并保留空白页。"""-def _point_in_bbox(point: tuple[float, float], bbox: BBox) -> bool:- """检查点是否位于 bbox 内部或边界上。"""+ pages: list[str] = []+ with PDFDocument(filepath) as pdf_doc:+ page_count = pdf_doc.page_count+ end = page_count if end_page is None else min(end_page, page_count)- return bbox[0] <= point[0] <= bbox[2] and bbox[1] <= point[1] <= bbox[3]+ # 保留旧 Flash parser 依赖的逐页纯文本接口。+ for page_idx in range(start_page, end):+ pages.append(pdf_doc.get_page_text(page_idx))+ return pagesdef doc_analyze(@@ -5431,6 +59,11 @@ def doc_analyze(resolved_mode = parse_modeif resolved_mode == "txt":+ # 延迟加载原生分析流水线,使逐页纯文本接口保持轻量。+ from mineru.backend.flash.native_pdf.pipeline import (+ _analyze_native_document,+ )+return _analyze_native_document(pdf_doc)# OCR 路径延迟加载 Hybrid,保证原生 Flash 不引入本地视觉模型运行时。@@ -5446,9 +79,10 @@ def doc_analyze(if __name__ == '__main__':- # pdf_path = "/Users/myhloli/pdf/截断合并/demo1-3.pdf"- # pdf_path = "/Users/myhloli/pdf/png/seal4.png" # shubiao.png- pdf_path = "/Users/myhloli/pdf/demo1.pdf"- pdf_bytes = read_fn(pdf_path)- model_list = doc_analyze(pdf_bytes, parse_mode="auto")- logger.info(f"model_list: {model_list}")+ if __name__ == "__main__":+ # pdf_path = "/Users/myhloli/pdf/截断合并/demo1-3.pdf"+ # pdf_path = "/Users/myhloli/pdf/png/seal4.png" # shubiao.png+ pdf_path = "/Users/myhloli/pdf/demo1.pdf"+ pdf_bytes = read_fn(pdf_path)+ model_list = doc_analyze(pdf_bytes, parse_mode="auto")+ logger.info(f"model_list: {model_list}")diff --git a/tests/unittest/_flash_pdf_test_utils.py b/tests/unittest/_flash_pdf_test_utils.pynew file mode 100644index 00000000..4a7514cc--- /dev/null+++ b/tests/unittest/_flash_pdf_test_utils.py@@ -0,0 +1,59 @@+from __future__ import annotations++++from mineru.backend.flash.native_pdf import (+ models,+)+++def _text_line(+ text: str,+ bbox: tuple[float, float, float, float],+ source_index: int,+ *,+ angle: int = 0,+ visual_row_id: int | None = None,+ run_index: int = 0,+ split_from_row: bool = False,+ effective_height: float | None = None,+ font_signature: tuple[str, int] | None = None,+ font_coverage: float = 0.0,+ dominant_font_weight: float | None = None,+ median_glyph_width: float | None = None,+ semantic_type: str | None = None,+) -> models._LineItem:+ """构造栏带、排版恢复与图形标签测试使用的原生文本行。"""++ return models._LineItem(+ text=text,+ bbox=bbox,+ angle=angle,+ source_index=source_index,+ visual_row_id=visual_row_id,+ run_index=run_index,+ effective_height=effective_height or (bbox[3] - bbox[1]),+ font_signature=font_signature,+ font_coverage=font_coverage,+ dominant_font_weight=dominant_font_weight,+ median_glyph_width=median_glyph_width,+ split_from_row=split_from_row,+ semantic_type=semantic_type,+ )+++def _prepared_text_page(+ *lines: models._LineItem,+ page_size: tuple[float, float] = (100.0, 100.0),+) -> models._PreparedPage:+ """构造跨页边缘类型测试使用的无容器轻量页面。"""++ return models._PreparedPage(+ page_size=page_size,+ remaining_lines=list(lines),+ table_bboxes=[],+ drawing_lines=[],+ fixed_blocks=[],+ )++diff --git a/tests/unittest/test_flash_pdf_auxiliary_text.py b/tests/unittest/test_flash_pdf_auxiliary_text.pynew file mode 100644index 00000000..e6b35649--- /dev/null+++ b/tests/unittest/test_flash_pdf_auxiliary_text.py@@ -0,0 +1,479 @@+from __future__ import annotations++import inspect++import pytest++from mineru.backend.flash.native_pdf import (+ auxiliary_text,+ models,+ pipeline,+ text_blocks,+)+++from _flash_pdf_test_utils import (+ _prepared_text_page,+ _text_line,+)+++def test_page_footnote_uses_separator_and_stops_before_distant_footer_text() -> None:+ """验证单栏页脚注由页底横线触发,并在较大行间隙前停止扩展。"""++ lines = [+ _text_line("body one", (100.0, 100.0, 900.0, 110.0), 0),+ _text_line("body two", (100.0, 130.0, 900.0, 140.0), 1),+ _text_line("body three", (100.0, 160.0, 900.0, 170.0), 2),+ _text_line("note one", (100.0, 770.0, 500.0, 780.0), 3),+ _text_line("note two", (100.0, 788.0, 500.0, 798.0), 4),+ _text_line("note three", (100.0, 806.0, 500.0, 816.0), 5),+ _text_line("footer text", (100.0, 850.0, 600.0, 860.0), 6),+ ]+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))+ page.drawing_lines = [+ models._AxisLine(+ bbox=(100.0, 750.0, 260.0, 752.0),+ width=1.0,+ orientation="horizontal",+ ),+ models._AxisLine(+ bbox=(100.0, 750.5, 260.0, 752.5),+ width=1.0,+ orientation="horizontal",+ ),+ ]++ auxiliary_text._classify_page_auxiliary_text(page)++ assert [line.semantic_type for line in lines] == [+ None,+ None,+ None,+ "page_footnote",+ "page_footnote",+ "page_footnote",+ None,+ ]+ assert page.page_footnote_groups == [{3, 4, 5}]+++def test_page_footnote_supports_independent_column_rules() -> None:+ """验证左右栏各自的短横线只认领本栏连续页脚注。"""++ lines = [+ *[+ _text_line(f"left body {index}", (80.0, 100.0 + 30.0 * index, 460.0, 110.0 + 30.0 * index), index)+ for index in range(3)+ ],+ *[+ _text_line(+ f"right body {index}",+ (540.0, 100.0 + 30.0 * index, 920.0, 110.0 + 30.0 * index),+ index + 3,+ )+ for index in range(3)+ ],+ _text_line("left note one", (80.0, 820.0, 400.0, 830.0), 6),+ _text_line("left note two", (80.0, 838.0, 400.0, 848.0), 7),+ _text_line("right note one", (540.0, 820.0, 860.0, 830.0), 8),+ _text_line("right note two", (540.0, 838.0, 860.0, 848.0), 9),+ ]+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))+ page.drawing_lines = [+ models._AxisLine((80.0, 800.0, 220.0, 802.0), 1.0, "horizontal"),+ models._AxisLine((540.0, 800.0, 680.0, 802.0), 1.0, "horizontal"),+ ]++ auxiliary_text._classify_page_auxiliary_text(page)++ assert all(line.semantic_type is None for line in lines[:6])+ assert all(line.semantic_type == "page_footnote" for line in lines[6:])+ assert page.page_footnote_groups == [{6, 7}, {8, 9}]+++def test_page_footnote_unions_aligned_regular_and_span_lanes_only() -> None:+ """验证同左缘 regular/span 栏可联合认领,但不会吞掉右侧正文栏。"""++ lines = [+ *[+ _text_line(f"left body {index}", (100.0, 100.0 + 30.0 * index, 480.0, 110.0 + 30.0 * index), index)+ for index in range(3)+ ],+ *[+ _text_line(+ f"right body {index}",+ (520.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index),+ index + 3,+ )+ for index in range(3)+ ],+ _text_line("span note one", (100.0, 810.0, 900.0, 820.0), 6),+ _text_line("span note two", (100.0, 830.0, 900.0, 840.0), 7),+ _text_line("span note three", (100.0, 850.0, 900.0, 860.0), 8),+ _text_line("left note one", (100.0, 812.0, 480.0, 822.0), 9),+ _text_line("left note two", (100.0, 832.0, 480.0, 842.0), 10),+ _text_line("right body below rule", (520.0, 812.0, 900.0, 822.0), 11),+ ]+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))+ page.drawing_lines = [+ models._AxisLine((100.0, 800.0, 305.0, 802.0), 1.0, "horizontal")+ ]++ auxiliary_text._classify_page_auxiliary_text(page)++ assert {line.source_index for line in lines if line.semantic_type == "page_footnote"} == {+ 6,+ 7,+ 8,+ 9,+ 10,+ }+ assert page.page_footnote_groups == [{6, 7, 8, 9, 10}]+ assert lines[11].semantic_type is None+++def test_page_footnote_entries_split_first_line_indent_without_text() -> None:+ """验证首行缩进模式把两个脚注起始行拆开,并吸收左对齐续行。"""++ lines = [+ _text_line("first", (87.0, 732.0, 245.0, 742.0), 0, effective_height=8.0, median_glyph_width=4.5),+ _text_line("second", (83.0, 743.0, 293.0, 753.0), 1, effective_height=8.0, median_glyph_width=4.5),+ _text_line("continuation", (70.0, 755.0, 276.0, 763.0), 2, effective_height=7.0, median_glyph_width=5.0),+ _text_line("tail", (70.0, 766.0, 146.0, 773.0), 3, effective_height=7.0, median_glyph_width=5.0),+ ]++ entries = text_blocks._split_page_footnote_entries(+ lines,+ (595.0, 842.0),+ )++ assert [[line.source_index for line in entry] for entry in entries] == [+ [0],+ [1, 2, 3],+ ]+++def test_page_footnote_entries_split_hanging_indent_and_tighten_boxes() -> None:+ """验证 Boosting 型续行缩进拆成四条脚注,且异常高字符框不再互相覆盖。"""++ page_size = (612.2833862304688, 858.8975830078125)+ lines = [+ _text_line(+ "receipt",+ (81.2767, 740.0383, 238.2958, 758.6347),+ 66,+ effective_height=18.5964,+ median_glyph_width=3.92,+ semantic_type="page_footnote",+ ),+ _text_line(+ "fund start",+ (81.2767, 750.5583, 546.9993, 769.1547),+ 67,+ effective_height=9.0,+ median_glyph_width=7.84,+ semantic_type="page_footnote",+ ),+ _text_line(+ "fund continuation",+ (119.6767, 761.0783, 364.8372, 779.6747),+ 68,+ effective_height=10.38,+ median_glyph_width=4.78,+ semantic_type="page_footnote",+ ),+ _text_line(+ "author",+ (81.2767, 771.5983, 385.9195, 790.1947),+ 69,+ effective_height=9.0,+ median_glyph_width=7.84,+ semantic_type="page_footnote",+ ),+ _text_line(+ "corresponding",+ (81.2767, 782.1183, 439.2661, 800.7147),+ 70,+ effective_height=9.0,+ median_glyph_width=7.84,+ semantic_type="page_footnote",+ ),+ ]+ page = _prepared_text_page(*lines, page_size=page_size)+ page.page_footnote_groups = [{line.source_index for line in lines}]++ blocks = [+ block+ for block in pipeline._finalize_prepared_page(page, page_index=0)+ if block["type"] == "page_footnote"+ ]++ assert [block["content"] for block in blocks] == [+ "receipt",+ "fund start fund continuation",+ "author",+ "corresponding",+ ]+ assert [block["bbox"] for block in blocks] == [+ [0.133, 0.867, 0.389, 0.878],+ [0.133, 0.879, 0.893, 0.902],+ [0.133, 0.904, 0.63, 0.914],+ [0.133, 0.916, 0.717, 0.927],+ ]+ assert all(+ previous["bbox"][3] < current["bbox"][1]+ for previous, current in zip(blocks, blocks[1:])+ )+++ ("rule_bbox", "table_bboxes"),+ [+ ((100.0, 750.0, 125.0, 752.0), []),+ ((400.0, 750.0, 550.0, 752.0), []),+ ((100.0, 750.0, 260.0, 752.0), [(90.0, 730.0, 500.0, 850.0)]),+ (None, []),+ ],+)+def test_page_footnote_rejects_decorative_formula_table_and_missing_rules(+ rule_bbox: tuple[float, float, float, float] | None,+ table_bboxes: list[tuple[float, float, float, float]],+) -> None:+ """验证装饰短线、居中公式线、表格线和无横线页底正文均不触发脚注。"""++ lines = [+ _text_line("body one", (100.0, 100.0, 900.0, 110.0), 0),+ _text_line("body two", (100.0, 130.0, 900.0, 140.0), 1),+ _text_line("body three", (100.0, 160.0, 900.0, 170.0), 2),+ _text_line("bottom body", (100.0, 770.0, 500.0, 780.0), 3),+ ]+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))+ page.table_bboxes = table_bboxes+ if rule_bbox is not None:+ page.drawing_lines = [models._AxisLine(rule_bbox, 1.0, "horizontal")]++ auxiliary_text._classify_page_auxiliary_text(page)++ assert all(line.semantic_type is None for line in lines)+++def test_page_footnote_rejects_collinear_rule_segment_next_to_table() -> None:+ """验证表格框外的同高近邻断裂横线不会独立触发页脚注。"""++ lines = [+ _text_line("body one", (100.0, 100.0, 900.0, 110.0), 0),+ _text_line("body two", (100.0, 130.0, 900.0, 140.0), 1),+ _text_line("body three", (100.0, 160.0, 900.0, 170.0), 2),+ _text_line("bottom table row", (100.0, 770.0, 500.0, 780.0), 3),+ ]+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))+ page.table_bboxes = [(280.0, 730.0, 900.0, 850.0)]+ page.drawing_lines = [+ models._AxisLine((100.0, 750.0, 260.0, 752.0), 1.0, "horizontal"),+ models._AxisLine((280.0, 750.0, 900.0, 752.0), 1.0, "horizontal"),+ ]++ auxiliary_text._classify_page_auxiliary_text(page)++ assert all(line.semantic_type is None for line in lines)+ assert page.page_footnote_groups == []+++ ("angle", "bbox"),+ [+ (270, (20.0, 250.0, 50.0, 650.0)),+ (90, (930.0, 250.0, 960.0, 650.0)),+ ],+)+def test_aside_text_accepts_tall_vertical_text_in_either_edge_band(+ angle: int,+ bbox: tuple[float, float, float, float],+) -> None:+ """验证横排正文占主导时,左右边缘的高占比垂直文字均标为侧栏。"""++ lines = [+ *[+ _text_line(f"body {index}", (100.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index), index)+ for index in range(6)+ ],+ _text_line("aside", bbox, 6, angle=angle, effective_height=20.0),+ ]+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))++ auxiliary_text._classify_page_auxiliary_text(page)++ assert lines[-1].semantic_type == "aside_text"+ assert all(line.semantic_type is None for line in lines[:-1])+++def test_aside_text_rejects_short_internal_wide_and_non_dominant_rotated_text() -> None:+ """验证短旋转行、页内旋转行、过宽边缘行及旋转正文均不误报侧栏。"""++ upright_lines = [+ _text_line(f"body {index}", (100.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index), index)+ for index in range(10)+ ]+ rejected = [+ _text_line("short", (20.0, 250.0, 50.0, 350.0), 10, angle=270, effective_height=20.0),+ _text_line("internal", (400.0, 200.0, 430.0, 600.0), 11, angle=270, effective_height=20.0),+ _text_line("wide", (0.0, 200.0, 100.0, 600.0), 12, angle=270, effective_height=20.0),+ ]+ page = _prepared_text_page(*upright_lines, *rejected, page_size=(1000.0, 1000.0))+ auxiliary_text._classify_page_auxiliary_text(page)+ assert all(line.semantic_type is None for line in rejected)++ rotated_body = [+ _text_line(f"upright {index}", (100.0, 100.0 + 20.0 * index, 300.0, 110.0 + 20.0 * index), index)+ for index in range(4)+ ]+ rotated_body.append(+ _text_line("edge but not aside", (20.0, 200.0, 50.0, 700.0), 4, angle=270, effective_height=20.0)+ )+ rotated_page = _prepared_text_page(*rotated_body, page_size=(1000.0, 1000.0))+ auxiliary_text._classify_page_auxiliary_text(rotated_page)+ assert rotated_body[-1].semantic_type is None+++def test_auxiliary_text_classification_is_content_independent() -> None:+ """验证替换全部行文本不会改变页脚注空间分类结果。"""++ geometries = [+ (100.0, 100.0, 900.0, 110.0),+ (100.0, 130.0, 900.0, 140.0),+ (100.0, 160.0, 900.0, 170.0),+ (100.0, 770.0, 500.0, 780.0),+ (100.0, 788.0, 500.0, 798.0),+ ]+ first_lines = [_text_line(f"alpha {index}", bbox, index) for index, bbox in enumerate(geometries)]+ second_lines = [_text_line(f"完全不同 {index}", bbox, index) for index, bbox in enumerate(geometries)]+ first_page = _prepared_text_page(*first_lines, page_size=(1000.0, 1000.0))+ second_page = _prepared_text_page(*second_lines, page_size=(1000.0, 1000.0))+ for page in (first_page, second_page):+ page.drawing_lines = [+ models._AxisLine((100.0, 750.0, 260.0, 752.0), 1.0, "horizontal")+ ]+ auxiliary_text._classify_page_auxiliary_text(page)++ assert [line.semantic_type for line in first_lines] == [+ line.semantic_type for line in second_lines+ ]+ assert first_page.page_footnote_groups == second_page.page_footnote_groups+++def test_auxiliary_text_classifiers_do_not_read_line_text() -> None:+ """静态守卫侧栏和页脚注分类函数不访问文本内容。"""++ source = "\n".join(+ inspect.getsource(function)+ for function in (+ auxiliary_text._classify_page_auxiliary_text,+ auxiliary_text._classify_aside_text,+ auxiliary_text._geometric_text_support_by_angle,+ auxiliary_text._classify_page_footnotes,+ auxiliary_text._rule_belongs_to_confirmed_table,+ auxiliary_text._merge_overlapping_source_groups,+ auxiliary_text._footnote_lane_members,+ text_blocks._split_page_footnote_entries,+ text_blocks._tight_page_footnote_bboxes,+ )+ )++ assert ".text" not in source+++def test_finalize_preserves_preclassified_auxiliary_text_types() -> None:+ """验证单页终结阶段不会丢失已标注的侧栏和页脚注。"""++ page = _prepared_text_page(+ _text_line("note", (10.0, 80.0, 40.0, 90.0), 0, semantic_type="page_footnote"),+ _text_line(+ "aside",+ (2.0, 20.0, 5.0, 60.0),+ 1,+ angle=270,+ effective_height=3.0,+ semantic_type="aside_text",+ ),+ )++ blocks = pipeline._finalize_prepared_page(page, page_index=0)++ assert {block["type"] for block in blocks} == {"page_footnote", "aside_text"}+++def test_repeated_marginals_require_cross_page_evidence_and_separate_page_numbers() -> None:+ """验证重复页眉页脚与递增镜像页码被标注,孤立边缘行和正文不变。"""++ margin_font = ("Margin", 0)+ pages = [+ _prepared_text_page(+ _text_line("Quarterly report 2024 - 1", (20.0, 5.0, 80.0, 10.0), 0, font_signature=margin_font, font_coverage=1.0),+ _text_line("Only on first page", (20.0, 11.0, 80.0, 16.0), 1, font_signature=margin_font, font_coverage=1.0),+ _text_line("Repeated body", (10.0, 30.0, 90.0, 40.0), 2, font_signature=margin_font, font_coverage=1.0),+ _text_line("1", (4.0, 48.0, 6.0, 53.0), 3, font_signature=margin_font, font_coverage=1.0),+ _text_line("10", (5.0, 89.0, 10.0, 94.0), 4, font_signature=margin_font, font_coverage=1.0),+ _text_line("Confidential", (30.0, 95.0, 70.0, 99.0), 5, font_signature=margin_font, font_coverage=1.0),+ ),+ _prepared_text_page(+ _text_line("Quarterly report 2024 - 2", (20.0, 5.0, 80.0, 10.0), 0, font_signature=margin_font, font_coverage=1.0),+ _text_line("Repeated body", (10.0, 30.0, 90.0, 40.0), 1, font_signature=margin_font, font_coverage=1.0),+ _text_line("2", (4.0, 48.0, 6.0, 53.0), 2, font_signature=margin_font, font_coverage=1.0),+ _text_line("11", (90.0, 89.0, 95.0, 94.0), 3, font_signature=margin_font, font_coverage=1.0),+ _text_line("Confidential", (30.0, 95.0, 70.0, 99.0), 4, font_signature=margin_font, font_coverage=1.0),+ ),+ _prepared_text_page(+ _text_line("Quarterly report 2024 - 3", (20.0, 5.0, 80.0, 10.0), 0, font_signature=margin_font, font_coverage=1.0),+ _text_line("Repeated body", (10.0, 30.0, 90.0, 40.0), 1, font_signature=margin_font, font_coverage=1.0),+ _text_line("3", (4.0, 48.0, 6.0, 53.0), 2, font_signature=margin_font, font_coverage=1.0),+ _text_line("12", (5.0, 89.0, 10.0, 94.0), 3, font_signature=margin_font, font_coverage=1.0),+ _text_line("Confidential", (30.0, 95.0, 70.0, 99.0), 4, font_signature=margin_font, font_coverage=1.0),+ ),+ ]++ auxiliary_text._classify_repeated_page_marginals(pages)++ assert [[line.semantic_type for line in page.remaining_lines] for page in pages] == [+ ["header", None, None, None, "page_number", "footer"],+ ["header", None, None, "page_number", "footer"],+ ["header", None, None, "page_number", "footer"],+ ]+++def test_page_number_sequence_survives_portrait_to_landscape_edge_change() -> None:+ """验证横竖版切换时连续页码可从底边迁移到侧边,且后续侧边序列继续命中。"""++ pages = [+ _prepared_text_page(+ _text_line("2", (45.0, 126.0, 55.0, 131.0), 0),+ page_size=(100.0, 140.0),+ ),+ _prepared_text_page(+ _text_line("3", (126.0, 75.0, 131.0, 80.0), 0),+ page_size=(140.0, 100.0),+ ),+ _prepared_text_page(+ _text_line("4", (126.0, 75.0, 131.0, 80.0), 0),+ page_size=(140.0, 100.0),+ ),+ ]++ auxiliary_text._classify_repeated_page_marginals(pages)++ assert [page.remaining_lines[0].semantic_type for page in pages] == ["page_number"] * 3+++def test_single_page_marginal_content_remains_text() -> None:+ """验证单页顶部和底部文字不会仅凭位置被猜成页眉、页脚或页码。"""++ page = _prepared_text_page(+ _text_line("Page 7", (45.0, 3.0, 55.0, 8.0), 0),+ _text_line("Copyright notice", (20.0, 92.0, 80.0, 98.0), 1),+ )++ auxiliary_text._classify_repeated_page_marginals([page])++ assert [line.semantic_type for line in page.remaining_lines] == [None, None]++diff --git a/tests/unittest/test_flash_pdf_extractor.py b/tests/unittest/test_flash_pdf_extractor.pyindex 5ba7dc5d..29231f3b 100644--- a/tests/unittest/test_flash_pdf_extractor.py+++ b/tests/unittest/test_flash_pdf_extractor.py@@ -1,8 +1,6 @@from __future__ import annotations-import inspectimport sys-from pathlib import Pathfrom types import ModuleTypefrom typing import Anyfrom unittest.mock import MagicMock@@ -10,6 +8,9 @@ from unittest.mock import MagicMockimport pytestfrom mineru.backend.flash import pdf_extractor+from mineru.backend.flash.native_pdf import (+ pipeline,+)def _install_pdf_document(@@ -107,7 +108,7 @@ def test_txt_mode_keeps_native_flash_path(classified_mode="txt",)native_analyze = MagicMock(return_value=expected_model_list)- monkeypatch.setattr(pdf_extractor, "_analyze_native_document", native_analyze)+ monkeypatch.setattr(pipeline, "_analyze_native_document", native_analyze)hybrid_doc_analyze = _install_hybrid_analyze(monkeypatch,model_list=[[{"type": "text", "content": "unexpected"}]],@@ -122,8 +123,6 @@ def test_txt_mode_keeps_native_flash_path(assert pdf_doc.classify.call_count == expected_classify_callsnative_analyze.assert_called_once_with(pdf_doc)hybrid_doc_analyze.assert_not_called()--def test_invalid_parse_mode_is_rejected_before_opening_pdf(monkeypatch: pytest.MonkeyPatch) -> None:"""验证非法解析模式在打开 PDF 前保持原有报错行为。"""@@ -150,2962 +149,3 @@ def test_page_index_map_mismatch_is_rejected_before_hybrid_call(monkeypatch: pyt)hybrid_doc_analyze.assert_not_called()---def test_flash_extractor_has_no_local_ocr_runtime_logic() -> None:- """守卫 Flash extractor 不再引入或实现本地 OCR 运行时逻辑。"""-- source = inspect.getsource(pdf_extractor)- forbidden_tokens = (- "import numpy",- "import cv2",- "project_ocr_table_text",- "_load_ocr_runtime",- "_run_full_page_ocr",- "_project_ocr_candidate",- "_recognize_rotated_ocr_table",- "AtomModelSingleton",- "run_ocr_inference",- "get_processing_window_size",- "bgr_image",- "pixel_quad",- "ocr_model",- )-- assert not [token for token in forbidden_tokens if token in source]---def _formula_member(- text: str,- bbox: tuple[float, float, float, float],- source_index: int,-) -> tuple[pdf_extractor._LineItem, tuple[float, float, float, float]]:- """构造公式块序列化测试使用的文本行及其局部几何。"""-- return (- pdf_extractor._LineItem(- text=text,- bbox=bbox,- angle=0,- source_index=source_index,- effective_height=bbox[3] - bbox[1],- ),- bbox,- )---def test_detached_formula_sidecar_sharing_middle_row_moves_to_trailing_line() -> None:- """验证纯 bbox 规则会后置与正文共享中间视觉行的远距窄幅 sidecar。"""-- members = [- _formula_member("numerator", (20.0, 0.0, 60.0, 10.0), 0),- _formula_member("body", (10.0, 10.0, 40.0, 20.0), 1),- _formula_member("marker", (100.0, 10.0, 110.0, 20.0), 2),- _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),- ]-- block = pdf_extractor._formula_members_to_block(- members,- (130.0, 60.0),- 0,- anchor_source_index=2,- )-- assert block == {- "type": "equation",- "bbox": (10.0, 0.0, 110.0, 30.0),- "angle": 0,- "content": "numerator\nbody\ndenominator\nmarker",- }--[email protected]("marker", ["(4)", "(4)", "﹙4﹚", "(4)"])-def test_adjacent_parenthesized_formula_number_moves_to_trailing_line(marker: str) -> None:- """验证贴近公式主体的多种圆括号序号后置,且前导逗号留在原视觉行。"""-- members = [- _formula_member("numerator", (20.0, 0.0, 90.0, 10.0), 0),- _formula_member(f", {marker}", (91.0, 0.0, 110.0, 10.0), 1),- _formula_member("body", (10.0, 10.0, 40.0, 20.0), 2),- _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),- ]-- block = pdf_extractor._formula_members_to_block(- members,- (130.0, 60.0),- 0,- anchor_source_index=1,- )-- assert block == {- "type": "equation",- "bbox": (10.0, 0.0, 110.0, 30.0),- "angle": 0,- "content": f"numerator,\nbody\ndenominator\n{marker}",- }---def test_adjacent_square_bracket_formula_sidecar_keeps_visual_order() -> None:- """验证方括号内容不触发圆括号公式序号规则。"""-- members = [- _formula_member("numerator", (20.0, 0.0, 90.0, 10.0), 0),- _formula_member(", [4]", (91.0, 0.0, 110.0, 10.0), 1),- _formula_member("body", (10.0, 10.0, 40.0, 20.0), 2),- _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),- ]-- block = pdf_extractor._formula_members_to_block(- members,- (130.0, 60.0),- 0,- anchor_source_index=1,- )-- assert block == {- "type": "equation",- "bbox": (10.0, 0.0, 110.0, 30.0),- "angle": 0,- "content": "numerator, [4]\nbody\ndenominator",- }---def test_detached_formula_sidecar_on_middle_row_moves_after_denominator() -> None:- """验证独占中间视觉行的远距窄幅 sidecar 排到分母后且不留下空行。"""-- members = [- _formula_member("numerator", (20.0, 0.0, 70.0, 10.0), 0),- _formula_member("sidecar", (100.0, 10.0, 110.0, 20.0), 1),- _formula_member("denominator", (30.0, 20.0, 65.0, 30.0), 2),- ]-- block = pdf_extractor._formula_members_to_block(- members,- (130.0, 60.0),- 0,- anchor_source_index=1,- )-- assert block == {- "type": "equation",- "bbox": (20.0, 0.0, 110.0, 30.0),- "angle": 0,- "content": "numerator\ndenominator\nsidecar",- }---def test_detached_formula_sidecar_already_at_end_keeps_visual_row() -> None:- """验证已经处于内容末尾的离散 sidecar 保持原视觉行格式。"""-- members = [- _formula_member("formula", (10.0, 0.0, 40.0, 10.0), 0),- _formula_member("terminal", (100.0, 0.0, 110.0, 10.0), 1),- ]-- block = pdf_extractor._formula_members_to_block(- members,- (130.0, 60.0),- 0,- anchor_source_index=1,- )-- assert block == {- "type": "equation",- "bbox": (10.0, 0.0, 110.0, 10.0),- "angle": 0,- "content": "formula terminal",- }---def test_attached_formula_sidecar_keeps_visual_order() -> None:- """验证与公式主体净空不足的右侧锚点保持原视觉顺序。"""-- members = [- _formula_member("numerator", (20.0, 0.0, 60.0, 10.0), 0),- _formula_member("body", (10.0, 10.0, 70.0, 20.0), 1),- _formula_member("sidecar", (85.0, 10.0, 95.0, 20.0), 2),- _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),- ]-- block = pdf_extractor._formula_members_to_block(- members,- (120.0, 60.0),- 0,- anchor_source_index=2,- )-- assert block == {- "type": "equation",- "bbox": (10.0, 0.0, 95.0, 30.0),- "angle": 0,- "content": "numerator\nbody sidecar\ndenominator",- }---def test_wide_formula_sidecar_keeps_visual_order() -> None:- """验证宽度超过中位行高限制的远距锚点不会被后置。"""-- members = [- _formula_member("numerator", (20.0, 0.0, 60.0, 10.0), 0),- _formula_member("body", (10.0, 10.0, 70.0, 20.0), 1),- _formula_member("wide", (100.0, 10.0, 126.0, 20.0), 2),- _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),- ]-- block = pdf_extractor._formula_members_to_block(- members,- (140.0, 60.0),- 0,- anchor_source_index=2,- )-- assert block == {- "type": "equation",- "bbox": (10.0, 0.0, 126.0, 30.0),- "angle": 0,- "content": "numerator\nbody wide\ndenominator",- }---def test_non_rightmost_formula_sidecar_keeps_visual_order() -> None:- """验证未处于公式分量最右侧的锚点不会被后置。"""-- members = [- _formula_member("numerator", (20.0, 0.0, 120.0, 10.0), 0),- _formula_member("body", (10.0, 10.0, 40.0, 20.0), 1),- _formula_member("sidecar", (90.0, 10.0, 100.0, 20.0), 2),- _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),- ]-- block = pdf_extractor._formula_members_to_block(- members,- (140.0, 60.0),- 0,- anchor_source_index=2,- )-- assert block == {- "type": "equation",- "bbox": (10.0, 0.0, 120.0, 30.0),- "angle": 0,- "content": "numerator\nbody sidecar\ndenominator",- }---def _axis_line(- orientation: str,- bbox: tuple[float, float, float, float],-) -> pdf_extractor._LocalAxisLine:- """构造表格候选测试使用的局部横竖线。"""-- return pdf_extractor._LocalAxisLine(- bbox=bbox,- original_bbox=bbox,- orientation=orientation, # type: ignore[arg-type]- width=0.0,- )--- ("median_height", "rejected_length", "accepted_length"),- [- (3.0, 39.99, 40.0),- (5.0, 49.99, 50.0),- ],-)-def test_long_rule_group_uses_40pt_or_ten_times_height_threshold(- median_height: float,- rejected_length: float,- accepted_length: float,-) -> None:- """验证长横线沿用 40pt 或十倍行高门槛,竖线不参与分组。"""-- rejected_lines = [- _axis_line("horizontal", (0.0, 10.0, rejected_length, 10.1)),- _axis_line("horizontal", (0.0, 20.0, accepted_length, 20.1)),- _axis_line("horizontal", (0.0, 30.0, accepted_length, 30.1)),- _axis_line("vertical", (10.0, 0.0, 10.1, 40.0)),- ]- accepted_lines = [_axis_line("horizontal", (0.0, top, accepted_length, top + 0.1)) for top in (10.0, 20.0, 30.0)]-- assert pdf_extractor._group_long_horizontal_rules(rejected_lines, median_height) == []- assert len(pdf_extractor._group_long_horizontal_rules(accepted_lines, median_height)) == 1---def _rule_table_fixture(- rule_count: int = 3,- *,- centered_columns: bool = False,-) -> tuple[- list[pdf_extractor._VisualRow],- list[pdf_extractor._LineItem],- list[pdf_extractor._LocalAxisLine],-]:- """构造无 caption 的规则表格,并可切换为宽度变化的居中列。"""-- rows: list[pdf_extractor._VisualRow] = []- lines: list[pdf_extractor._LineItem] = []- source_index = 0- for row_index, top in enumerate((10.0, 30.0, 50.0)):- fragments: list[pdf_extractor._Fragment] = []- if centered_columns:- half_width = (2.0, 8.0, 14.0)[row_index]- column_bounds = (- (30.0 - half_width, 30.0 + half_width),- (90.0 - half_width, 90.0 + half_width),- )- else:- column_bounds = ((10.0, 20.0), (50.0, 60.0), (90.0, 100.0))- for column_index, (left, right) in enumerate(column_bounds):- bbox = (left, top, right, top + 5.0)- text = f"r{row_index}c{column_index}"- fragments.append(- pdf_extractor._Fragment(- text=text,- bbox=bbox,- local_bbox=bbox,- line_index=source_index,- visual_row_id=row_index,- )- )- lines.append(- pdf_extractor._LineItem(- text=text,- bbox=bbox,- angle=0,- source_index=source_index,- effective_height=5.0,- visual_row_id=row_index,- )- )- source_index += 1- rows.append(- pdf_extractor._VisualRow(- fragments=fragments,- center_y=top + 2.5,- bbox=(10.0, top, 100.0, top + 5.0),- visual_row_id=row_index,- )- )- axis_lines = [_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in (8.0, 33.0, 58.0)[:rule_count]]- return rows, lines, axis_lines---def test_rule_table_candidate_accepts_captionless_regular_text_distribution() -> None:- """验证三横线和连续稳定列足以识别没有显式标题的表格。"""-- rows, lines, axis_lines = _rule_table_fixture()-- candidates = pdf_extractor._build_rule_table_candidates(- rows,- lines,- (150.0, 100.0),- 0,- 5.0,- axis_lines,- )-- assert len(candidates) == 1- assert candidates[0].line_indices == set(range(9))---def test_rule_table_candidate_accepts_center_aligned_columns_with_varying_widths() -> None:- """验证左右边界变化但中心稳定的两列表格仍可形成候选。"""-- rows, lines, axis_lines = _rule_table_fixture(centered_columns=True)-- assert pdf_extractor._count_stable_columns(rows, 5.0) == (2, 1.0)- candidates = pdf_extractor._build_rule_table_candidates(- rows,- lines,- (150.0, 100.0),- 0,- 5.0,- axis_lines,- )-- assert len(candidates) == 1- assert candidates[0].line_indices == set(range(6))---def test_two_horizontal_rule_grid_is_deliberately_rejected() -> None:- """验证即使存在竖线和规则文本,两条长横线也不再形成表格候选。"""-- rows, lines, axis_lines = _rule_table_fixture(rule_count=2)- axis_lines.extend(- [- _axis_line("vertical", (0.0, 8.0, 0.1, 58.0)),- _axis_line("vertical", (55.0, 8.0, 55.1, 58.0)),- _axis_line("vertical", (109.9, 8.0, 110.0, 58.0)),- ]- )-- candidates = pdf_extractor._build_rule_table_candidates(- rows,- lines,- (150.0, 100.0),- 0,- 5.0,- axis_lines,- )-- assert candidates == []---def test_duplicate_horizontal_paths_do_not_satisfy_three_rule_requirement() -> None:- """验证同一 y 位置的重复 PDF path 只计为一条横线。"""-- axis_lines = [- _axis_line("horizontal", (0.0, 10.0, 100.0, 10.1)),- _axis_line("horizontal", (0.0, 10.5, 100.0, 10.6)),- _axis_line("horizontal", (0.0, 30.0, 100.0, 30.1)),- ]-- assert pdf_extractor._group_long_horizontal_rules(axis_lines, 5.0) == []---def test_chart_tick_rows_fail_dense_multi_cell_distribution() -> None:- """验证多个图表刻度行因纵向不连续而不能冒充规则表格。"""-- rows: list[pdf_extractor._VisualRow] = []- lines: list[pdf_extractor._LineItem] = []- source_index = 0- for row_index, (top, anchors) in enumerate(- (- (10.0, (10.0, 30.0, 50.0, 70.0, 90.0)),- (20.0, (50.0,)),- (30.0, (45.0,)),- (75.0, (10.0, 30.0, 50.0, 70.0, 90.0)),- (85.0, (50.0,)),- (95.0, (45.0,)),- )- ):- fragments: list[pdf_extractor._Fragment] = []- for anchor in anchors:- bbox = (anchor, top, anchor + 5.0, top + 5.0)- text = f"tick-{source_index}"- fragments.append(- pdf_extractor._Fragment(- text=text,- bbox=bbox,- local_bbox=bbox,- line_index=source_index,- visual_row_id=row_index,- )- )- lines.append(- pdf_extractor._LineItem(- text=text,- bbox=bbox,- angle=0,- source_index=source_index,- effective_height=5.0,- visual_row_id=row_index,- )- )- source_index += 1- rows.append(- pdf_extractor._VisualRow(- fragments=fragments,- center_y=top + 2.5,- bbox=pdf_extractor._bbox_union_many([fragment.bbox for fragment in fragments]),- visual_row_id=row_index,- )- )- axis_lines = [_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in (0.0, 55.0, 110.0)]-- candidates = pdf_extractor._build_rule_table_candidates(- rows,- lines,- (150.0, 120.0),- 0,- 5.0,- axis_lines,- )-- assert candidates == []---def test_split_table_footnote_marker_is_joined_before_matching() -> None:- """验证旋转表拆开的 For 与星号脚注在视觉行拼接后可被识别。"""-- row = pdf_extractor._VisualRow(- fragments=[- pdf_extractor._Fragment("For", (0.0, 0.0, 10.0, 5.0), (0.0, 0.0, 10.0, 5.0), 0),- pdf_extractor._Fragment("*rainfall", (12.0, 0.0, 35.0, 5.0), (12.0, 0.0, 35.0, 5.0), 1),- ],- center_y=2.5,- bbox=(0.0, 0.0, 35.0, 5.0),- )-- assert pdf_extractor._is_table_note_text(pdf_extractor._visual_row_text(row))- assert pdf_extractor._is_table_note_text("1 Numeric table footnote")--[email protected]("projection_mode", ["empty", "error"])-def test_failed_table_projection_does_not_claim_text(- monkeypatch: pytest.MonkeyPatch,- projection_mode: str,-) -> None:- """验证投影为空或抛错时完整回滚候选,文本行仍可进入正文路径。"""-- line = pdf_extractor._LineItem(- text="cell",- bbox=(10.0, 10.0, 30.0, 20.0),- angle=0,- source_index=0,- effective_height=10.0,- )- source = pdf_extractor._PageSource(- page_size=(100.0, 100.0),- lines=[line],- chars=[],- drawing_lines=[],- )- candidate = pdf_extractor._TableCandidate(- bbox=(0.0, 0.0, 50.0, 50.0),- local_bbox=(0.0, 0.0, 50.0, 50.0),- angle=0,- score=1.0,- core_bbox=(0.0, 0.0, 50.0, 50.0),- line_indices={0},- )- projection = MagicMock(return_value="")- if projection_mode == "error":- projection.side_effect = RuntimeError("projection failed")- monkeypatch.setattr(pdf_extractor, "project_pdf_table_text", projection)-- blocks, claimed = pdf_extractor._materialize_table_blocks(source, [candidate])-- assert blocks == []- assert claimed == set()---def _text_line(- text: str,- bbox: tuple[float, float, float, float],- source_index: int,- *,- angle: int = 0,- visual_row_id: int | None = None,- run_index: int = 0,- split_from_row: bool = False,- effective_height: float | None = None,- font_signature: tuple[str, int] | None = None,- font_coverage: float = 0.0,- dominant_font_weight: float | None = None,- median_glyph_width: float | None = None,- semantic_type: str | None = None,-) -> pdf_extractor._LineItem:- """构造栏带、排版恢复与图形标签测试使用的原生文本行。"""-- return pdf_extractor._LineItem(- text=text,- bbox=bbox,- angle=angle,- source_index=source_index,- visual_row_id=visual_row_id,- run_index=run_index,- effective_height=effective_height or (bbox[3] - bbox[1]),- font_signature=font_signature,- font_coverage=font_coverage,- dominant_font_weight=dominant_font_weight,- median_glyph_width=median_glyph_width,- split_from_row=split_from_row,- semantic_type=semantic_type,- )---def _prepared_text_page(- *lines: pdf_extractor._LineItem,- page_size: tuple[float, float] = (100.0, 100.0),-) -> pdf_extractor._PreparedPage:- """构造跨页边缘类型测试使用的无容器轻量页面。"""-- return pdf_extractor._PreparedPage(- page_size=page_size,- remaining_lines=list(lines),- table_bboxes=[],- drawing_lines=[],- fixed_blocks=[],- )---def test_page_footnote_uses_separator_and_stops_before_distant_footer_text() -> None:- """验证单栏页脚注由页底横线触发,并在较大行间隙前停止扩展。"""-- lines = [- _text_line("body one", (100.0, 100.0, 900.0, 110.0), 0),- _text_line("body two", (100.0, 130.0, 900.0, 140.0), 1),- _text_line("body three", (100.0, 160.0, 900.0, 170.0), 2),- _text_line("note one", (100.0, 770.0, 500.0, 780.0), 3),- _text_line("note two", (100.0, 788.0, 500.0, 798.0), 4),- _text_line("note three", (100.0, 806.0, 500.0, 816.0), 5),- _text_line("footer text", (100.0, 850.0, 600.0, 860.0), 6),- ]- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))- page.drawing_lines = [- pdf_extractor._AxisLine(- bbox=(100.0, 750.0, 260.0, 752.0),- width=1.0,- orientation="horizontal",- ),- pdf_extractor._AxisLine(- bbox=(100.0, 750.5, 260.0, 752.5),- width=1.0,- orientation="horizontal",- ),- ]-- pdf_extractor._classify_page_auxiliary_text(page)-- assert [line.semantic_type for line in lines] == [- None,- None,- None,- "page_footnote",- "page_footnote",- "page_footnote",- None,- ]- assert page.page_footnote_groups == [{3, 4, 5}]---def test_page_footnote_supports_independent_column_rules() -> None:- """验证左右栏各自的短横线只认领本栏连续页脚注。"""-- lines = [- *[- _text_line(f"left body {index}", (80.0, 100.0 + 30.0 * index, 460.0, 110.0 + 30.0 * index), index)- for index in range(3)- ],- *[- _text_line(- f"right body {index}",- (540.0, 100.0 + 30.0 * index, 920.0, 110.0 + 30.0 * index),- index + 3,- )- for index in range(3)- ],- _text_line("left note one", (80.0, 820.0, 400.0, 830.0), 6),- _text_line("left note two", (80.0, 838.0, 400.0, 848.0), 7),- _text_line("right note one", (540.0, 820.0, 860.0, 830.0), 8),- _text_line("right note two", (540.0, 838.0, 860.0, 848.0), 9),- ]- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))- page.drawing_lines = [- pdf_extractor._AxisLine((80.0, 800.0, 220.0, 802.0), 1.0, "horizontal"),- pdf_extractor._AxisLine((540.0, 800.0, 680.0, 802.0), 1.0, "horizontal"),- ]-- pdf_extractor._classify_page_auxiliary_text(page)-- assert all(line.semantic_type is None for line in lines[:6])- assert all(line.semantic_type == "page_footnote" for line in lines[6:])- assert page.page_footnote_groups == [{6, 7}, {8, 9}]---def test_page_footnote_unions_aligned_regular_and_span_lanes_only() -> None:- """验证同左缘 regular/span 栏可联合认领,但不会吞掉右侧正文栏。"""-- lines = [- *[- _text_line(f"left body {index}", (100.0, 100.0 + 30.0 * index, 480.0, 110.0 + 30.0 * index), index)- for index in range(3)- ],- *[- _text_line(- f"right body {index}",- (520.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index),- index + 3,- )- for index in range(3)- ],- _text_line("span note one", (100.0, 810.0, 900.0, 820.0), 6),- _text_line("span note two", (100.0, 830.0, 900.0, 840.0), 7),- _text_line("span note three", (100.0, 850.0, 900.0, 860.0), 8),- _text_line("left note one", (100.0, 812.0, 480.0, 822.0), 9),- _text_line("left note two", (100.0, 832.0, 480.0, 842.0), 10),- _text_line("right body below rule", (520.0, 812.0, 900.0, 822.0), 11),- ]- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))- page.drawing_lines = [- pdf_extractor._AxisLine((100.0, 800.0, 305.0, 802.0), 1.0, "horizontal")- ]-- pdf_extractor._classify_page_auxiliary_text(page)-- assert {line.source_index for line in lines if line.semantic_type == "page_footnote"} == {- 6,- 7,- 8,- 9,- 10,- }- assert page.page_footnote_groups == [{6, 7, 8, 9, 10}]- assert lines[11].semantic_type is None---def test_page_footnote_entries_split_first_line_indent_without_text() -> None:- """验证首行缩进模式把两个脚注起始行拆开,并吸收左对齐续行。"""-- lines = [- _text_line("first", (87.0, 732.0, 245.0, 742.0), 0, effective_height=8.0, median_glyph_width=4.5),- _text_line("second", (83.0, 743.0, 293.0, 753.0), 1, effective_height=8.0, median_glyph_width=4.5),- _text_line("continuation", (70.0, 755.0, 276.0, 763.0), 2, effective_height=7.0, median_glyph_width=5.0),- _text_line("tail", (70.0, 766.0, 146.0, 773.0), 3, effective_height=7.0, median_glyph_width=5.0),- ]-- entries = pdf_extractor._split_page_footnote_entries(- lines,- (595.0, 842.0),- )-- assert [[line.source_index for line in entry] for entry in entries] == [- [0],- [1, 2, 3],- ]---def test_page_footnote_entries_split_hanging_indent_and_tighten_boxes() -> None:- """验证 Boosting 型续行缩进拆成四条脚注,且异常高字符框不再互相覆盖。"""-- page_size = (612.2833862304688, 858.8975830078125)- lines = [- _text_line(- "receipt",- (81.2767, 740.0383, 238.2958, 758.6347),- 66,- effective_height=18.5964,- median_glyph_width=3.92,- semantic_type="page_footnote",- ),- _text_line(- "fund start",- (81.2767, 750.5583, 546.9993, 769.1547),- 67,- effective_height=9.0,- median_glyph_width=7.84,- semantic_type="page_footnote",- ),- _text_line(- "fund continuation",- (119.6767, 761.0783, 364.8372, 779.6747),- 68,- effective_height=10.38,- median_glyph_width=4.78,- semantic_type="page_footnote",- ),- _text_line(- "author",- (81.2767, 771.5983, 385.9195, 790.1947),- 69,- effective_height=9.0,- median_glyph_width=7.84,- semantic_type="page_footnote",- ),- _text_line(- "corresponding",- (81.2767, 782.1183, 439.2661, 800.7147),- 70,- effective_height=9.0,- median_glyph_width=7.84,- semantic_type="page_footnote",- ),- ]- page = _prepared_text_page(*lines, page_size=page_size)- page.page_footnote_groups = [{line.source_index for line in lines}]-- blocks = [- block- for block in pdf_extractor._finalize_prepared_page(page, page_index=0)- if block["type"] == "page_footnote"- ]-- assert [block["content"] for block in blocks] == [- "receipt",- "fund start fund continuation",- "author",- "corresponding",- ]- assert [block["bbox"] for block in blocks] == [- [0.133, 0.867, 0.389, 0.878],- [0.133, 0.879, 0.893, 0.902],- [0.133, 0.904, 0.63, 0.914],- [0.133, 0.916, 0.717, 0.927],- ]- assert all(- previous["bbox"][3] < current["bbox"][1]- for previous, current in zip(blocks, blocks[1:])- )--- ("rule_bbox", "table_bboxes"),- [- ((100.0, 750.0, 125.0, 752.0), []),- ((400.0, 750.0, 550.0, 752.0), []),- ((100.0, 750.0, 260.0, 752.0), [(90.0, 730.0, 500.0, 850.0)]),- (None, []),- ],-)-def test_page_footnote_rejects_decorative_formula_table_and_missing_rules(- rule_bbox: tuple[float, float, float, float] | None,- table_bboxes: list[tuple[float, float, float, float]],-) -> None:- """验证装饰短线、居中公式线、表格线和无横线页底正文均不触发脚注。"""-- lines = [- _text_line("body one", (100.0, 100.0, 900.0, 110.0), 0),- _text_line("body two", (100.0, 130.0, 900.0, 140.0), 1),- _text_line("body three", (100.0, 160.0, 900.0, 170.0), 2),- _text_line("bottom body", (100.0, 770.0, 500.0, 780.0), 3),- ]- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))- page.table_bboxes = table_bboxes- if rule_bbox is not None:- page.drawing_lines = [pdf_extractor._AxisLine(rule_bbox, 1.0, "horizontal")]-- pdf_extractor._classify_page_auxiliary_text(page)-- assert all(line.semantic_type is None for line in lines)---def test_page_footnote_rejects_collinear_rule_segment_next_to_table() -> None:- """验证表格框外的同高近邻断裂横线不会独立触发页脚注。"""-- lines = [- _text_line("body one", (100.0, 100.0, 900.0, 110.0), 0),- _text_line("body two", (100.0, 130.0, 900.0, 140.0), 1),- _text_line("body three", (100.0, 160.0, 900.0, 170.0), 2),- _text_line("bottom table row", (100.0, 770.0, 500.0, 780.0), 3),- ]- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))- page.table_bboxes = [(280.0, 730.0, 900.0, 850.0)]- page.drawing_lines = [- pdf_extractor._AxisLine((100.0, 750.0, 260.0, 752.0), 1.0, "horizontal"),- pdf_extractor._AxisLine((280.0, 750.0, 900.0, 752.0), 1.0, "horizontal"),- ]-- pdf_extractor._classify_page_auxiliary_text(page)-- assert all(line.semantic_type is None for line in lines)- assert page.page_footnote_groups == []--- ("angle", "bbox"),- [- (270, (20.0, 250.0, 50.0, 650.0)),- (90, (930.0, 250.0, 960.0, 650.0)),- ],-)-def test_aside_text_accepts_tall_vertical_text_in_either_edge_band(- angle: int,- bbox: tuple[float, float, float, float],-) -> None:- """验证横排正文占主导时,左右边缘的高占比垂直文字均标为侧栏。"""-- lines = [- *[- _text_line(f"body {index}", (100.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index), index)- for index in range(6)- ],- _text_line("aside", bbox, 6, angle=angle, effective_height=20.0),- ]- page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))-- pdf_extractor._classify_page_auxiliary_text(page)-- assert lines[-1].semantic_type == "aside_text"- assert all(line.semantic_type is None for line in lines[:-1])---def test_aside_text_rejects_short_internal_wide_and_non_dominant_rotated_text() -> None:- """验证短旋转行、页内旋转行、过宽边缘行及旋转正文均不误报侧栏。"""-- upright_lines = [- _text_line(f"body {index}", (100.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index), index)- for index in range(10)- ]- rejected = [- _text_line("short", (20.0, 250.0, 50.0, 350.0), 10, angle=270, effective_height=20.0),- _text_line("internal", (400.0, 200.0, 430.0, 600.0), 11, angle=270, effective_height=20.0),- _text_line("wide", (0.0, 200.0, 100.0, 600.0), 12, angle=270, effective_height=20.0),- ]- page = _prepared_text_page(*upright_lines, *rejected, page_size=(1000.0, 1000.0))- pdf_extractor._classify_page_auxiliary_text(page)- assert all(line.semantic_type is None for line in rejected)-- rotated_body = [- _text_line(f"upright {index}", (100.0, 100.0 + 20.0 * index, 300.0, 110.0 + 20.0 * index), index)- for index in range(4)- ]- rotated_body.append(- _text_line("edge but not aside", (20.0, 200.0, 50.0, 700.0), 4, angle=270, effective_height=20.0)- )- rotated_page = _prepared_text_page(*rotated_body, page_size=(1000.0, 1000.0))- pdf_extractor._classify_page_auxiliary_text(rotated_page)- assert rotated_body[-1].semantic_type is None---def test_auxiliary_text_classification_is_content_independent() -> None:- """验证替换全部行文本不会改变页脚注空间分类结果。"""-- geometries = [- (100.0, 100.0, 900.0, 110.0),- (100.0, 130.0, 900.0, 140.0),- (100.0, 160.0, 900.0, 170.0),- (100.0, 770.0, 500.0, 780.0),- (100.0, 788.0, 500.0, 798.0),- ]- first_lines = [_text_line(f"alpha {index}", bbox, index) for index, bbox in enumerate(geometries)]- second_lines = [_text_line(f"完全不同 {index}", bbox, index) for index, bbox in enumerate(geometries)]- first_page = _prepared_text_page(*first_lines, page_size=(1000.0, 1000.0))- second_page = _prepared_text_page(*second_lines, page_size=(1000.0, 1000.0))- for page in (first_page, second_page):- page.drawing_lines = [- pdf_extractor._AxisLine((100.0, 750.0, 260.0, 752.0), 1.0, "horizontal")- ]- pdf_extractor._classify_page_auxiliary_text(page)-- assert [line.semantic_type for line in first_lines] == [- line.semantic_type for line in second_lines- ]- assert first_page.page_footnote_groups == second_page.page_footnote_groups---def test_auxiliary_text_classifiers_do_not_read_line_text() -> None:- """静态守卫侧栏和页脚注分类函数不访问文本内容。"""-- source = "\n".join(- inspect.getsource(function)- for function in (- pdf_extractor._classify_page_auxiliary_text,- pdf_extractor._classify_aside_text,- pdf_extractor._geometric_text_support_by_angle,- pdf_extractor._classify_page_footnotes,- pdf_extractor._rule_belongs_to_confirmed_table,- pdf_extractor._merge_overlapping_source_groups,- pdf_extractor._footnote_lane_members,- pdf_extractor._split_page_footnote_entries,- pdf_extractor._tight_page_footnote_bboxes,- )- )-- assert ".text" not in source---def test_finalize_preserves_preclassified_auxiliary_text_types() -> None:- """验证单页终结阶段不会丢失已标注的侧栏和页脚注。"""-- page = _prepared_text_page(- _text_line("note", (10.0, 80.0, 40.0, 90.0), 0, semantic_type="page_footnote"),- _text_line(- "aside",- (2.0, 20.0, 5.0, 60.0),- 1,- angle=270,- effective_height=3.0,- semantic_type="aside_text",- ),- )-- blocks = pdf_extractor._finalize_prepared_page(page, page_index=0)-- assert {block["type"] for block in blocks} == {"page_footnote", "aside_text"}---def test_repeated_marginals_require_cross_page_evidence_and_separate_page_numbers() -> None:- """验证重复页眉页脚与递增镜像页码被标注,孤立边缘行和正文不变。"""-- margin_font = ("Margin", 0)- pages = [- _prepared_text_page(- _text_line("Quarterly report 2024 - 1", (20.0, 5.0, 80.0, 10.0), 0, font_signature=margin_font, font_coverage=1.0),- _text_line("Only on first page", (20.0, 11.0, 80.0, 16.0), 1, font_signature=margin_font, font_coverage=1.0),- _text_line("Repeated body", (10.0, 30.0, 90.0, 40.0), 2, font_signature=margin_font, font_coverage=1.0),- _text_line("1", (4.0, 48.0, 6.0, 53.0), 3, font_signature=margin_font, font_coverage=1.0),- _text_line("10", (5.0, 89.0, 10.0, 94.0), 4, font_signature=margin_font, font_coverage=1.0),- _text_line("Confidential", (30.0, 95.0, 70.0, 99.0), 5, font_signature=margin_font, font_coverage=1.0),- ),- _prepared_text_page(- _text_line("Quarterly report 2024 - 2", (20.0, 5.0, 80.0, 10.0), 0, font_signature=margin_font, font_coverage=1.0),- _text_line("Repeated body", (10.0, 30.0, 90.0, 40.0), 1, font_signature=margin_font, font_coverage=1.0),- _text_line("2", (4.0, 48.0, 6.0, 53.0), 2, font_signature=margin_font, font_coverage=1.0),- _text_line("11", (90.0, 89.0, 95.0, 94.0), 3, font_signature=margin_font, font_coverage=1.0),- _text_line("Confidential", (30.0, 95.0, 70.0, 99.0), 4, font_signature=margin_font, font_coverage=1.0),- ),- _prepared_text_page(- _text_line("Quarterly report 2024 - 3", (20.0, 5.0, 80.0, 10.0), 0, font_signature=margin_font, font_coverage=1.0),- _text_line("Repeated body", (10.0, 30.0, 90.0, 40.0), 1, font_signature=margin_font, font_coverage=1.0),- _text_line("3", (4.0, 48.0, 6.0, 53.0), 2, font_signature=margin_font, font_coverage=1.0),- _text_line("12", (5.0, 89.0, 10.0, 94.0), 3, font_signature=margin_font, font_coverage=1.0),- _text_line("Confidential", (30.0, 95.0, 70.0, 99.0), 4, font_signature=margin_font, font_coverage=1.0),- ),- ]-- pdf_extractor._classify_repeated_page_marginals(pages)-- assert [[line.semantic_type for line in page.remaining_lines] for page in pages] == [- ["header", None, None, None, "page_number", "footer"],- ["header", None, None, "page_number", "footer"],- ["header", None, None, "page_number", "footer"],- ]---def test_page_number_sequence_survives_portrait_to_landscape_edge_change() -> None:- """验证横竖版切换时连续页码可从底边迁移到侧边,且后续侧边序列继续命中。"""-- pages = [- _prepared_text_page(- _text_line("2", (45.0, 126.0, 55.0, 131.0), 0),- page_size=(100.0, 140.0),- ),- _prepared_text_page(- _text_line("3", (126.0, 75.0, 131.0, 80.0), 0),- page_size=(140.0, 100.0),- ),- _prepared_text_page(- _text_line("4", (126.0, 75.0, 131.0, 80.0), 0),- page_size=(140.0, 100.0),- ),- ]-- pdf_extractor._classify_repeated_page_marginals(pages)-- assert [page.remaining_lines[0].semantic_type for page in pages] == ["page_number"] * 3---def test_single_page_marginal_content_remains_text() -> None:- """验证单页顶部和底部文字不会仅凭位置被猜成页眉、页脚或页码。"""-- page = _prepared_text_page(- _text_line("Page 7", (45.0, 3.0, 55.0, 8.0), 0),- _text_line("Copyright notice", (20.0, 92.0, 80.0, 98.0), 1),- )-- pdf_extractor._classify_repeated_page_marginals([page])-- assert [line.semantic_type for line in page.remaining_lines] == [None, None]--[email protected]("heading_text", ["1. INTRODUCTION", "completely unrelated words"])-def test_paragraph_title_classification_is_independent_of_heading_content(heading_text: str) -> None:- """验证相同版式和字体的不同内容得到完全相同的段落标题类型。"""-- body_font = ("Body", 0)- heading_font = ("Heading", 1)- lines = [- _text_line("body one", (0.0, 10.0, 100.0, 20.0), 0, font_signature=body_font, font_coverage=1.0),- _text_line("body two", (0.0, 22.0, 100.0, 32.0), 1, font_signature=body_font, font_coverage=1.0),- _text_line(heading_text, (0.0, 45.0, 40.0, 55.0), 2, font_signature=heading_font, font_coverage=1.0),- _text_line("body three", (0.0, 68.0, 100.0, 78.0), 3, font_signature=body_font, font_coverage=1.0),- _text_line("body four", (0.0, 80.0, 100.0, 90.0), 4, font_signature=body_font, font_coverage=1.0),- _text_line("body five", (0.0, 92.0, 100.0, 102.0), 5, font_signature=body_font, font_coverage=1.0),- ]-- pdf_extractor._classify_page_titles(lines, (100.0, 150.0), page_index=1, container_bboxes=[])-- assert lines[2].semantic_type == "paragraph_title"---def test_heading_like_content_with_body_layout_remains_text() -> None:- """验证标题式字符串在正文几何、正文字体和常规行距下仍保持普通文本。"""-- body_font = ("Body", 0)- lines = [- _text_line(- f"body {index}",- (0.0, 10.0 + 12.0 * index, 100.0, 20.0 + 12.0 * index),- index,- font_signature=body_font,- font_coverage=1.0,- )- for index in range(6)- ]- lines[2].text = "1. INTRODUCTION"-- pdf_extractor._classify_page_titles(lines, (100.0, 120.0), page_index=1, container_bboxes=[])-- assert lines[2].semantic_type is None---def test_centered_smaller_paragraph_title_uses_layout_contrast_only() -> None:- """验证同字体的小字号居中标题可由栏宽和上下留白识别。"""-- body_font = ("Body", 0)- lines = [- _text_line("body one", (0.0, 10.0, 100.0, 20.0), 0, font_signature=body_font, font_coverage=1.0),- _text_line("body two", (0.0, 22.0, 100.0, 32.0), 1, font_signature=body_font, font_coverage=1.0),- _text_line(- "neutral label",- (30.0, 45.0, 70.0, 53.0),- 2,- effective_height=8.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line("body three", (0.0, 66.0, 100.0, 76.0), 3, font_signature=body_font, font_coverage=1.0),- _text_line("body four", (0.0, 78.0, 100.0, 88.0), 4, font_signature=body_font, font_coverage=1.0),- _text_line("body five", (0.0, 90.0, 100.0, 100.0), 5, font_signature=body_font, font_coverage=1.0),- ]-- pdf_extractor._classify_page_titles(lines, (100.0, 150.0), page_index=1, container_bboxes=[])-- assert lines[2].semantic_type == "paragraph_title"---def test_multiline_document_title_does_not_absorb_author_line() -> None:- """验证首页两行大字号标题合并为文档标题,较小作者行保持普通文本。"""-- body_font = ("Body", 0)- title_font = ("Title", 0)- lines = [- _text_line(- "title line one",- (15.0, 20.0, 85.0, 34.4),- 0,- effective_height=14.4,- font_signature=title_font,- font_coverage=1.0,- ),- _text_line(- "title line two",- (10.0, 33.8, 90.0, 48.2),- 1,- effective_height=14.4,- font_signature=title_font,- font_coverage=1.0,- ),- _text_line(- "author names",- (20.0, 60.0, 80.0, 69.1),- 2,- effective_height=9.1,- font_signature=title_font,- font_coverage=1.0,- ),- _text_line("body one", (0.0, 110.0, 100.0, 120.0), 3, font_signature=body_font, font_coverage=1.0),- _text_line("body two", (0.0, 122.0, 100.0, 132.0), 4, font_signature=body_font, font_coverage=1.0),- _text_line("body three", (0.0, 134.0, 100.0, 144.0), 5, font_signature=body_font, font_coverage=1.0),- ]-- pdf_extractor._classify_page_titles(lines, (100.0, 200.0), page_index=0, container_bboxes=[])-- assert [line.semantic_type for line in lines[:3]] == ["doc_title", "doc_title", None]---def test_cross_column_document_title_uses_thirteen_tenths_body_height_fallback() -> None:- """验证首页跨栏居中标题达到正文 1.30 倍时可命中,作者行保持正文类型。"""-- body_font = ("Body", 0)- title_font = ("Title", 0)- lines = [- _text_line(- "wide title",- (20.0, 20.0, 180.0, 33.0),- 0,- effective_height=13.0,- font_signature=title_font,- font_coverage=1.0,- ),- _text_line(- "author row",- (60.0, 42.0, 140.0, 52.0),- 1,- effective_height=10.0,- font_signature=title_font,- font_coverage=1.0,- ),- ]- for row_index, top in enumerate((80.0, 92.0, 104.0, 116.0)):- lines.extend(- [- _text_line(- f"left body {row_index}",- (10.0, top, 90.0, top + 10.0),- 2 + row_index * 2,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- f"right body {row_index}",- (110.0, top, 190.0, top + 10.0),- 3 + row_index * 2,- font_signature=body_font,- font_coverage=1.0,- ),- ]- )-- pdf_extractor._classify_page_titles(- lines,- (200.0, 200.0),- page_index=0,- container_bboxes=[],- )-- assert lines[0].semantic_type == "doc_title"- assert lines[1].semantic_type != "paragraph_title"---def test_complete_visual_row_promotes_number_and_demotes_inline_body() -> None:- """验证同字体编号整行晋升,标题字体与正文同排时整行降级并重新合并。"""-- body_font = ("Body", 0)- title_font = ("Title", 0)- lines = [- _text_line("body one", (0.0, 5.0, 100.0, 15.0), 0, font_signature=body_font, font_coverage=1.0),- _text_line("body two", (0.0, 17.0, 100.0, 27.0), 1, font_signature=body_font, font_coverage=1.0),- _text_line(- "2",- (0.0, 42.0, 8.0, 52.0),- 2,- visual_row_id=20,- split_from_row=True,- font_signature=title_font,- font_coverage=1.0,- dominant_font_weight=700.0,- ),- _text_line(- "neutral heading",- (15.0, 42.0, 60.0, 52.0),- 3,- visual_row_id=20,- split_from_row=True,- font_signature=title_font,- font_coverage=1.0,- dominant_font_weight=700.0,- ),- _text_line("body three", (0.0, 65.0, 100.0, 75.0), 4, font_signature=body_font, font_coverage=1.0),- _text_line(- "inline label",- (0.0, 82.0, 32.0, 92.0),- 5,- visual_row_id=30,- split_from_row=True,- font_signature=title_font,- font_coverage=1.0,- dominant_font_weight=700.0,- ),- _text_line(- "inline body",- (34.0, 82.0, 100.0, 92.0),- 6,- visual_row_id=30,- split_from_row=True,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line("body four", (0.0, 94.0, 100.0, 104.0), 7, font_signature=body_font, font_coverage=1.0),- ]-- pdf_extractor._classify_page_titles(- lines,- (100.0, 140.0),- page_index=1,- container_bboxes=[],- )- merged = pdf_extractor._merge_title_resolved_visual_rows(lines, (100.0, 140.0))-- numbered_title = next(line for line in merged if line.visual_row_id == 20)- inline_row = next(line for line in merged if line.visual_row_id == 30)- assert numbered_title.semantic_type == "paragraph_title"- assert numbered_title.text == "2 neutral heading"- assert inline_row.semantic_type is None- assert inline_row.text == "inline label inline body"---def test_low_coverage_mixed_weight_visual_row_demotes_inline_title() -> None:- """验证低字体覆盖率的同一视觉行仍按字重冲突识别为行内粗体正文。"""-- body_font = ("Body", 0)- lines = [- _text_line(- "body one",- (0.0, 0.0, 100.0, 10.0),- 0,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "body two",- (0.0, 12.0, 100.0, 22.0),- 1,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "body three",- (0.0, 24.0, 100.0, 34.0),- 2,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- _text_line(- "inline label",- (0.0, 50.0, 35.0, 62.0),- 3,- visual_row_id=30,- split_from_row=True,- font_signature=("Heading", 0),- font_coverage=0.6,- dominant_font_weight=700.0,- ),- _text_line(- "inline body",- (37.0, 50.0, 100.0, 62.0),- 4,- visual_row_id=30,- run_index=1,- split_from_row=True,- font_signature=body_font,- font_coverage=0.6,- dominant_font_weight=400.0,- ),- _text_line(- "body continuation",- (0.0, 64.0, 100.0, 74.0),- 5,- font_signature=body_font,- font_coverage=1.0,- dominant_font_weight=400.0,- ),- ]-- pdf_extractor._classify_page_titles(- lines,- (100.0, 100.0),- page_index=1,- container_bboxes=[],- )- merged = pdf_extractor._merge_title_resolved_visual_rows(lines, (100.0, 100.0))-- inline_row = next(line for line in merged if line.visual_row_id == 30)- assert inline_row.semantic_type is None- assert inline_row.text == "inline label inline body"---def test_full_width_normal_height_inline_heading_merges_with_body_continuation() -> None:- """验证满栏正常字号粗体行降为正文,并只与其下方常规正文续接。"""-- body_font = ("Body", 0)- heading_font = ("Heading", 1)- lines = [- _text_line("body one", (0.0, 0.0, 100.0, 10.0), 0, font_signature=body_font, font_coverage=1.0),- _text_line("body two", (0.0, 12.0, 100.0, 22.0), 1, font_signature=body_font, font_coverage=1.0),- _text_line(- "inline heading",- (0.0, 40.0, 100.0, 50.0),- 2,- font_signature=heading_font,- font_coverage=1.0,- dominant_font_weight=700.0,- ),- _text_line(- "continuation one",- (0.0, 52.0, 100.0, 62.0),- 3,- effective_height=8.0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line("continuation two", (0.0, 64.0, 100.0, 74.0), 4, font_signature=body_font, font_coverage=1.0),- _text_line("continuation three", (0.0, 76.0, 100.0, 86.0), 5, font_signature=body_font, font_coverage=1.0),- ]-- pdf_extractor._classify_page_titles(- lines,- (100.0, 120.0),- page_index=1,- container_bboxes=[],- )- blocks = pdf_extractor._build_text_blocks(lines, [], (100.0, 120.0))-- inline_block = next(block for block in blocks if block["content"].startswith("inline heading"))- assert lines[2].semantic_type is None- assert inline_block["type"] == "text"- assert "continuation one" in inline_block["content"]- assert "body two" not in inline_block["content"]---def test_dense_same_font_two_run_row_requires_complete_high_occupancy_geometry() -> None:- """验证双 run 正文仅在同字体、同基线、连续编号且占用充分时恢复。"""-- body_font = ("Body", 0)- dense_members = [- _text_line(- "left",- (0.0, 0.0, 48.0, 10.0),- 0,- visual_row_id=10,- run_index=0,- split_from_row=True,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "right",- (52.0, 0.0, 100.0, 10.0),- 1,- visual_row_id=10,- run_index=1,- split_from_row=True,- font_signature=body_font,- font_coverage=1.0,- ),- ]- sparse_members = [- _text_line(- "sparse left",- (0.0, 20.0, 30.0, 30.0),- 2,- visual_row_id=20,- run_index=0,- split_from_row=True,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "sparse right",- (70.0, 20.0, 100.0, 30.0),- 3,- visual_row_id=20,- run_index=1,- split_from_row=True,- font_signature=body_font,- font_coverage=1.0,- ),- ]- partial_formula_row = [- _text_line(- "formula body",- (0.0, 40.0, 48.0, 50.0),- 4,- visual_row_id=30,- run_index=0,- split_from_row=True,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "sidecar",- (52.0, 40.0, 100.0, 50.0),- 5,- visual_row_id=30,- run_index=2,- split_from_row=True,- font_signature=body_font,- font_coverage=1.0,- ),- ]- different_font_members = [- dense_members[0],- _text_line(- "different",- (52.0, 0.0, 100.0, 10.0),- 6,- visual_row_id=10,- run_index=1,- split_from_row=True,- font_signature=("Math", 0),- font_coverage=1.0,- ),- ]-- assert pdf_extractor._is_dense_same_font_two_run_row(dense_members, (100.0, 100.0))- assert not pdf_extractor._is_dense_same_font_two_run_row(sparse_members, (100.0, 100.0))- assert not pdf_extractor._is_dense_same_font_two_run_row(partial_formula_row, (100.0, 100.0))- assert not pdf_extractor._is_dense_same_font_two_run_row(different_font_members, (100.0, 100.0))-- merged = pdf_extractor._merge_title_resolved_visual_rows(- dense_members + sparse_members,- (100.0, 100.0),- )- assert [line.text for line in merged if line.visual_row_id == 10] == ["left right"]- assert len([line for line in merged if line.visual_row_id == 20]) == 2---def test_paragraph_title_detector_does_not_read_line_text() -> None:- """守卫段落标题候选、打分和邻行扩展不读取文本内容。"""-- source = "\n".join(- inspect.getsource(function)- for function in (- pdf_extractor._classify_page_titles,- pdf_extractor._infer_lane_body_profile,- pdf_extractor._classify_document_title,- pdf_extractor._document_title_uses_page_fallback,- pdf_extractor._classify_paragraph_titles_in_lane,- pdf_extractor._visual_row_has_body_style_sibling,- pdf_extractor._is_near_full_mixed_inline_row,- pdf_extractor._is_full_width_inline_heading,- pdf_extractor._has_following_body_row,- pdf_extractor._unify_visual_row_title_types,- pdf_extractor._protect_front_matter_title_types,- pdf_extractor._infer_front_matter_boundary,- pdf_extractor._normalized_title_gap,- pdf_extractor._line_near_visual_container,- pdf_extractor._title_fonts_compatible,- pdf_extractor._expand_paragraph_title_neighbors,- )- )-- assert ".text" not in source--- "block_type",- [- "doc_title",- "paragraph_title",- "header",- "footer",- "page_number",- "page_footnote",- "aside_text",- "equation",- ],-)-def test_output_normalization_preserves_new_flash_types(block_type: str) -> None:- """验证 Flash 文本语义类型和公式类型不会在归一化阶段退回 text。"""-- block = pdf_extractor._normalize_output_block(- {"type": block_type, "bbox": (10.0, 20.0, 40.0, 50.0), "angle": 0, "content": "value"},- (100.0, 100.0),- )-- assert block is not None- assert block["type"] == block_type---def test_hanging_indent_groups_neutral_entries_and_ignores_centered_heading() -> None:- """验证不含序号的重复悬挂缩进逐条分组,且居中标题不参与条目。"""-- body_font = ("Body", 0)- italic_font = ("BodyItalic", 1)- lines = [- _text_line(- "Centered heading",- (35.0, 0.0, 85.0, 10.0),- 0,- font_signature=("Heading", 0),- font_coverage=1.0,- ),- _text_line("Alpha begins", (0.0, 20.0, 100.0, 30.0), 1, font_signature=body_font, font_coverage=1.0),- _text_line(- "alpha italic continuation",- (15.0, 30.0, 100.0, 40.0),- 2,- font_signature=italic_font,- font_coverage=1.0,- ),- _text_line("alpha closes", (15.0, 40.0, 70.0, 50.0), 3, font_signature=body_font, font_coverage=1.0),- _text_line("Beta begins", (0.0, 50.0, 100.0, 60.0), 4, font_signature=body_font, font_coverage=1.0),- _text_line("beta continues", (15.0, 60.0, 100.0, 70.0), 5, font_signature=body_font, font_coverage=1.0),- _text_line("Gamma begins", (0.0, 70.0, 100.0, 80.0), 6, font_signature=body_font, font_coverage=1.0),- _text_line("gamma continues", (15.0, 80.0, 100.0, 90.0), 7, font_signature=body_font, font_coverage=1.0),- ]- lane = pdf_extractor._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lines],- )-- group_map = pdf_extractor._build_hanging_indent_group_map(lane, [], [])- blocks = pdf_extractor._build_text_blocks(lines, [], (120.0, 120.0))-- assert 0 not in group_map- assert [group_map[index] for index in range(1, 8)] == [0, 0, 0, 1, 1, 2, 2]- assert [block["content"] for block in blocks] == [- "Centered heading",- "Alpha begins alpha italic continuation alpha closes",- "Beta begins beta continues",- "Gamma begins gamma continues",- ]---def test_hanging_indent_accepts_reference_spacing_and_italic_tail() -> None:- """验证 1.25 倍行高的参考文献间距不会拆掉前一条斜体尾行。"""-- body_font = ("Body", 0)- lines = [- _text_line(- "Alpha begins",- (0.0, 0.0, 100.0, 10.0),- 0,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "alpha continues",- (15.0, 10.0, 100.0, 20.0),- 1,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "alpha italic tail",- (15.0, 20.0, 75.0, 30.0),- 2,- font_signature=("BodyItalic", 1),- font_coverage=1.0,- ),- _text_line(- "Beta begins",- (0.0, 42.5, 100.0, 52.5),- 3,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "beta continues",- (15.0, 52.5, 100.0, 62.5),- 4,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "Gamma begins",- (0.0, 75.0, 100.0, 85.0),- 5,- font_signature=body_font,- font_coverage=1.0,- ),- _text_line(- "gamma continues",- (15.0, 85.0, 100.0, 95.0),- 6,- font_signature=body_font,- font_coverage=1.0,- ),- ]- lane = pdf_extractor._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lines],- )-- group_map = pdf_extractor._build_hanging_indent_group_map(lane, [], [])- blocks = pdf_extractor._build_text_blocks(lines, [], (120.0, 120.0))-- assert [group_map[index] for index in range(7)] == [0, 0, 0, 1, 1, 2, 2]- assert [block["content"] for block in blocks] == [- "Alpha begins alpha continues alpha italic tail",- "Beta begins beta continues",- "Gamma begins gamma continues",- ]---def test_first_line_indent_and_large_gap_do_not_form_hanging_indent_groups() -> None:- """验证普通首行缩进及跨越大间距的行不会误触发悬挂缩进模式。"""-- lines = [- _text_line("First paragraph", (15.0, 0.0, 100.0, 10.0), 0),- _text_line("first continuation", (0.0, 10.0, 100.0, 20.0), 1),- _text_line("Second paragraph", (15.0, 20.0, 100.0, 30.0), 2),- _text_line("second continuation", (0.0, 30.0, 100.0, 40.0), 3),- _text_line("Detached start", (0.0, 70.0, 100.0, 80.0), 4),- _text_line("detached continuation", (15.0, 80.0, 100.0, 90.0), 5),- ]- lane = pdf_extractor._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lines],- )-- assert pdf_extractor._build_hanging_indent_group_map(lane, [], []) == {}---def test_twelve_point_gutter_keeps_two_text_lanes_and_paragraphs_separate() -> None:- """验证约 12pt 行高和栏沟仍识别为双栏,左右正文不会交叉拼接。"""-- lines: list[pdf_extractor._LineItem] = []- for row_index, top in enumerate((100.0, 112.0, 124.0)):- lines.extend(- [- _text_line(f"left-{row_index}", (49.0, top, 300.0, top + 12.0), row_index * 2),- _text_line(f"right-{row_index}", (312.0, top, 563.0, top + 12.0), row_index * 2 + 1),- ]- )-- lanes = pdf_extractor._infer_text_lanes(- [(line, line.bbox) for line in lines],- 612.0,- 12.0,- )- blocks = pdf_extractor._build_text_blocks(lines, [], (612.0, 792.0))-- regular_lanes = [lane for lane in lanes if not lane.is_span]- assert [(lane.left, lane.right) for lane in regular_lanes] == [- (49.0, 300.0),- (312.0, 563.0),- ]- assert len(blocks) == 2- assert all("right-" not in block["content"] for block in blocks if "left-" in block["content"])- assert all("left-" not in block["content"] for block in blocks if "right-" in block["content"])---def test_cross_column_caption_tail_stays_in_span_lane_and_one_text_block() -> None:- """验证仅占单栏宽的短 caption 尾行仍回收到连续跨栏 caption。"""-- lines: list[pdf_extractor._LineItem] = [- _text_line("caption line one", (0.0, 10.0, 200.0, 20.0), 0),- _text_line("caption line two", (0.0, 22.0, 200.0, 32.0), 1),- _text_line("caption tail", (0.0, 34.0, 70.0, 44.0), 2),- _text_line("ordinary left short line", (0.0, 70.0, 70.0, 80.0), 3),- ]- for row_index, top in enumerate((100.0, 112.0, 124.0, 136.0, 148.0)):- lines.extend(- [- _text_line(- f"left body {row_index}",- (0.0, top, 90.0, top + 10.0),- 4 + 2 * row_index,- ),- _text_line(- f"right body {row_index}",- (110.0, top, 200.0, top + 10.0),- 5 + 2 * row_index,- ),- ]- )-- lanes = pdf_extractor._infer_text_lanes(- [(line, line.bbox) for line in lines],- 200.0,- 10.0,- )- blocks = pdf_extractor._build_text_blocks(lines, [], (200.0, 180.0))-- span_lane = next(lane for lane in lanes if lane.is_span)- assert {line.source_index for line, _bbox in span_lane.lines} == {0, 1, 2}- assert all(line.source_index != 3 for line, _bbox in span_lane.lines)- caption_blocks = [block for block in blocks if "caption line one" in block["content"]]- assert len(caption_blocks) == 1- assert "caption tail" in caption_blocks[0]["content"]---def test_slight_bbox_overlap_contributes_to_gap_estimate_and_separates_caption() -> None:- """验证轻微纵向重叠按零净空统计,短图例不会与后续长 caption 合并。"""-- body_lines = [- _text_line("body-0", (312.0, 0.0, 563.0, 12.0), 0),- _text_line("body-1", (312.0, 11.95, 563.0, 23.95), 1),- _text_line("body-2", (312.0, 23.9, 563.0, 35.9), 2),- ]- legend = _text_line("Right camera", (458.0, 60.0, 509.0, 72.0), 3)- caption = _text_line(- "Figure 1: a long caption spanning the full column",- (312.0, 79.0, 563.0, 91.0),- 4,- )- lane = pdf_extractor._TextLane(- left=312.0,- right=563.0,- lines=[*((line, line.bbox) for line in body_lines), (legend, legend.bbox), (caption, caption.bbox)],- )-- regular_gap, gap_mad = pdf_extractor._estimate_lane_gap(lane)-- assert (regular_gap, gap_mad) == (0.0, 0.0)- assert not pdf_extractor._should_connect_text_rows(- (legend, legend.bbox),- (caption, caption.bbox),- lane,- regular_gap,- gap_mad,- [],- [],- )---def test_local_previous_left_edge_exposes_first_line_indent() -> None:- """验证局部版心左移后仍能识别下一行相对前一物理行的首行缩进。"""-- previous = _text_line(- "previous paragraph without punctuation",- (0.0, 0.0, 80.0, 10.0),- 0,- )- current = _text_line(- "Indented new paragraph",- (10.0, 12.0, 100.0, 22.0),- 1,- )- lane = pdf_extractor._TextLane(- left=20.0,- right=100.0,- lines=[(previous, previous.bbox), (current, current.bbox)],- )-- assert not pdf_extractor._should_connect_text_rows(- (previous, previous.bbox),- (current, current.bbox),- lane,- 2.0,- 0.0,- [],- [],- )---def test_terminal_full_lane_row_breaks_after_abnormal_clearance() -> None:- """验证满栏句末行后的净空超过常规间距半行高时强制另起段落。"""-- previous = _text_line("Figure caption ends.", (0.0, 0.0, 100.0, 10.0), 0)- current = _text_line("new paragraph fills the lane", (0.0, 17.0, 100.0, 27.0), 1)- lane = pdf_extractor._TextLane(- left=0.0,- right=100.0,- lines=[(previous, previous.bbox), (current, current.bbox)],- )-- assert not pdf_extractor._should_connect_text_rows(- (previous, previous.bbox),- (current, current.bbox),- lane,- 1.0,- 0.0,- [],- [],- )---def test_effective_height_connects_body_line_after_tall_math_glyph() -> None:- """验证高数学字形拉长原始 bbox 时仍按有效行高连接下一正文行。"""-- previous = _text_line(- "support window Ωp centered at the pixel",- (312.0, 100.0, 563.0, 118.82),- 0,- effective_height=12.0,- )- current = _text_line(- "by",- (312.0, 112.0, 325.0, 124.0),- 1,- effective_height=12.0,- )- lane = pdf_extractor._TextLane(- left=312.0,- right=563.0,- lines=[(previous, previous.bbox), (current, current.bbox)],- )-- assert current.bbox[1] - previous.bbox[3] == pytest.approx(-6.82)- assert pdf_extractor._effective_text_row_gap(- (previous, previous.bbox),- (current, current.bbox),- ) == pytest.approx(0.0)- assert pdf_extractor._should_connect_text_rows(- (previous, previous.bbox),- (current, current.bbox),- lane,- 0.0,- 0.0,- [],- [],- )---def test_inline_scripts_and_touching_low_coverage_runs_are_recovered() -> None:- """验证紧贴上下标与低覆盖率同行后缀恢复,同时保留外置公式编号。"""-- script_lines = [- _text_line("O(ω", (0.0, 0.0, 100.0, 18.8), 0, visual_row_id=0, effective_height=12.0),- _text_line("2", (100.3, 0.8, 104.0, 7.0), 1, visual_row_id=1, effective_height=6.0),- _text_line("Di", (0.0, 40.0, 100.0, 52.0), 2, visual_row_id=2, effective_height=12.0),- _text_line("p", (96.9, 46.0, 101.0, 53.0), 3, visual_row_id=3, effective_height=7.0),- ]-- merged_scripts = pdf_extractor._merge_native_inline_scripts(script_lines, (200.0, 100.0))-- assert [line.text for line in merged_scripts] == ["O(ω2", "Dip"]-- caption_prefix = _text_line(- "(4",- (0.0, 70.0, 12.0, 82.0),- 4,- font_signature=("Body", 0),- font_coverage=1.0,- )- caption_suffix = _text_line(- "th row).",- (12.1, 70.0, 50.0, 82.0),- 5,- font_signature=("Body", 0),- font_coverage=0.7,- )- formula_body = _text_line(- "formula",- (0.0, 90.0, 50.0, 102.0),- 6,- font_signature=("Math", 0),- font_coverage=1.0,- )- formula_number = _text_line(- "(4)",- (51.2, 90.0, 60.0, 102.0),- 7,- font_signature=("Body", 0),- font_coverage=1.0,- )-- assert pdf_extractor._can_merge_same_baseline_pair(- caption_prefix,- caption_prefix.bbox,- caption_suffix,- caption_suffix.bbox,- [],- )- assert not pdf_extractor._can_merge_same_baseline_pair(- formula_body,- formula_body.bbox,- formula_number,- formula_number.bbox,- [],- )---def test_full_lane_large_height_mismatch_only_recovers_aligned_continuation() -> None:- """验证满栏混合字体 URL 可续接,而短公式与显式字体样式边界仍分离。"""-- previous = _text_line(- "video sequences have been made avail-",- (0.0, 0.0, 100.0, 12.0),- 0,- effective_height=12.0,- font_signature=("Body", 0),- font_coverage=1.0,- )- full_width_url = _text_line(- "able at http://example.test/data",- (0.0, 12.0, 100.0, 24.0),- 1,- effective_height=7.69,- font_signature=("Mono", 0),- font_coverage=1.0,- )- short_formula = _text_line(- "x = 1",- (0.0, 12.0, 60.0, 24.0),- 2,- effective_height=7.69,- font_signature=("Math", 0),- font_coverage=1.0,- )- styled_reference = _text_line(- "italic bibliography continuation",- (0.0, 12.0, 100.0, 24.0),- 3,- effective_height=7.69,- font_signature=("BodyItalic", 1),- font_coverage=1.0,- )- lane = pdf_extractor._TextLane(left=0.0, right=100.0)-- assert pdf_extractor._should_connect_text_rows(- (previous, previous.bbox),- (full_width_url, full_width_url.bbox),- lane,- 0.0,- 0.0,- [],- [],- )- assert not pdf_extractor._should_connect_text_rows(- (previous, previous.bbox),- (short_formula, short_formula.bbox),- lane,- 0.0,- 0.0,- [],- [],- )- assert not pdf_extractor._should_connect_text_rows(- (previous, previous.bbox),- (styled_reference, styled_reference.bbox),- lane,- 0.0,- 0.0,- [],- [],- )---def test_smaller_footnote_after_abnormal_gap_forces_text_block_break() -> None:- """验证字号不足前行 88% 且净空偏大时,正文与脚注强制分块。"""-- body = _text_line(- "body continuation",- (0.0, 0.0, 100.0, 10.0),- 0,- effective_height=10.0,- font_signature=("Body", 0),- font_coverage=1.0,- )- footnote = _text_line(- "small footnote",- (0.0, 16.0, 100.0, 24.7),- 1,- effective_height=8.7,- font_signature=("Body", 0),- font_coverage=1.0,- )- lane = pdf_extractor._TextLane(- left=0.0,- right=100.0,- lines=[(body, body.bbox), (footnote, footnote.bbox)],- )-- assert not pdf_extractor._should_connect_text_rows(- (body, body.bbox),- (footnote, footnote.bbox),- lane,- 3.0,- 0.0,- [],- [],- )---def test_detached_formula_anchor_collects_multiline_formula_but_not_body_prefix() -> None:- """验证低位右缘锚点上溯多行公式,并排除左对齐正文与靠右句点。"""-- body_font = ("Body", 0)- body_lines = [- _text_line(- f"body-{index}",- (0.0, top, 100.0, top + 10.0),- index,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- for index, top in enumerate((0.0, 12.0, 24.0))- ]- body_prefix = _text_line(- "regular prose before formula",- (0.0, 60.0, 60.0, 70.0),- 3,- effective_height=10.0,- font_signature=body_font,- font_coverage=1.0,- )- formula_lines = [- _text_line("numerator", (20.0, 42.0, 50.0, 52.0), 4, effective_height=10.0),- _text_line("Fp =", (15.0, 52.0, 45.0, 62.0), 5, effective_height=10.0),- _text_line("otherwise", (20.0, 65.0, 65.0, 75.0), 6, effective_height=10.0),- _text_line("0,", (68.0, 72.0, 78.0, 82.0), 7, effective_height=10.0),- ]- punctuation = _text_line(".", (93.0, 45.0, 96.0, 55.0), 8, effective_height=10.0)- number = _text_line("(7)", (91.0, 75.0, 100.0, 85.0), 9, effective_height=10.0)- lane_lines = [*body_lines, body_prefix, *formula_lines, punctuation, number]- lane = pdf_extractor._TextLane(- left=0.0,- right=100.0,- lines=[(line, line.bbox) for line in lane_lines],- )-- anchors = pdf_extractor._find_formula_spatial_anchors(lane, 10.0)-- assert len(anchors) == 1- assert anchors[0].line is number- assert anchors[0].detached_below_body-- anchor_center = pdf_extractor._bbox_center_y(anchors[0].bbox)- dominant_font = pdf_extractor._infer_formula_body_font(lane, 10.0)- members = pdf_extractor._grow_formula_spatial_component(- lane,- anchors[0],- anchor_center - 4.75 * 10.0,- anchor_center + 2.25 * 10.0,- set(),- [],- dominant_font,- 10.0,- )- member_texts = {line.text for line, _bbox in members}-- assert member_texts == {"numerator", "Fp =", "otherwise", "0,", "(7)"}- assert body_prefix.text not in member_texts- assert punctuation.text not in member_texts---def _drawing_axis_line(- orientation: str,- bbox: tuple[float, float, float, float],-) -> pdf_extractor._AxisLine:- """构造图形容器测试使用的 PDF 绘图线。"""-- return pdf_extractor._AxisLine(- bbox=bbox,- width=0.5,- orientation=orientation, # type: ignore[arg-type]- )---def _graphic_source_fixture() -> pdf_extractor._PageSource:- """构造双框图形、六个标签、拆分 caption 与邻近正文。"""-- lines = [- _text_line("p = (x, y)", (378.0, 302.0, 421.0, 312.0), 0, visual_row_id=10),- _text_line("pbar = (xbar, y)", (445.0, 302.0, 488.0, 312.0), 1, visual_row_id=10),- _text_line("dp", (382.0, 282.0, 403.0, 292.0), 2, visual_row_id=11),- _text_line("x", (468.0, 282.0, 475.0, 292.0), 3, visual_row_id=11),- _text_line("Left camera", (360.0, 339.0, 411.0, 350.0), 4, visual_row_id=12),- _text_line("Right camera", (458.0, 339.0, 509.0, 350.0), 5, visual_row_id=12),- _text_line(- "Figure 1: a deliberately long caption that must remain",- (312.0, 359.0, 500.0, 371.0),- 6,- visual_row_id=20,- split_from_row=True,- ),- _text_line(- "independent.",- (510.0, 359.0, 563.0, 371.0),- 7,- visual_row_id=20,- split_from_row=True,- ),- _text_line("Nearby prose", (370.0, 225.0, 430.0, 237.0), 8, visual_row_id=9),- ]- drawing_lines = [- _drawing_axis_line("horizontal", (348.0, 272.0, 430.0, 272.5)),- _drawing_axis_line("horizontal", (348.0, 331.5, 430.0, 332.0)),- _drawing_axis_line("vertical", (348.0, 272.0, 348.5, 332.0)),- _drawing_axis_line("vertical", (429.5, 272.0, 430.0, 332.0)),- _drawing_axis_line("horizontal", (436.0, 272.0, 526.0, 272.5)),- _drawing_axis_line("horizontal", (436.0, 331.5, 526.0, 332.0)),- _drawing_axis_line("vertical", (436.0, 272.0, 436.5, 332.0)),- _drawing_axis_line("vertical", (525.5, 272.0, 526.0, 332.0)),- ]- return pdf_extractor._PageSource(- page_size=(612.0, 792.0),- lines=lines,- chars=[],- drawing_lines=drawing_lines,- )---def test_double_box_graphic_claims_six_labels_but_not_caption_or_body() -> None:- """验证双框图形整行聚合六个标签,拆分 caption 和邻近正文均不被部分认领。"""-- blocks, claimed = pdf_extractor._build_graphic_like_blocks(- _graphic_source_fixture(),- [],- set(),- )-- assert len(blocks) == 1- assert claimed == set(range(6))- assert blocks[0]["type"] == "image"- for expected_text in ("dp", "x", "p = (x, y)", "pbar = (xbar, y)", "Left camera", "Right camera"):- assert expected_text in blocks[0]["content"]- assert blocks[0]["content"].count("Left camera") == 1- assert blocks[0]["content"].count("Right camera") == 1- assert "Figure 1" not in blocks[0]["content"]- assert "Nearby prose" not in blocks[0]["content"]---def test_materialized_table_bbox_has_priority_over_graphic_candidate() -> None:- """验证绘图组件与成功表格框重叠时跳过图形容器并保留全部文本身份。"""-- blocks, claimed = pdf_extractor._build_graphic_like_blocks(- _graphic_source_fixture(),- [(340.0, 265.0, 535.0, 355.0)],- set(),- )-- assert blocks == []- assert claimed == set()---def test_form_image_claims_internal_text_and_small_table_but_not_caption() -> None:- """验证有效 Form 吞并图内文字与小表候选,外部 caption 仍保留。"""-- form_bbox = (10.0, 10.0, 90.0, 65.0)- source = pdf_extractor._PageSource(- page_size=(100.0, 100.0),- lines=[- _text_line("inside row one", (15.0, 20.0, 70.0, 30.0), 0, visual_row_id=1),- _text_line("inside row two", (15.0, 35.0, 80.0, 45.0), 1, visual_row_id=2),- _text_line("Figure 1: outside", (10.0, 70.0, 80.0, 80.0), 2, visual_row_id=3),- ],- chars=[],- drawing_lines=[- _drawing_axis_line("horizontal", (20.0, 15.0, 80.0, 15.5)),- _drawing_axis_line("horizontal", (20.0, 55.0, 80.0, 55.5)),- _drawing_axis_line("vertical", (20.0, 15.0, 20.5, 55.0)),- _drawing_axis_line("vertical", (79.5, 15.0, 80.0, 55.0)),- ],- form_bboxes=[form_bbox],- )-- selected = pdf_extractor._select_form_image_bboxes(source)- blocks, claimed = pdf_extractor._build_form_image_blocks(source, selected, set())-- assert selected == [form_bbox]- assert pdf_extractor._form_supersedes_nested_bbox(- form_bbox,- (20.0, 20.0, 40.0, 35.0),- )- assert not pdf_extractor._form_supersedes_nested_bbox(- form_bbox,- (15.0, 15.0, 85.0, 60.0),- )- assert claimed == {0, 1}- assert blocks == [- {- "type": "image",- "bbox": form_bbox,- "angle": 0,- "content": "inside row one\ninside row two",- }- ]---def test_raster_images_filter_small_objects_avoid_containers_and_claim_text_once() -> None:- """验证点阵图过滤、容器优先、空 content 和重叠对象的唯一文本归属。"""-- source = pdf_extractor._PageSource(- page_size=(100.0, 100.0),- lines=[- _text_line("inside", (25.0, 25.0, 35.0, 35.0), 0, visual_row_id=1),- _text_line("outside caption", (10.0, 52.0, 50.0, 60.0), 1, visual_row_id=2),- _text_line("covered container text", (20.0, 70.0, 40.0, 80.0), 2, visual_row_id=3),- ],- chars=[],- drawing_lines=[],- image_bboxes=[- (10.0, 10.0, 50.0, 50.0),- (20.0, 20.0, 40.0, 40.0),- (60.0, 10.0, 90.0, 40.0),- (0.0, 90.0, 10.0, 94.0),- (10.0, 60.0, 50.0, 90.0),- ],- )-- blocks, claimed = pdf_extractor._build_raster_image_blocks(- source,- [{"type": "table", "bbox": (10.0, 60.0, 50.0, 90.0), "angle": 0, "content": "table"}],- set(),- )-- assert len(blocks) == 3- assert all(block["type"] == "image" and block["angle"] == 0 for block in blocks)- assert [block["bbox"] for block in blocks] == [- (10.0, 10.0, 50.0, 50.0),- (60.0, 10.0, 90.0, 40.0),- (20.0, 20.0, 40.0, 40.0),- ]- assert [block["content"] for block in blocks] == ["", "", "inside"]- assert claimed == {0}---def test_raster_image_content_is_removed_from_text_and_empty_image_page_is_kept() -> None:- """验证图内文本只进入 image,caption 保持 text,纯图片页仍输出空 content。"""-- source = pdf_extractor._PageSource(- page_size=(100.0, 100.0),- lines=[- _text_line("inside row one", (20.0, 20.0, 50.0, 30.0), 0, visual_row_id=1),- _text_line("inside row two", (20.0, 35.0, 50.0, 45.0), 1, visual_row_id=2),- _text_line("Figure 1: outside caption", (10.0, 70.0, 80.0, 80.0), 2, visual_row_id=3),- ],- chars=[],- drawing_lines=[],- image_bboxes=[(10.0, 10.0, 60.0, 60.0)],- )-- blocks = pdf_extractor._analyze_page_source(source)- image_block = next(block for block in blocks if block["type"] == "image")- text_block = next(block for block in blocks if block["type"] == "text")-- assert image_block["content"] == "inside row one\ninside row two"- assert text_block["content"] == "Figure 1: outside caption"- assert sum("inside row" in block["content"] for block in blocks) == 1-- empty_page_blocks = pdf_extractor._analyze_page_source(- pdf_extractor._PageSource(- page_size=(100.0, 100.0),- lines=[],- chars=[],- drawing_lines=[],- image_bboxes=[(10.0, 10.0, 60.0, 60.0)],- )- )- assert empty_page_blocks == [- {- "type": "image",- "bbox": [0.1, 0.1, 0.6, 0.6],- "angle": 0,- "content": "",- }- ]---def _native_model_list(pdf_name: str) -> list[list[dict[str, Any]]]:- """运行仓库内数字 PDF 样例并返回 Flash 原生模型输出。"""-- pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / pdf_name- with pdf_extractor.PDFDocument(str(pdf_path)) as pdf_doc:- return pdf_extractor._analyze_native_document(pdf_doc)---def _native_table_counts(pdf_name: str) -> list[int]:- """返回仓库内数字 PDF 样例的逐页表格块数量。"""-- return [sum(block["type"] == "table" for block in page) for page in _native_model_list(pdf_name)]---def _native_page_source(pdf_name: str, page_idx: int) -> pdf_extractor._PageSource:- """读取指定样例页并构造候选检测与认领测试使用的页面源。"""-- pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / pdf_name- with pdf_extractor.PDFDocument(str(pdf_path)) as pdf_doc:- page_size = pdf_doc.page_size(page_idx)- chars = pdf_doc.get_page_chars(page_idx)- lines = pdf_extractor._build_native_line_items(- pdf_extractor.get_lines_from_chars(chars),- page_size,- page_rotation=pdf_doc.page_rotation(page_idx),- )- return pdf_extractor._PageSource(- page_size=page_size,- lines=lines,- chars=chars,- drawing_lines=pdf_extractor._get_pdf_drawing_lines(pdf_doc, page_idx),- image_bboxes=pdf_doc.get_page_image_bboxes(page_idx),- form_bboxes=pdf_doc.get_page_form_bboxes(page_idx),- )---def _normalized_content_probe(text: str) -> str:- """去除空白、标点与 dash 差异,生成原生行内容覆盖检查使用的探针。"""-- return "".join(char.casefold() for char in text if char.isalnum())---def test_demo1_keeps_five_real_tables_without_formula_false_positive() -> None:- """验证 demo1 首页脚注、参考文献、公式与五个真实表格均保持正确。"""-- model_list = _native_model_list("demo1.pdf")-- assert [len(page) for page in model_list] == [16, 9, 12, 18, 10, 9, 11, 8, 10, 7, 10, 26, 9]- assert [sum(block["type"] == "table" for block in page) for page in model_list] == [- 0,- 0,- 0,- 0,- 1,- 2,- 0,- 1,- 1,- 0,- 0,- 0,- 0,- ]- assert sum(block["type"] == "doc_title" for page in model_list for block in page) == 1- assert sum(block["type"] == "header" for page in model_list for block in page) == 12- assert sum(block["type"] == "page_number" for page in model_list for block in page) == 12- assert sum(block["type"] == "equation" for page in model_list for block in page) == 7- page1_footnotes = [block for block in model_list[0] if block["type"] == "page_footnote"]- assert len(page1_footnotes) == 1- assert page1_footnotes[0]["content"].startswith("* Corresponding author.")- copyright_block = next(- block for block in model_list[0] if block["content"].startswith("0022-1694/$")- )- assert copyright_block["type"] == "text"- assert "doi:10.1016/j.jhydrol.2005.01.006" in copyright_block["content"]- assert next(block for block in model_list[0] if block["content"] == "Abstract")["type"] == "paragraph_title"- assert next(block for block in model_list[6] if block["content"].startswith("4.2."))["type"] == "paragraph_title"---def test_demo1_rotated_table_claims_all_206_lines_without_residual_text() -> None:- """验证 demo1 第五页旋转表完整认领 206 行且表框内没有残留文本。"""-- source = _native_page_source("demo1.pdf", 4)- candidates = pdf_extractor._detect_table_candidates(source)- blocks, claimed = pdf_extractor._materialize_table_blocks(source, candidates)- rotated_indices = {line.source_index for line in source.lines if line.angle == 270}-- assert len(blocks) == 1- assert len(rotated_indices) == 206- assert claimed == rotated_indices- assert not [- line- for line in source.lines- if line.angle == 270- and line.source_index not in claimed- and any(- candidate.angle == 270- and pdf_extractor._point_in_bbox(- (pdf_extractor._bbox_center_x(line.bbox), pdf_extractor._bbox_center_y(line.bbox)),- candidate.bbox,- )- for candidate in candidates- )- ]---def test_demo2_rejects_figure_grid_and_keeps_two_real_tables() -> None:- """验证 demo2 曲线图被拒绝且第四、五页真实表格保留。"""-- assert _native_table_counts("demo2.pdf") == [0, 0, 0, 1, 1, 0]---def test_demo2_page1_forms_sixteen_blocks_and_keeps_figure_caption_separate() -> None:- """验证 demo2 首页正文自然聚合,六个 Figure 1 标签单块且 caption 独立。"""-- page = _native_model_list("demo2.pdf")[0]- graphic_block = next(block for block in page if "Left camera" in block["content"])- caption_block = next(block for block in page if "Figure 1:" in block["content"])-- assert len(page) == 16- assert not [block for block in page if block["type"] == "table"]- assert next(block for block in page if block["content"].startswith("Real-time Temporal"))["type"] == "doc_title"- assert next(block for block in page if block["content"] == "I. INTRODUCTION")["type"] == "paragraph_title"- for expected_text in ("dp", "¯x", "p =", "¯p =", "Left camera", "Right camera"):- assert expected_text in graphic_block["content"]- assert graphic_block is not caption_block- assert "Figure 1:" not in graphic_block["content"]- assert "Left camera" not in caption_block["content"]- assert sum(block["content"].count("Left camera") for block in page) == 1---def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> None:- """验证 demo2 后续页达到目标块数,正文、公式、caption 与双栏顺序均稳定。"""-- model_list = _native_model_list("demo2.pdf")-- assert [len(page) for page in model_list] == [16, 16, 21, 13, 16, 16]- assert [sum(block["type"] == "image" for block in page) for page in model_list] == [1, 0, 0, 5, 2, 0]- assert [sum(block["type"] == "table" for block in page) for page in model_list] == [0, 0, 0, 1, 1, 0]- assert sum(block["type"] == "equation" for page in model_list for block in page) == 9-- page2 = model_list[1]- page2_contents = [block["content"] for block in page2]- humans = next(content for content in page2_contents if content.startswith("Humans group shapes"))- matching = next(content for content in page2_contents if content.startswith("To identify a match"))- dissimilarity = next(content for content in page2_contents if content.startswith("where the pixel dissimilarity"))- formula3 = next(content for content in page2_contents if content.endswith("(3)"))- assert not [content for content in page2_contents if content.strip() == "by"]- assert humans.endswith("is given by")- assert "Sp denotes a set of matching candidates" in matching- assert "green, and blue components given by" in dissimilarity- assert "green, and blue" not in formula3-- page3 = model_list[2]- page3_contents = [block["content"] for block in page3]- assert page3_contents[12] == "D. Iterative Disparity Refinement"- assert all(block["bbox"][2] <= 0.5 for block in page3[:12])- assert "O(ω2) to O(ω)" in page3_contents[0]- assert "disparity estimates Dip" in page3_contents[13]- for formula_number in range(4, 10):- marker = f"({formula_number})"- assert sum(marker in content for content in page3_contents) == 1- formula7 = next(content for content in page3_contents if "(7)" in content)- formula4 = next(content for content in page3_contents if "(4)" in content)- formula8 = next(content for content in page3_contents if "(8)" in content)- assert formula4.splitlines()[-1] == "(4)"- assert formula8.splitlines()[-1] == "(8)"- assert "(4)" not in "\n".join(formula4.splitlines()[:-1])- assert "(8)" not in "\n".join(formula8.splitlines()[:-1])- assert "Fp =" in formula7- assert "otherwise" in formula7- assert not [content for content in page3_contents if content.strip() in {"2", "p", "otherwise", "(7)"}]- assert "available at http://mc2.unl.edu/current-research" in page3_contents[-1]- assert "/image-processing/. Figure 2" in page3_contents[-1]-- page4_contents = [block["content"] for block in model_list[3]]- figure2 = next(content for content in page4_contents if content.startswith("Figure 2:"))- figure3 = next(content for content in page4_contents if content.startswith("Figure 3:"))- results = next(content for content in page4_contents if content.startswith("The results of temporal stereo"))- improvements = next(content for content in page4_contents if content.startswith("Significant improvements"))- assert figure2.endswith("(4th row).")- assert figure3.endswith("without temporal aggregation.")- assert results.endswith("methods that operate on pairs of images.")- assert improvements.endswith("has the effect")-- page5_contents = [block["content"] for block in model_list[4]]- optimal_feedback = next(content for content in page5_contents if content.startswith("The optimal value"))- page5_references = [content for content in page5_contents if content.startswith("[")]- assert "noise ranging between ±0 to ±40" in optimal_feedback- assert optimal_feedback.endswith("temporal stereo matching is used.")- assert [content.partition("]")[0] + "]" for content in page5_references] == [- f"[{number}]" for number in range(1, 6)- ]-- page6_contents = [block["content"] for block in model_list[5]]- assert len(page6_contents) == 16- assert [content.partition("]")[0] + "]" for content in page6_contents] == [- f"[{number}]" for number in range(6, 22)- ]---def test_demo2_container_claims_are_pairwise_disjoint() -> None:- """验证表格、图形和公式阶段按 source_index 唯一认领,不重复消费文本身份。"""-- for page_idx in (1, 2, 3):- source = _native_page_source("demo2.pdf", page_idx)- table_candidates = pdf_extractor._detect_table_candidates(source)- table_blocks, table_claimed = pdf_extractor._materialize_table_blocks(source, table_candidates)- table_bboxes = [block["bbox"] for block in table_blocks]- _graphic_blocks, graphic_claimed = pdf_extractor._build_graphic_like_blocks(- source,- table_bboxes,- table_claimed,- )- remaining = pdf_extractor._merge_same_baseline_text_lines(- [- line- for line in source.lines- if line.source_index not in table_claimed | graphic_claimed- ],- source.page_size,- table_bboxes,- )- formula_input_indices = {line.source_index for line in remaining}- _formula_blocks, formula_remaining = pdf_extractor._build_formula_like_blocks(- remaining,- table_bboxes,- source.page_size,- )- formula_claimed = formula_input_indices - {line.source_index for line in formula_remaining}-- assert table_claimed.isdisjoint(graphic_claimed)- assert table_claimed.isdisjoint(formula_claimed)- assert graphic_claimed.isdisjoint(formula_claimed)- combined = table_claimed | graphic_claimed | formula_claimed- assert len(combined) == len(table_claimed) + len(graphic_claimed) + len(formula_claimed)---def test_demo2_page4_groups_five_graphics_and_keeps_table1() -> None:- """验证 demo2 第四页五个图形区域分别聚合,Table 1 继续优先输出为 table。"""-- page = _native_model_list("demo2.pdf")[3]- table_blocks = [block for block in page if block["type"] == "table"]- graphic_markers = ("Frame 30", "Noise: ±0", "Noise: ±20", "Noise: ±40", "Noise ±")- graphic_blocks = [- next(block for block in page if block["type"] == "image" and marker in block["content"])- for marker in graphic_markers- ]-- assert len(table_blocks) == 1- assert "Table I:" in table_blocks[0]["content"]- assert len({id(block) for block in graphic_blocks}) == 5- assert "Frame 90" in graphic_blocks[0]["content"]- assert all("Figure" not in block["content"] for block in graphic_blocks)---def test_demo2_table_captions_and_numeric_footnotes_are_not_text_blocks() -> None:- """验证 demo2 两张表的换行标题和数字脚注全部并入表格投影。"""-- model_list = _native_model_list("demo2.pdf")- page4_table = next(block for block in model_list[3] if block["type"] == "table")- page5_table = next(block for block in model_list[4] if block["type"] == "table")- residual_text = "\n".join(- block["content"] for page_idx in (3, 4) for block in model_list[page_idx] if block["type"] == "text"- )-- assert "ral stereo matching." in page4_table["content"]- assert "1 To enable propagation of disparity information" in page4_table["content"]- assert "0.01, respectively." in page4_table["content"]- assert "Noise: ±20" not in page4_table["content"]- assert "1 Millions of Disparity Estimates per Second." in page5_table["content"]- assert "2 Assumes 320 × 240 images with 32 disparity levels." in page5_table["content"]- assert "the avgerage % of bad pixels." in page5_table["content"]- assert "ral stereo matching." not in residual_text- assert "Millions of Disparity Estimates per Second." not in residual_text---def test_demo3_keeps_tables_and_covers_every_native_source_line() -> None:- """验证 demo3 容器、后续页段落边界及每条原生 source line 均保持稳定。"""-- pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / "demo3.pdf"- with pdf_extractor.PDFDocument(str(pdf_path)) as pdf_doc:- model_list = pdf_extractor._analyze_native_document(pdf_doc)- source_lines_by_page: list[list[pdf_extractor._LineItem]] = []- for page_idx in range(pdf_doc.page_count):- page_size = pdf_doc.page_size(page_idx)- source_lines_by_page.append(- pdf_extractor._build_native_line_items(- pdf_extractor.get_lines_from_chars(pdf_doc.get_page_chars(page_idx)),- page_size,- page_rotation=pdf_doc.page_rotation(page_idx),- )- )-- assert [sum(block["type"] == "table" for block in page) for page in model_list] == [- 2,- 0,- 0,- 0,- 1,- 2,- 2,- 2,- 0,- 0,- ]- assert [len(page) for page in model_list] == [- 24,- 15,- 13,- 21,- 19,- 16,- 16,- 15,- 17,- 18,- ]- page7_tables = [block for block in model_list[6] if block["type"] == "table"]- page7_table4 = next(- block for block in page7_tables if "Number of parameters" in block["content"]- )- page7_table4_caption = next(- block- for block in model_list[6]- if block["content"] == "Table 4: Model size comparison."- )- page7_inline_body = next(- block- for block in model_list[6]- if block["content"].startswith("Row, Column, & Global Positional IDs.")- )- page9_conclusion = next(- block- for block in model_list[8]- if block["content"].startswith("In this paper, we identified")- )- page10_first_reference = next(- block- for block in model_list[9]- if block["content"].startswith("Xiang Deng, Huan Sun")- )- assert all(- marker in page7_table4["content"]- for marker in (- "Model",- "TAPASBASE",- "TABLEFORMERBASE",- "TAPASLARGE",- "TABLEFORMERLARGE",- )- )- assert page7_table4_caption["content"] not in page7_table4["content"]- assert page7_table4["bbox"][3] < page7_table4_caption["bbox"][1]- assert page7_inline_body["type"] == "text"- assert "With TAPASBASE" in page7_inline_body["content"]- assert "To tackle this" in page9_conclusion["content"]- assert "Acknowledgments" not in page9_conclusion["content"]- assert "Cong Yu. 2021. TURL:" in page10_first_reference["content"]- assert "Jacob Devlin" not in page10_first_reference["content"]- for page, source_lines in zip(model_list, source_lines_by_page, strict=True):- output_probe = _normalized_content_probe("".join(str(block.get("content") or "") for block in page))- missing_lines = [- line.text- for line in source_lines- if (line_probe := _normalized_content_probe(line.text)) and line_probe not in output_probe- ]- assert not missing_lines---def test_demo3_auxiliary_text_types_match_real_page_geometry() -> None:- """验证真实 PDF 的首页侧栏及第 1、5、6、9 页脚注命中,公式页不误报。"""-- model_list = _native_model_list("demo3.pdf")-- assert [sum(block["type"] == "aside_text" for block in page) for page in model_list] == [- 1,- 0,- 0,- 0,- 0,- 0,- 0,- 0,- 0,- 0,- ]- assert [sum(block["type"] == "page_footnote" for block in page) for page in model_list] == [- 2,- 0,- 0,- 0,- 2,- 1,- 0,- 0,- 1,- 0,- ]- assert not [- block- for block in model_list[6]- if block["type"] in {"aside_text", "page_footnote"}- ]---def test_demo3_pages1_and2_fix_title_front_matter_and_embedding_formula() -> None:- """验证首页标题稳定,第二页标题、公式和栏尾正文各自保持完整。"""-- page1, page2 = _native_model_list("demo3.pdf")[:2]- title = next(block for block in page1 if block["content"].startswith("TABLEFORMER:"))- front_matter_contents = {- "∗",- "Aditya Gupta† Rahul Goel†",- "Jingfeng Yang Luheng He†",- "Shyam Upadhyay† Shachi Paul †",- "?Georgia Institute of Technology",- "†Google Assistant",- }- front_matter = [- block for block in page1 if block["content"] in front_matter_contents- ]- released_code = next(- block for block in page1 if "TABLEFORMER.md" in block["content"]- )- aside = next(block for block in page1 if block["type"] == "aside_text")- introduction = next(- block for block in page1 if block["content"].startswith("Recently, semi-structured")- )- nutshell = next(- block for block in page1 if block["content"].startswith("In a nutshell")- )- figure_caption = next(- block for block in page1 if block["content"].startswith("Figure 1:")- )- tables_body = next(- block for block in page1 if block["content"].startswith("tables or rows")- )-- assert title["type"] == "doc_title"- assert len(front_matter) == len(front_matter_contents)- assert all(block["type"] == "text" for block in front_matter)- assert next(block for block in page1 if block["content"] == "Abstract")["type"] == "paragraph_title"- assert released_code["type"] == "page_footnote"- assert aside["angle"] == 270- assert aside["bbox"][2] <= 0.12- assert introduction["content"].endswith("(Eisenschlos et al., 2021; Liu et al., 2021).")- assert nutshell["type"] == "text"- assert nutshell["content"].endswith("by serializing")- assert figure_caption["type"] == "text"- assert figure_caption["content"].endswith("both questions.")- assert "tables or rows" not in figure_caption["content"]- assert tables_body["type"] == "text"-- section_title = next(- block for block in page2 if block["content"].startswith("2 Preliminaries:")- )- equations = [block for block in page2 if block["type"] == "equation"]- assert section_title["type"] == "paragraph_title"- assert section_title["content"] == "2 Preliminaries: TAPAS for Table Encoding"- assert len(equations) == 1- assert equations[0]["content"].splitlines() == [- "token ids (W) = {wv1, wv2, · · · , wvn }",- "positional ids (B) = {b1, b2, · · · , bn}",- "segment ids (G) = {gseg1, gseg2, · · · , gsegn }",- "column ids (C) = {ccol1, ccol2, · · · , ccoln}",- "row ids (R) = {rrow1, rrow2, · · · , rrown }",- "rank ids (Z) = {zrank1, zrank2, · · · , zrankn}",- ]- as_model_blocks = [- block- for block in page2- if "As for the model" in block["content"]- or "attends to all the tokens." in block["content"]- or "Let the layer input" in block["content"]- ]- assert len(as_model_blocks) == 1- assert as_model_blocks[0]["type"] == "text"- assert as_model_blocks[0]["content"].startswith("As for the model")- assert "attends to all the tokens." in as_model_blocks[0]["content"]- assert "Let the layer input" in as_model_blocks[0]["content"]---def test_demo3_pages6_7_and10_fix_caption_inline_titles_and_reference_tail() -> None:- """验证跨栏 caption、行内粗体正文与参考文献尾行均保持正确归属。"""-- model_list = _native_model_list("demo3.pdf")- page6 = model_list[5]- page7 = model_list[6]- page10 = model_list[9]-- table2_caption = next(- block for block in page6 if block["content"].startswith("Table 2:")- )- assert table2_caption["type"] == "text"- assert "Median of 5 independent runs are reported." in table2_caption["content"]- assert table2_caption["content"].endswith("not reported in the original paper.")- assert sum(- "not reported in the original paper." in block["content"]- for block in page6- ) == 1-- attention_bias = next(- block for block in page7 if block["content"].startswith("Attention Bias Scaling.")- )- positional_ids = next(- block- for block in page7- if block["content"].startswith("Row, Column, & Global Positional IDs.")- )- formula6 = next(- block- for block in page7- if block["type"] == "equation" and "(6)" in block["content"]- )- assert attention_bias["type"] == "text"- assert attention_bias["content"].endswith("attention score by:")- assert positional_ids["type"] == "text"- assert "With TAPASBASE" in positional_ids["content"]- assert formula6["content"].splitlines()[-1] == "(6)"- assert not [- block- for block in page7- if block["type"] == "paragraph_title"- and block["content"].startswith(- ("Attention Bias Scaling.", "Row, Column, & Global Positional IDs.")- )- ]-- ying_reference = next(- block for block in page10 if block["content"].startswith("Chengxuan Ying")- )- yu_reference = next(- block for block in page10 if block["content"].startswith("Tao Yu")- )- assert ying_reference["type"] == yu_reference["type"] == "text"- assert ying_reference["content"].endswith("arXiv:2106.05234.")- assert "Tao Yu" not in ying_reference["content"]- assert not [- block for block in page10 if block["content"] == "arXiv:2106.05234."- ]---def test_demo3_page3_form_image_formulas_titles_and_inline_body_are_whole() -> None:- """验证第三页大 Form、caption、公式、标题及行内粗体都按整体输出。"""-- page = _native_model_list("demo3.pdf")[2]- image_blocks = [block for block in page if block["type"] == "image"]- assert len(image_blocks) == 1- assert not [block for block in page if block["type"] == "table"]- image_block = image_blocks[0]- assert "Transformer (Self Attention)" in image_block["content"]- assert "Screwed Up" in image_block["content"]- assert "Figure 2:" not in image_block["content"]- assert all(- block is image_block- or not pdf_extractor._point_in_bbox(- (- (block["bbox"][0] + block["bbox"][2]) / 2.0,- (block["bbox"][1] + block["bbox"][3]) / 2.0,- ),- tuple(image_block["bbox"]),- )- for block in page- )- caption_blocks = [- block- for block in page- if "Figure 2:" in block["content"]- or "types of task independent biases" in block["content"]- ]- assert len(caption_blocks) == 1- assert caption_blocks[0]["type"] == "text"- assert "This example corresponds to table (a)" in caption_blocks[0]["content"]- assert "associated text." in caption_blocks[0]["content"]-- formula1 = next(block for block in page if "(1)" in block["content"])- section3 = next(block for block in page if block["content"].startswith("3 TABLEFORMER:"))- inline_item = next(block for block in page if block["content"].startswith("2) Per cell positional ids."))- inline_heading = next(- block for block in page if block["content"].startswith("Positional Encoding in TABLEFORMER.")- )- assert formula1["type"] == "equation"- assert "Q = HWQ" in formula1["content"] and "K = HWK" in formula1["content"]- assert section3["type"] == "paragraph_title"- assert section3["content"] == "3 TABLEFORMER: Robust Structural Table Encoding"- assert inline_item["type"] == "text" and "To further remove any" in inline_item["content"]- assert inline_heading["type"] == "text" and "Transformer model" in inline_heading["content"]---def test_demo3_pages4_and5_fix_lists_formula_titles_italics_and_footnotes() -> None:- """验证第四、五页列表、公式、独立标题、行内标题、斜体续行及脚注边界。"""-- page4, page5 = _native_model_list("demo3.pdf")[3:5]- left_bullets = [- block- for block in page4- if block["type"] == "text"- and block["content"].startswith("•")- and block["bbox"][2] <= 0.5- ]- assert len(left_bullets) == 6- assert all(len(block["content"].split()) > 8 for block in left_bullets)- attention_biases = next(- block for block in page4 if block["content"].startswith("Attention Biases in TABLEFORMER.")- )- assert attention_biases["type"] == "text"- assert "13 bias types" in attention_biases["content"]-- formula3 = next(block for block in page4 if "(3)" in block["content"])- formula4 = next(block for block in page4 if "(4)" in block["content"])- assert formula3["type"] == formula4["type"] == "equation"- assert formula3 is not formula4- assert "A =" in formula3["content"] and "(4)" not in formula3["content"]- assert "(3)" not in formula4["content"]-- relation_blocks = [- block- for block in page4- if "Relation between TABLEFORMER and ETC." in block["content"]- or "ETC (Ainslie et al., 2020)" in block["content"]- ]- assert len(relation_blocks) == 1- assert relation_blocks[0]["type"] == "text"- assert relation_blocks[0]["content"].startswith("Relation between TABLEFORMER and ETC.")- assert "uses vectors to represent relative position labels" in relation_blocks[0]["content"]-- title4 = next(block for block in page4 if block["content"] == "4 Experimental Setup")- title41 = next(block for block in page4 if block["content"] == "4.1 Datasets and Evaluation")- assert title4["type"] == title41["type"] == "paragraph_title"- for prefix, continuation in (- ("Table Question Answering.", "conducted experiments"),- ("Table-Text Entailment.", "TABFACT dataset"),- ):- inline_block = next(block for block in page4 if block["content"].startswith(prefix))- assert inline_block["type"] == "text"- assert continuation in inline_block["content"]-- assert next(block for block in page5 if block["content"] == "4.2 Baselines")["type"] == "paragraph_title"- assert next(- block for block in page5 if block["content"] == "4.3 Perturbing Tables as Augmented Data"- )["type"] == "paragraph_title"- italic_body = next(- block for block in page5 if block["content"].startswith("Could we alleviate")- )- assert italic_body["type"] == "text"- assert italic_body["content"].endswith("without making any")-- final_bullet = next(- block for block in page5 if block["content"].startswith("• How does TABLEFORMER compare")- )- final_footnote = next(- block for block in page5 if block["content"].startswith("3By perturbation")- )- assert final_bullet["type"] == "text"- assert final_footnote["type"] == "page_footnote"- assert "3By perturbation" not in final_bullet["content"]diff --git a/tests/unittest/test_flash_pdf_formulas.py b/tests/unittest/test_flash_pdf_formulas.pynew file mode 100644index 00000000..e8d304f3--- /dev/null+++ b/tests/unittest/test_flash_pdf_formulas.py@@ -0,0 +1,297 @@+from __future__ import annotations+++import pytest++from mineru.backend.flash.native_pdf import (+ formulas,+ geometry,+ models,+)+++from _flash_pdf_test_utils import (+ _text_line,+)+++def _formula_member(+ text: str,+ bbox: tuple[float, float, float, float],+ source_index: int,+) -> tuple[models._LineItem, tuple[float, float, float, float]]:+ """构造公式块序列化测试使用的文本行及其局部几何。"""++ return (+ models._LineItem(+ text=text,+ bbox=bbox,+ angle=0,+ source_index=source_index,+ effective_height=bbox[3] - bbox[1],+ ),+ bbox,+ )+++def test_detached_formula_sidecar_sharing_middle_row_moves_to_trailing_line() -> None:+ """验证纯 bbox 规则会后置与正文共享中间视觉行的远距窄幅 sidecar。"""++ members = [+ _formula_member("numerator", (20.0, 0.0, 60.0, 10.0), 0),+ _formula_member("body", (10.0, 10.0, 40.0, 20.0), 1),+ _formula_member("marker", (100.0, 10.0, 110.0, 20.0), 2),+ _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),+ ]++ block = formulas._formula_members_to_block(+ members,+ (130.0, 60.0),+ 0,+ anchor_source_index=2,+ )++ assert block == {+ "type": "equation",+ "bbox": (10.0, 0.0, 110.0, 30.0),+ "angle": 0,+ "content": "numerator\nbody\ndenominator\nmarker",+ }++[email protected]("marker", ["(4)", "(4)", "﹙4﹚", "(4)"])+def test_adjacent_parenthesized_formula_number_moves_to_trailing_line(marker: str) -> None:+ """验证贴近公式主体的多种圆括号序号后置,且前导逗号留在原视觉行。"""++ members = [+ _formula_member("numerator", (20.0, 0.0, 90.0, 10.0), 0),+ _formula_member(f", {marker}", (91.0, 0.0, 110.0, 10.0), 1),+ _formula_member("body", (10.0, 10.0, 40.0, 20.0), 2),+ _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),+ ]++ block = formulas._formula_members_to_block(+ members,+ (130.0, 60.0),+ 0,+ anchor_source_index=1,+ )++ assert block == {+ "type": "equation",+ "bbox": (10.0, 0.0, 110.0, 30.0),+ "angle": 0,+ "content": f"numerator,\nbody\ndenominator\n{marker}",+ }+++def test_adjacent_square_bracket_formula_sidecar_keeps_visual_order() -> None:+ """验证方括号内容不触发圆括号公式序号规则。"""++ members = [+ _formula_member("numerator", (20.0, 0.0, 90.0, 10.0), 0),+ _formula_member(", [4]", (91.0, 0.0, 110.0, 10.0), 1),+ _formula_member("body", (10.0, 10.0, 40.0, 20.0), 2),+ _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),+ ]++ block = formulas._formula_members_to_block(+ members,+ (130.0, 60.0),+ 0,+ anchor_source_index=1,+ )++ assert block == {+ "type": "equation",+ "bbox": (10.0, 0.0, 110.0, 30.0),+ "angle": 0,+ "content": "numerator, [4]\nbody\ndenominator",+ }+++def test_detached_formula_sidecar_on_middle_row_moves_after_denominator() -> None:+ """验证独占中间视觉行的远距窄幅 sidecar 排到分母后且不留下空行。"""++ members = [+ _formula_member("numerator", (20.0, 0.0, 70.0, 10.0), 0),+ _formula_member("sidecar", (100.0, 10.0, 110.0, 20.0), 1),+ _formula_member("denominator", (30.0, 20.0, 65.0, 30.0), 2),+ ]++ block = formulas._formula_members_to_block(+ members,+ (130.0, 60.0),+ 0,+ anchor_source_index=1,+ )++ assert block == {+ "type": "equation",+ "bbox": (20.0, 0.0, 110.0, 30.0),+ "angle": 0,+ "content": "numerator\ndenominator\nsidecar",+ }+++def test_detached_formula_sidecar_already_at_end_keeps_visual_row() -> None:+ """验证已经处于内容末尾的离散 sidecar 保持原视觉行格式。"""++ members = [+ _formula_member("formula", (10.0, 0.0, 40.0, 10.0), 0),+ _formula_member("terminal", (100.0, 0.0, 110.0, 10.0), 1),+ ]++ block = formulas._formula_members_to_block(+ members,+ (130.0, 60.0),+ 0,+ anchor_source_index=1,+ )++ assert block == {+ "type": "equation",+ "bbox": (10.0, 0.0, 110.0, 10.0),+ "angle": 0,+ "content": "formula terminal",+ }+++def test_attached_formula_sidecar_keeps_visual_order() -> None:+ """验证与公式主体净空不足的右侧锚点保持原视觉顺序。"""++ members = [+ _formula_member("numerator", (20.0, 0.0, 60.0, 10.0), 0),+ _formula_member("body", (10.0, 10.0, 70.0, 20.0), 1),+ _formula_member("sidecar", (85.0, 10.0, 95.0, 20.0), 2),+ _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),+ ]++ block = formulas._formula_members_to_block(+ members,+ (120.0, 60.0),+ 0,+ anchor_source_index=2,+ )++ assert block == {+ "type": "equation",+ "bbox": (10.0, 0.0, 95.0, 30.0),+ "angle": 0,+ "content": "numerator\nbody sidecar\ndenominator",+ }+++def test_wide_formula_sidecar_keeps_visual_order() -> None:+ """验证宽度超过中位行高限制的远距锚点不会被后置。"""++ members = [+ _formula_member("numerator", (20.0, 0.0, 60.0, 10.0), 0),+ _formula_member("body", (10.0, 10.0, 70.0, 20.0), 1),+ _formula_member("wide", (100.0, 10.0, 126.0, 20.0), 2),+ _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),+ ]++ block = formulas._formula_members_to_block(+ members,+ (140.0, 60.0),+ 0,+ anchor_source_index=2,+ )++ assert block == {+ "type": "equation",+ "bbox": (10.0, 0.0, 126.0, 30.0),+ "angle": 0,+ "content": "numerator\nbody wide\ndenominator",+ }+++def test_non_rightmost_formula_sidecar_keeps_visual_order() -> None:+ """验证未处于公式分量最右侧的锚点不会被后置。"""++ members = [+ _formula_member("numerator", (20.0, 0.0, 120.0, 10.0), 0),+ _formula_member("body", (10.0, 10.0, 40.0, 20.0), 1),+ _formula_member("sidecar", (90.0, 10.0, 100.0, 20.0), 2),+ _formula_member("denominator", (30.0, 20.0, 70.0, 30.0), 3),+ ]++ block = formulas._formula_members_to_block(+ members,+ (140.0, 60.0),+ 0,+ anchor_source_index=2,+ )++ assert block == {+ "type": "equation",+ "bbox": (10.0, 0.0, 120.0, 30.0),+ "angle": 0,+ "content": "numerator\nbody sidecar\ndenominator",+ }+++def test_detached_formula_anchor_collects_multiline_formula_but_not_body_prefix() -> None:+ """验证低位右缘锚点上溯多行公式,并排除左对齐正文与靠右句点。"""++ body_font = ("Body", 0)+ body_lines = [+ _text_line(+ f"body-{index}",+ (0.0, top, 100.0, top + 10.0),+ index,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=1.0,+ )+ for index, top in enumerate((0.0, 12.0, 24.0))+ ]+ body_prefix = _text_line(+ "regular prose before formula",+ (0.0, 60.0, 60.0, 70.0),+ 3,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=1.0,+ )+ formula_lines = [+ _text_line("numerator", (20.0, 42.0, 50.0, 52.0), 4, effective_height=10.0),+ _text_line("Fp =", (15.0, 52.0, 45.0, 62.0), 5, effective_height=10.0),+ _text_line("otherwise", (20.0, 65.0, 65.0, 75.0), 6, effective_height=10.0),+ _text_line("0,", (68.0, 72.0, 78.0, 82.0), 7, effective_height=10.0),+ ]+ punctuation = _text_line(".", (93.0, 45.0, 96.0, 55.0), 8, effective_height=10.0)+ number = _text_line("(7)", (91.0, 75.0, 100.0, 85.0), 9, effective_height=10.0)+ lane_lines = [*body_lines, body_prefix, *formula_lines, punctuation, number]+ lane = models._TextLane(+ left=0.0,+ right=100.0,+ lines=[(line, line.bbox) for line in lane_lines],+ )++ anchors = formulas._find_formula_spatial_anchors(lane, 10.0)++ assert len(anchors) == 1+ assert anchors[0].line is number+ assert anchors[0].detached_below_body++ anchor_center = geometry._bbox_center_y(anchors[0].bbox)+ dominant_font = formulas._infer_formula_body_font(lane, 10.0)+ members = formulas._grow_formula_spatial_component(+ lane,+ anchors[0],+ anchor_center - 4.75 * 10.0,+ anchor_center + 2.25 * 10.0,+ set(),+ [],+ dominant_font,+ 10.0,+ )+ member_texts = {line.text for line, _bbox in members}++ assert member_texts == {"numerator", "Fp =", "otherwise", "0,", "(7)"}+ assert body_prefix.text not in member_texts+ assert punctuation.text not in member_texts++diff --git a/tests/unittest/test_flash_pdf_graphics.py b/tests/unittest/test_flash_pdf_graphics.pynew file mode 100644index 00000000..3e9affb0--- /dev/null+++ b/tests/unittest/test_flash_pdf_graphics.py@@ -0,0 +1,230 @@+from __future__ import annotations++++from mineru.backend.flash.native_pdf import (+ graphics,+ models,+ pipeline,+)+++from _flash_pdf_test_utils import (+ _text_line,+)+++def _drawing_axis_line(+ orientation: str,+ bbox: tuple[float, float, float, float],+) -> models._AxisLine:+ """构造图形容器测试使用的 PDF 绘图线。"""++ return models._AxisLine(+ bbox=bbox,+ width=0.5,+ orientation=orientation, # type: ignore[arg-type]+ )+++def _graphic_source_fixture() -> models._PageSource:+ """构造双框图形、六个标签、拆分 caption 与邻近正文。"""++ lines = [+ _text_line("p = (x, y)", (378.0, 302.0, 421.0, 312.0), 0, visual_row_id=10),+ _text_line("pbar = (xbar, y)", (445.0, 302.0, 488.0, 312.0), 1, visual_row_id=10),+ _text_line("dp", (382.0, 282.0, 403.0, 292.0), 2, visual_row_id=11),+ _text_line("x", (468.0, 282.0, 475.0, 292.0), 3, visual_row_id=11),+ _text_line("Left camera", (360.0, 339.0, 411.0, 350.0), 4, visual_row_id=12),+ _text_line("Right camera", (458.0, 339.0, 509.0, 350.0), 5, visual_row_id=12),+ _text_line(+ "Figure 1: a deliberately long caption that must remain",+ (312.0, 359.0, 500.0, 371.0),+ 6,+ visual_row_id=20,+ split_from_row=True,+ ),+ _text_line(+ "independent.",+ (510.0, 359.0, 563.0, 371.0),+ 7,+ visual_row_id=20,+ split_from_row=True,+ ),+ _text_line("Nearby prose", (370.0, 225.0, 430.0, 237.0), 8, visual_row_id=9),+ ]+ drawing_lines = [+ _drawing_axis_line("horizontal", (348.0, 272.0, 430.0, 272.5)),+ _drawing_axis_line("horizontal", (348.0, 331.5, 430.0, 332.0)),+ _drawing_axis_line("vertical", (348.0, 272.0, 348.5, 332.0)),+ _drawing_axis_line("vertical", (429.5, 272.0, 430.0, 332.0)),+ _drawing_axis_line("horizontal", (436.0, 272.0, 526.0, 272.5)),+ _drawing_axis_line("horizontal", (436.0, 331.5, 526.0, 332.0)),+ _drawing_axis_line("vertical", (436.0, 272.0, 436.5, 332.0)),+ _drawing_axis_line("vertical", (525.5, 272.0, 526.0, 332.0)),+ ]+ return models._PageSource(+ page_size=(612.0, 792.0),+ lines=lines,+ chars=[],+ drawing_lines=drawing_lines,+ )+++def test_double_box_graphic_claims_six_labels_but_not_caption_or_body() -> None:+ """验证双框图形整行聚合六个标签,拆分 caption 和邻近正文均不被部分认领。"""++ blocks, claimed = graphics._build_graphic_like_blocks(+ _graphic_source_fixture(),+ [],+ set(),+ )++ assert len(blocks) == 1+ assert claimed == set(range(6))+ assert blocks[0]["type"] == "image"+ for expected_text in ("dp", "x", "p = (x, y)", "pbar = (xbar, y)", "Left camera", "Right camera"):+ assert expected_text in blocks[0]["content"]+ assert blocks[0]["content"].count("Left camera") == 1+ assert blocks[0]["content"].count("Right camera") == 1+ assert "Figure 1" not in blocks[0]["content"]+ assert "Nearby prose" not in blocks[0]["content"]+++def test_materialized_table_bbox_has_priority_over_graphic_candidate() -> None:+ """验证绘图组件与成功表格框重叠时跳过图形容器并保留全部文本身份。"""++ blocks, claimed = graphics._build_graphic_like_blocks(+ _graphic_source_fixture(),+ [(340.0, 265.0, 535.0, 355.0)],+ set(),+ )++ assert blocks == []+ assert claimed == set()+++def test_form_image_claims_internal_text_and_small_table_but_not_caption() -> None:+ """验证有效 Form 吞并图内文字与小表候选,外部 caption 仍保留。"""++ form_bbox = (10.0, 10.0, 90.0, 65.0)+ source = models._PageSource(+ page_size=(100.0, 100.0),+ lines=[+ _text_line("inside row one", (15.0, 20.0, 70.0, 30.0), 0, visual_row_id=1),+ _text_line("inside row two", (15.0, 35.0, 80.0, 45.0), 1, visual_row_id=2),+ _text_line("Figure 1: outside", (10.0, 70.0, 80.0, 80.0), 2, visual_row_id=3),+ ],+ chars=[],+ drawing_lines=[+ _drawing_axis_line("horizontal", (20.0, 15.0, 80.0, 15.5)),+ _drawing_axis_line("horizontal", (20.0, 55.0, 80.0, 55.5)),+ _drawing_axis_line("vertical", (20.0, 15.0, 20.5, 55.0)),+ _drawing_axis_line("vertical", (79.5, 15.0, 80.0, 55.0)),+ ],+ form_bboxes=[form_bbox],+ )++ selected = graphics._select_form_image_bboxes(source)+ blocks, claimed = graphics._build_form_image_blocks(source, selected, set())++ assert selected == [form_bbox]+ assert graphics._form_supersedes_nested_bbox(+ form_bbox,+ (20.0, 20.0, 40.0, 35.0),+ )+ assert not graphics._form_supersedes_nested_bbox(+ form_bbox,+ (15.0, 15.0, 85.0, 60.0),+ )+ assert claimed == {0, 1}+ assert blocks == [+ {+ "type": "image",+ "bbox": form_bbox,+ "angle": 0,+ "content": "inside row one\ninside row two",+ }+ ]+++def test_raster_images_filter_small_objects_avoid_containers_and_claim_text_once() -> None:+ """验证点阵图过滤、容器优先、空 content 和重叠对象的唯一文本归属。"""++ source = models._PageSource(+ page_size=(100.0, 100.0),+ lines=[+ _text_line("inside", (25.0, 25.0, 35.0, 35.0), 0, visual_row_id=1),+ _text_line("outside caption", (10.0, 52.0, 50.0, 60.0), 1, visual_row_id=2),+ _text_line("covered container text", (20.0, 70.0, 40.0, 80.0), 2, visual_row_id=3),+ ],+ chars=[],+ drawing_lines=[],+ image_bboxes=[+ (10.0, 10.0, 50.0, 50.0),+ (20.0, 20.0, 40.0, 40.0),+ (60.0, 10.0, 90.0, 40.0),+ (0.0, 90.0, 10.0, 94.0),+ (10.0, 60.0, 50.0, 90.0),+ ],+ )++ blocks, claimed = graphics._build_raster_image_blocks(+ source,+ [{"type": "table", "bbox": (10.0, 60.0, 50.0, 90.0), "angle": 0, "content": "table"}],+ set(),+ )++ assert len(blocks) == 3+ assert all(block["type"] == "image" and block["angle"] == 0 for block in blocks)+ assert [block["bbox"] for block in blocks] == [+ (10.0, 10.0, 50.0, 50.0),+ (60.0, 10.0, 90.0, 40.0),+ (20.0, 20.0, 40.0, 40.0),+ ]+ assert [block["content"] for block in blocks] == ["", "", "inside"]+ assert claimed == {0}+++def test_raster_image_content_is_removed_from_text_and_empty_image_page_is_kept() -> None:+ """验证图内文本只进入 image,caption 保持 text,纯图片页仍输出空 content。"""++ source = models._PageSource(+ page_size=(100.0, 100.0),+ lines=[+ _text_line("inside row one", (20.0, 20.0, 50.0, 30.0), 0, visual_row_id=1),+ _text_line("inside row two", (20.0, 35.0, 50.0, 45.0), 1, visual_row_id=2),+ _text_line("Figure 1: outside caption", (10.0, 70.0, 80.0, 80.0), 2, visual_row_id=3),+ ],+ chars=[],+ drawing_lines=[],+ image_bboxes=[(10.0, 10.0, 60.0, 60.0)],+ )++ blocks = pipeline._analyze_page_source(source)+ image_block = next(block for block in blocks if block["type"] == "image")+ text_block = next(block for block in blocks if block["type"] == "text")++ assert image_block["content"] == "inside row one\ninside row two"+ assert text_block["content"] == "Figure 1: outside caption"+ assert sum("inside row" in block["content"] for block in blocks) == 1++ empty_page_blocks = pipeline._analyze_page_source(+ models._PageSource(+ page_size=(100.0, 100.0),+ lines=[],+ chars=[],+ drawing_lines=[],+ image_bboxes=[(10.0, 10.0, 60.0, 60.0)],+ )+ )+ assert empty_page_blocks == [+ {+ "type": "image",+ "bbox": [0.1, 0.1, 0.6, 0.6],+ "angle": 0,+ "content": "",+ }+ ]++diff --git a/tests/unittest/test_flash_pdf_pipeline.py b/tests/unittest/test_flash_pdf_pipeline.pynew file mode 100644index 00000000..c9851087--- /dev/null+++ b/tests/unittest/test_flash_pdf_pipeline.py@@ -0,0 +1,116 @@+from __future__ import annotations++import ast+import inspect++import pytest++from mineru.backend.flash import pdf_extractor+from mineru.backend.flash.native_pdf import (+ auxiliary_text,+ formulas,+ geometry,+ graphics,+ line_layout,+ line_merging,+ models,+ native_text,+ pipeline,+ tables,+ text_blocks,+ titles,+)+++def test_flash_extractor_has_no_local_ocr_runtime_logic() -> None:+ """守卫 Flash extractor 不再引入或实现本地 OCR 运行时逻辑。"""++ source = "\n".join(+ inspect.getsource(module)+ for module in (+ pdf_extractor,+ auxiliary_text,+ formulas,+ geometry,+ graphics,+ line_layout,+ line_merging,+ models,+ native_text,+ pipeline,+ tables,+ text_blocks,+ titles,+ )+ )+ forbidden_tokens = (+ "import numpy",+ "import cv2",+ "project_ocr_table_text",+ "_load_ocr_runtime",+ "_run_full_page_ocr",+ "_project_ocr_candidate",+ "_recognize_rotated_ocr_table",+ "AtomModelSingleton",+ "run_ocr_inference",+ "get_processing_window_size",+ "bgr_image",+ "pixel_quad",+ "ocr_model",+ )++ assert not [token for token in forbidden_tokens if token in source]+++def test_flash_extractor_only_exports_supported_entrypoints() -> None:+ """验证旧模块只声明两个稳定公共入口,不再承载内部实现。"""++ assert pdf_extractor.__all__ == ["doc_analyze", "extract_pages_text"]+ assert not hasattr(pdf_extractor, "_analyze_native_document")+++def test_native_pdf_domain_modules_do_not_import_each_other() -> None:+ """守卫领域处理器只依赖共享层,跨领域组合统一留在 pipeline。"""++ domain_modules = (+ auxiliary_text,+ formulas,+ graphics,+ tables,+ text_blocks,+ titles,+ )+ domain_names = {module.__name__.rsplit(".", 1)[-1] for module in domain_modules}+ for module in domain_modules:+ tree = ast.parse(inspect.getsource(module))+ relative_imports = {+ node.module+ for node in ast.walk(tree)+ if isinstance(node, ast.ImportFrom) and node.level == 1 and node.module is not None+ }+ assert not relative_imports & domain_names, module.__name__+++ "block_type",+ [+ "doc_title",+ "paragraph_title",+ "header",+ "footer",+ "page_number",+ "page_footnote",+ "aside_text",+ "equation",+ ],+)+def test_output_normalization_preserves_new_flash_types(block_type: str) -> None:+ """验证 Flash 文本语义类型和公式类型不会在归一化阶段退回 text。"""++ block = pipeline._normalize_output_block(+ {"type": block_type, "bbox": (10.0, 20.0, 40.0, 50.0), "angle": 0, "content": "value"},+ (100.0, 100.0),+ )++ assert block is not None+ assert block["type"] == block_typediff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.pynew file mode 100644index 00000000..db13acdc--- /dev/null+++ b/tests/unittest/test_flash_pdf_samples.py@@ -0,0 +1,680 @@+from __future__ import annotations++from pathlib import Path+from typing import Any+++from mineru.backend.flash import pdf_extractor+from mineru.backend.flash.native_pdf import (+ formulas,+ geometry,+ graphics,+ line_merging,+ models,+ native_text,+ pipeline,+ tables,+)+from mineru.utils.pdf_document import get_lines_from_chars+++def _native_model_list(pdf_name: str) -> list[list[dict[str, Any]]]:+ """运行仓库内数字 PDF 样例并返回 Flash 原生模型输出。"""++ pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / pdf_name+ with pdf_extractor.PDFDocument(str(pdf_path)) as pdf_doc:+ return pipeline._analyze_native_document(pdf_doc)+++def _native_table_counts(pdf_name: str) -> list[int]:+ """返回仓库内数字 PDF 样例的逐页表格块数量。"""++ return [sum(block["type"] == "table" for block in page) for page in _native_model_list(pdf_name)]+++def _native_page_source(pdf_name: str, page_idx: int) -> models._PageSource:+ """读取指定样例页并构造候选检测与认领测试使用的页面源。"""++ pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / pdf_name+ with pdf_extractor.PDFDocument(str(pdf_path)) as pdf_doc:+ page_size = pdf_doc.page_size(page_idx)+ chars = pdf_doc.get_page_chars(page_idx)+ lines = native_text._build_native_line_items(+ get_lines_from_chars(chars),+ page_size,+ page_rotation=pdf_doc.page_rotation(page_idx),+ )+ return models._PageSource(+ page_size=page_size,+ lines=lines,+ chars=chars,+ drawing_lines=native_text._get_pdf_drawing_lines(pdf_doc, page_idx),+ image_bboxes=pdf_doc.get_page_image_bboxes(page_idx),+ form_bboxes=pdf_doc.get_page_form_bboxes(page_idx),+ )+++def _normalized_content_probe(text: str) -> str:+ """去除空白、标点与 dash 差异,生成原生行内容覆盖检查使用的探针。"""++ return "".join(char.casefold() for char in text if char.isalnum())+++def test_demo1_keeps_five_real_tables_without_formula_false_positive() -> None:+ """验证 demo1 首页脚注、参考文献、公式与五个真实表格均保持正确。"""++ model_list = _native_model_list("demo1.pdf")++ assert [len(page) for page in model_list] == [16, 9, 12, 18, 10, 9, 11, 8, 10, 7, 10, 26, 9]+ assert [sum(block["type"] == "table" for block in page) for page in model_list] == [+ 0,+ 0,+ 0,+ 0,+ 1,+ 2,+ 0,+ 1,+ 1,+ 0,+ 0,+ 0,+ 0,+ ]+ assert sum(block["type"] == "doc_title" for page in model_list for block in page) == 1+ assert sum(block["type"] == "header" for page in model_list for block in page) == 12+ assert sum(block["type"] == "page_number" for page in model_list for block in page) == 12+ assert sum(block["type"] == "equation" for page in model_list for block in page) == 7+ page1_footnotes = [block for block in model_list[0] if block["type"] == "page_footnote"]+ assert len(page1_footnotes) == 1+ assert page1_footnotes[0]["content"].startswith("* Corresponding author.")+ copyright_block = next(+ block for block in model_list[0] if block["content"].startswith("0022-1694/$")+ )+ assert copyright_block["type"] == "text"+ assert "doi:10.1016/j.jhydrol.2005.01.006" in copyright_block["content"]+ assert next(block for block in model_list[0] if block["content"] == "Abstract")["type"] == "paragraph_title"+ assert next(block for block in model_list[6] if block["content"].startswith("4.2."))["type"] == "paragraph_title"+++def test_demo1_rotated_table_claims_all_206_lines_without_residual_text() -> None:+ """验证 demo1 第五页旋转表完整认领 206 行且表框内没有残留文本。"""++ source = _native_page_source("demo1.pdf", 4)+ candidates = tables._detect_table_candidates(source)+ blocks, claimed = tables._materialize_table_blocks(source, candidates)+ rotated_indices = {line.source_index for line in source.lines if line.angle == 270}++ assert len(blocks) == 1+ assert len(rotated_indices) == 206+ assert claimed == rotated_indices+ assert not [+ line+ for line in source.lines+ if line.angle == 270+ and line.source_index not in claimed+ and any(+ candidate.angle == 270+ and geometry._point_in_bbox(+ (geometry._bbox_center_x(line.bbox), geometry._bbox_center_y(line.bbox)),+ candidate.bbox,+ )+ for candidate in candidates+ )+ ]+++def test_demo2_rejects_figure_grid_and_keeps_two_real_tables() -> None:+ """验证 demo2 曲线图被拒绝且第四、五页真实表格保留。"""++ assert _native_table_counts("demo2.pdf") == [0, 0, 0, 1, 1, 0]+++def test_demo2_page1_forms_sixteen_blocks_and_keeps_figure_caption_separate() -> None:+ """验证 demo2 首页正文自然聚合,六个 Figure 1 标签单块且 caption 独立。"""++ page = _native_model_list("demo2.pdf")[0]+ graphic_block = next(block for block in page if "Left camera" in block["content"])+ caption_block = next(block for block in page if "Figure 1:" in block["content"])++ assert len(page) == 16+ assert not [block for block in page if block["type"] == "table"]+ assert next(block for block in page if block["content"].startswith("Real-time Temporal"))["type"] == "doc_title"+ assert next(block for block in page if block["content"] == "I. INTRODUCTION")["type"] == "paragraph_title"+ for expected_text in ("dp", "¯x", "p =", "¯p =", "Left camera", "Right camera"):+ assert expected_text in graphic_block["content"]+ assert graphic_block is not caption_block+ assert "Figure 1:" not in graphic_block["content"]+ assert "Left camera" not in caption_block["content"]+ assert sum(block["content"].count("Left camera") for block in page) == 1+++def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> None:+ """验证 demo2 后续页达到目标块数,正文、公式、caption 与双栏顺序均稳定。"""++ model_list = _native_model_list("demo2.pdf")++ assert [len(page) for page in model_list] == [16, 16, 21, 13, 16, 16]+ assert [sum(block["type"] == "image" for block in page) for page in model_list] == [1, 0, 0, 5, 2, 0]+ assert [sum(block["type"] == "table" for block in page) for page in model_list] == [0, 0, 0, 1, 1, 0]+ assert sum(block["type"] == "equation" for page in model_list for block in page) == 9++ page2 = model_list[1]+ page2_contents = [block["content"] for block in page2]+ humans = next(content for content in page2_contents if content.startswith("Humans group shapes"))+ matching = next(content for content in page2_contents if content.startswith("To identify a match"))+ dissimilarity = next(content for content in page2_contents if content.startswith("where the pixel dissimilarity"))+ formula3 = next(content for content in page2_contents if content.endswith("(3)"))+ assert not [content for content in page2_contents if content.strip() == "by"]+ assert humans.endswith("is given by")+ assert "Sp denotes a set of matching candidates" in matching+ assert "green, and blue components given by" in dissimilarity+ assert "green, and blue" not in formula3++ page3 = model_list[2]+ page3_contents = [block["content"] for block in page3]+ assert page3_contents[12] == "D. Iterative Disparity Refinement"+ assert all(block["bbox"][2] <= 0.5 for block in page3[:12])+ assert "O(ω2) to O(ω)" in page3_contents[0]+ assert "disparity estimates Dip" in page3_contents[13]+ for formula_number in range(4, 10):+ marker = f"({formula_number})"+ assert sum(marker in content for content in page3_contents) == 1+ formula7 = next(content for content in page3_contents if "(7)" in content)+ formula4 = next(content for content in page3_contents if "(4)" in content)+ formula8 = next(content for content in page3_contents if "(8)" in content)+ assert formula4.splitlines()[-1] == "(4)"+ assert formula8.splitlines()[-1] == "(8)"+ assert "(4)" not in "\n".join(formula4.splitlines()[:-1])+ assert "(8)" not in "\n".join(formula8.splitlines()[:-1])+ assert "Fp =" in formula7+ assert "otherwise" in formula7+ assert not [content for content in page3_contents if content.strip() in {"2", "p", "otherwise", "(7)"}]+ assert "available at http://mc2.unl.edu/current-research" in page3_contents[-1]+ assert "/image-processing/. Figure 2" in page3_contents[-1]++ page4_contents = [block["content"] for block in model_list[3]]+ figure2 = next(content for content in page4_contents if content.startswith("Figure 2:"))+ figure3 = next(content for content in page4_contents if content.startswith("Figure 3:"))+ results = next(content for content in page4_contents if content.startswith("The results of temporal stereo"))+ improvements = next(content for content in page4_contents if content.startswith("Significant improvements"))+ assert figure2.endswith("(4th row).")+ assert figure3.endswith("without temporal aggregation.")+ assert results.endswith("methods that operate on pairs of images.")+ assert improvements.endswith("has the effect")++ page5_contents = [block["content"] for block in model_list[4]]+ optimal_feedback = next(content for content in page5_contents if content.startswith("The optimal value"))+ page5_references = [content for content in page5_contents if content.startswith("[")]+ assert "noise ranging between ±0 to ±40" in optimal_feedback+ assert optimal_feedback.endswith("temporal stereo matching is used.")+ assert [content.partition("]")[0] + "]" for content in page5_references] == [+ f"[{number}]" for number in range(1, 6)+ ]++ page6_contents = [block["content"] for block in model_list[5]]+ assert len(page6_contents) == 16+ assert [content.partition("]")[0] + "]" for content in page6_contents] == [+ f"[{number}]" for number in range(6, 22)+ ]+++def test_demo2_container_claims_are_pairwise_disjoint() -> None:+ """验证表格、图形和公式阶段按 source_index 唯一认领,不重复消费文本身份。"""++ for page_idx in (1, 2, 3):+ source = _native_page_source("demo2.pdf", page_idx)+ table_candidates = tables._detect_table_candidates(source)+ table_blocks, table_claimed = tables._materialize_table_blocks(source, table_candidates)+ table_bboxes = [block["bbox"] for block in table_blocks]+ _graphic_blocks, graphic_claimed = graphics._build_graphic_like_blocks(+ source,+ table_bboxes,+ table_claimed,+ )+ remaining = line_merging._merge_same_baseline_text_lines(+ [+ line+ for line in source.lines+ if line.source_index not in table_claimed | graphic_claimed+ ],+ source.page_size,+ table_bboxes,+ )+ formula_input_indices = {line.source_index for line in remaining}+ _formula_blocks, formula_remaining = formulas._build_formula_like_blocks(+ remaining,+ table_bboxes,+ source.page_size,+ )+ formula_claimed = formula_input_indices - {line.source_index for line in formula_remaining}++ assert table_claimed.isdisjoint(graphic_claimed)+ assert table_claimed.isdisjoint(formula_claimed)+ assert graphic_claimed.isdisjoint(formula_claimed)+ combined = table_claimed | graphic_claimed | formula_claimed+ assert len(combined) == len(table_claimed) + len(graphic_claimed) + len(formula_claimed)+++def test_demo2_page4_groups_five_graphics_and_keeps_table1() -> None:+ """验证 demo2 第四页五个图形区域分别聚合,Table 1 继续优先输出为 table。"""++ page = _native_model_list("demo2.pdf")[3]+ table_blocks = [block for block in page if block["type"] == "table"]+ graphic_markers = ("Frame 30", "Noise: ±0", "Noise: ±20", "Noise: ±40", "Noise ±")+ graphic_blocks = [+ next(block for block in page if block["type"] == "image" and marker in block["content"])+ for marker in graphic_markers+ ]++ assert len(table_blocks) == 1+ assert "Table I:" in table_blocks[0]["content"]+ assert len({id(block) for block in graphic_blocks}) == 5+ assert "Frame 90" in graphic_blocks[0]["content"]+ assert all("Figure" not in block["content"] for block in graphic_blocks)+++def test_demo2_table_captions_and_numeric_footnotes_are_not_text_blocks() -> None:+ """验证 demo2 两张表的换行标题和数字脚注全部并入表格投影。"""++ model_list = _native_model_list("demo2.pdf")+ page4_table = next(block for block in model_list[3] if block["type"] == "table")+ page5_table = next(block for block in model_list[4] if block["type"] == "table")+ residual_text = "\n".join(+ block["content"] for page_idx in (3, 4) for block in model_list[page_idx] if block["type"] == "text"+ )++ assert "ral stereo matching." in page4_table["content"]+ assert "1 To enable propagation of disparity information" in page4_table["content"]+ assert "0.01, respectively." in page4_table["content"]+ assert "Noise: ±20" not in page4_table["content"]+ assert "1 Millions of Disparity Estimates per Second." in page5_table["content"]+ assert "2 Assumes 320 × 240 images with 32 disparity levels." in page5_table["content"]+ assert "the avgerage % of bad pixels." in page5_table["content"]+ assert "ral stereo matching." not in residual_text+ assert "Millions of Disparity Estimates per Second." not in residual_text+++def test_demo3_keeps_tables_and_covers_every_native_source_line() -> None:+ """验证 demo3 容器、后续页段落边界及每条原生 source line 均保持稳定。"""++ pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / "demo3.pdf"+ with pdf_extractor.PDFDocument(str(pdf_path)) as pdf_doc:+ model_list = pipeline._analyze_native_document(pdf_doc)+ source_lines_by_page: list[list[models._LineItem]] = []+ for page_idx in range(pdf_doc.page_count):+ page_size = pdf_doc.page_size(page_idx)+ source_lines_by_page.append(+ native_text._build_native_line_items(+ get_lines_from_chars(pdf_doc.get_page_chars(page_idx)),+ page_size,+ page_rotation=pdf_doc.page_rotation(page_idx),+ )+ )++ assert [sum(block["type"] == "table" for block in page) for page in model_list] == [+ 2,+ 0,+ 0,+ 0,+ 1,+ 2,+ 2,+ 2,+ 0,+ 0,+ ]+ assert [len(page) for page in model_list] == [+ 24,+ 15,+ 13,+ 21,+ 19,+ 16,+ 16,+ 15,+ 17,+ 18,+ ]+ page7_tables = [block for block in model_list[6] if block["type"] == "table"]+ page7_table4 = next(+ block for block in page7_tables if "Number of parameters" in block["content"]+ )+ page7_table4_caption = next(+ block+ for block in model_list[6]+ if block["content"] == "Table 4: Model size comparison."+ )+ page7_inline_body = next(+ block+ for block in model_list[6]+ if block["content"].startswith("Row, Column, & Global Positional IDs.")+ )+ page9_conclusion = next(+ block+ for block in model_list[8]+ if block["content"].startswith("In this paper, we identified")+ )+ page10_first_reference = next(+ block+ for block in model_list[9]+ if block["content"].startswith("Xiang Deng, Huan Sun")+ )+ assert all(+ marker in page7_table4["content"]+ for marker in (+ "Model",+ "TAPASBASE",+ "TABLEFORMERBASE",+ "TAPASLARGE",+ "TABLEFORMERLARGE",+ )+ )+ assert page7_table4_caption["content"] not in page7_table4["content"]+ assert page7_table4["bbox"][3] < page7_table4_caption["bbox"][1]+ assert page7_inline_body["type"] == "text"+ assert "With TAPASBASE" in page7_inline_body["content"]+ assert "To tackle this" in page9_conclusion["content"]+ assert "Acknowledgments" not in page9_conclusion["content"]+ assert "Cong Yu. 2021. TURL:" in page10_first_reference["content"]+ assert "Jacob Devlin" not in page10_first_reference["content"]+ for page, source_lines in zip(model_list, source_lines_by_page, strict=True):+ output_probe = _normalized_content_probe("".join(str(block.get("content") or "") for block in page))+ missing_lines = [+ line.text+ for line in source_lines+ if (line_probe := _normalized_content_probe(line.text)) and line_probe not in output_probe+ ]+ assert not missing_lines+++def test_demo3_auxiliary_text_types_match_real_page_geometry() -> None:+ """验证真实 PDF 的首页侧栏及第 1、5、6、9 页脚注命中,公式页不误报。"""++ model_list = _native_model_list("demo3.pdf")++ assert [sum(block["type"] == "aside_text" for block in page) for page in model_list] == [+ 1,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ ]+ assert [sum(block["type"] == "page_footnote" for block in page) for page in model_list] == [+ 2,+ 0,+ 0,+ 0,+ 2,+ 1,+ 0,+ 0,+ 1,+ 0,+ ]+ assert not [+ block+ for block in model_list[6]+ if block["type"] in {"aside_text", "page_footnote"}+ ]+++def test_demo3_pages1_and2_fix_title_front_matter_and_embedding_formula() -> None:+ """验证首页标题稳定,第二页标题、公式和栏尾正文各自保持完整。"""++ page1, page2 = _native_model_list("demo3.pdf")[:2]+ title = next(block for block in page1 if block["content"].startswith("TABLEFORMER:"))+ front_matter_contents = {+ "∗",+ "Aditya Gupta† Rahul Goel†",+ "Jingfeng Yang Luheng He†",+ "Shyam Upadhyay† Shachi Paul †",+ "?Georgia Institute of Technology",+ "†Google Assistant",+ }+ front_matter = [+ block for block in page1 if block["content"] in front_matter_contents+ ]+ released_code = next(+ block for block in page1 if "TABLEFORMER.md" in block["content"]+ )+ aside = next(block for block in page1 if block["type"] == "aside_text")+ introduction = next(+ block for block in page1 if block["content"].startswith("Recently, semi-structured")+ )+ nutshell = next(+ block for block in page1 if block["content"].startswith("In a nutshell")+ )+ figure_caption = next(+ block for block in page1 if block["content"].startswith("Figure 1:")+ )+ tables_body = next(+ block for block in page1 if block["content"].startswith("tables or rows")+ )++ assert title["type"] == "doc_title"+ assert len(front_matter) == len(front_matter_contents)+ assert all(block["type"] == "text" for block in front_matter)+ assert next(block for block in page1 if block["content"] == "Abstract")["type"] == "paragraph_title"+ assert released_code["type"] == "page_footnote"+ assert aside["angle"] == 270+ assert aside["bbox"][2] <= 0.12+ assert introduction["content"].endswith("(Eisenschlos et al., 2021; Liu et al., 2021).")+ assert nutshell["type"] == "text"+ assert nutshell["content"].endswith("by serializing")+ assert figure_caption["type"] == "text"+ assert figure_caption["content"].endswith("both questions.")+ assert "tables or rows" not in figure_caption["content"]+ assert tables_body["type"] == "text"++ section_title = next(+ block for block in page2 if block["content"].startswith("2 Preliminaries:")+ )+ equations = [block for block in page2 if block["type"] == "equation"]+ assert section_title["type"] == "paragraph_title"+ assert section_title["content"] == "2 Preliminaries: TAPAS for Table Encoding"+ assert len(equations) == 1+ assert equations[0]["content"].splitlines() == [+ "token ids (W) = {wv1, wv2, · · · , wvn }",+ "positional ids (B) = {b1, b2, · · · , bn}",+ "segment ids (G) = {gseg1, gseg2, · · · , gsegn }",+ "column ids (C) = {ccol1, ccol2, · · · , ccoln}",+ "row ids (R) = {rrow1, rrow2, · · · , rrown }",+ "rank ids (Z) = {zrank1, zrank2, · · · , zrankn}",+ ]+ as_model_blocks = [+ block+ for block in page2+ if "As for the model" in block["content"]+ or "attends to all the tokens." in block["content"]+ or "Let the layer input" in block["content"]+ ]+ assert len(as_model_blocks) == 1+ assert as_model_blocks[0]["type"] == "text"+ assert as_model_blocks[0]["content"].startswith("As for the model")+ assert "attends to all the tokens." in as_model_blocks[0]["content"]+ assert "Let the layer input" in as_model_blocks[0]["content"]+++def test_demo3_pages6_7_and10_fix_caption_inline_titles_and_reference_tail() -> None:+ """验证跨栏 caption、行内粗体正文与参考文献尾行均保持正确归属。"""++ model_list = _native_model_list("demo3.pdf")+ page6 = model_list[5]+ page7 = model_list[6]+ page10 = model_list[9]++ table2_caption = next(+ block for block in page6 if block["content"].startswith("Table 2:")+ )+ assert table2_caption["type"] == "text"+ assert "Median of 5 independent runs are reported." in table2_caption["content"]+ assert table2_caption["content"].endswith("not reported in the original paper.")+ assert sum(+ "not reported in the original paper." in block["content"]+ for block in page6+ ) == 1++ attention_bias = next(+ block for block in page7 if block["content"].startswith("Attention Bias Scaling.")+ )+ positional_ids = next(+ block+ for block in page7+ if block["content"].startswith("Row, Column, & Global Positional IDs.")+ )+ formula6 = next(+ block+ for block in page7+ if block["type"] == "equation" and "(6)" in block["content"]+ )+ assert attention_bias["type"] == "text"+ assert attention_bias["content"].endswith("attention score by:")+ assert positional_ids["type"] == "text"+ assert "With TAPASBASE" in positional_ids["content"]+ assert formula6["content"].splitlines()[-1] == "(6)"+ assert not [+ block+ for block in page7+ if block["type"] == "paragraph_title"+ and block["content"].startswith(+ ("Attention Bias Scaling.", "Row, Column, & Global Positional IDs.")+ )+ ]++ ying_reference = next(+ block for block in page10 if block["content"].startswith("Chengxuan Ying")+ )+ yu_reference = next(+ block for block in page10 if block["content"].startswith("Tao Yu")+ )+ assert ying_reference["type"] == yu_reference["type"] == "text"+ assert ying_reference["content"].endswith("arXiv:2106.05234.")+ assert "Tao Yu" not in ying_reference["content"]+ assert not [+ block for block in page10 if block["content"] == "arXiv:2106.05234."+ ]+++def test_demo3_page3_form_image_formulas_titles_and_inline_body_are_whole() -> None:+ """验证第三页大 Form、caption、公式、标题及行内粗体都按整体输出。"""++ page = _native_model_list("demo3.pdf")[2]+ image_blocks = [block for block in page if block["type"] == "image"]+ assert len(image_blocks) == 1+ assert not [block for block in page if block["type"] == "table"]+ image_block = image_blocks[0]+ assert "Transformer (Self Attention)" in image_block["content"]+ assert "Screwed Up" in image_block["content"]+ assert "Figure 2:" not in image_block["content"]+ assert all(+ block is image_block+ or not geometry._point_in_bbox(+ (+ (block["bbox"][0] + block["bbox"][2]) / 2.0,+ (block["bbox"][1] + block["bbox"][3]) / 2.0,+ ),+ tuple(image_block["bbox"]),+ )+ for block in page+ )+ caption_blocks = [+ block+ for block in page+ if "Figure 2:" in block["content"]+ or "types of task independent biases" in block["content"]+ ]+ assert len(caption_blocks) == 1+ assert caption_blocks[0]["type"] == "text"+ assert "This example corresponds to table (a)" in caption_blocks[0]["content"]+ assert "associated text." in caption_blocks[0]["content"]++ formula1 = next(block for block in page if "(1)" in block["content"])+ section3 = next(block for block in page if block["content"].startswith("3 TABLEFORMER:"))+ inline_item = next(block for block in page if block["content"].startswith("2) Per cell positional ids."))+ inline_heading = next(+ block for block in page if block["content"].startswith("Positional Encoding in TABLEFORMER.")+ )+ assert formula1["type"] == "equation"+ assert "Q = HWQ" in formula1["content"] and "K = HWK" in formula1["content"]+ assert section3["type"] == "paragraph_title"+ assert section3["content"] == "3 TABLEFORMER: Robust Structural Table Encoding"+ assert inline_item["type"] == "text" and "To further remove any" in inline_item["content"]+ assert inline_heading["type"] == "text" and "Transformer model" in inline_heading["content"]+++def test_demo3_pages4_and5_fix_lists_formula_titles_italics_and_footnotes() -> None:+ """验证第四、五页列表、公式、独立标题、行内标题、斜体续行及脚注边界。"""++ page4, page5 = _native_model_list("demo3.pdf")[3:5]+ left_bullets = [+ block+ for block in page4+ if block["type"] == "text"+ and block["content"].startswith("•")+ and block["bbox"][2] <= 0.5+ ]+ assert len(left_bullets) == 6+ assert all(len(block["content"].split()) > 8 for block in left_bullets)+ attention_biases = next(+ block for block in page4 if block["content"].startswith("Attention Biases in TABLEFORMER.")+ )+ assert attention_biases["type"] == "text"+ assert "13 bias types" in attention_biases["content"]++ formula3 = next(block for block in page4 if "(3)" in block["content"])+ formula4 = next(block for block in page4 if "(4)" in block["content"])+ assert formula3["type"] == formula4["type"] == "equation"+ assert formula3 is not formula4+ assert "A =" in formula3["content"] and "(4)" not in formula3["content"]+ assert "(3)" not in formula4["content"]++ relation_blocks = [+ block+ for block in page4+ if "Relation between TABLEFORMER and ETC." in block["content"]+ or "ETC (Ainslie et al., 2020)" in block["content"]+ ]+ assert len(relation_blocks) == 1+ assert relation_blocks[0]["type"] == "text"+ assert relation_blocks[0]["content"].startswith("Relation between TABLEFORMER and ETC.")+ assert "uses vectors to represent relative position labels" in relation_blocks[0]["content"]++ title4 = next(block for block in page4 if block["content"] == "4 Experimental Setup")+ title41 = next(block for block in page4 if block["content"] == "4.1 Datasets and Evaluation")+ assert title4["type"] == title41["type"] == "paragraph_title"+ for prefix, continuation in (+ ("Table Question Answering.", "conducted experiments"),+ ("Table-Text Entailment.", "TABFACT dataset"),+ ):+ inline_block = next(block for block in page4 if block["content"].startswith(prefix))+ assert inline_block["type"] == "text"+ assert continuation in inline_block["content"]++ assert next(block for block in page5 if block["content"] == "4.2 Baselines")["type"] == "paragraph_title"+ assert next(+ block for block in page5 if block["content"] == "4.3 Perturbing Tables as Augmented Data"+ )["type"] == "paragraph_title"+ italic_body = next(+ block for block in page5 if block["content"].startswith("Could we alleviate")+ )+ assert italic_body["type"] == "text"+ assert italic_body["content"].endswith("without making any")++ final_bullet = next(+ block for block in page5 if block["content"].startswith("• How does TABLEFORMER compare")+ )+ final_footnote = next(+ block for block in page5 if block["content"].startswith("3By perturbation")+ )+ assert final_bullet["type"] == "text"+ assert final_footnote["type"] == "page_footnote"+ assert "3By perturbation" not in final_bullet["content"]++diff --git a/tests/unittest/test_flash_pdf_tables.py b/tests/unittest/test_flash_pdf_tables.pynew file mode 100644index 00000000..10319223--- /dev/null+++ b/tests/unittest/test_flash_pdf_tables.py@@ -0,0 +1,302 @@+from __future__ import annotations++from unittest.mock import MagicMock++import pytest++from mineru.backend.flash.native_pdf import (+ geometry,+ models,+ tables,+)+++def _axis_line(+ orientation: str,+ bbox: tuple[float, float, float, float],+) -> models._LocalAxisLine:+ """构造表格候选测试使用的局部横竖线。"""++ return models._LocalAxisLine(+ bbox=bbox,+ original_bbox=bbox,+ orientation=orientation, # type: ignore[arg-type]+ width=0.0,+ )+++ ("median_height", "rejected_length", "accepted_length"),+ [+ (3.0, 39.99, 40.0),+ (5.0, 49.99, 50.0),+ ],+)+def test_long_rule_group_uses_40pt_or_ten_times_height_threshold(+ median_height: float,+ rejected_length: float,+ accepted_length: float,+) -> None:+ """验证长横线沿用 40pt 或十倍行高门槛,竖线不参与分组。"""++ rejected_lines = [+ _axis_line("horizontal", (0.0, 10.0, rejected_length, 10.1)),+ _axis_line("horizontal", (0.0, 20.0, accepted_length, 20.1)),+ _axis_line("horizontal", (0.0, 30.0, accepted_length, 30.1)),+ _axis_line("vertical", (10.0, 0.0, 10.1, 40.0)),+ ]+ accepted_lines = [_axis_line("horizontal", (0.0, top, accepted_length, top + 0.1)) for top in (10.0, 20.0, 30.0)]++ assert tables._group_long_horizontal_rules(rejected_lines, median_height) == []+ assert len(tables._group_long_horizontal_rules(accepted_lines, median_height)) == 1+++def _rule_table_fixture(+ rule_count: int = 3,+ *,+ centered_columns: bool = False,+) -> tuple[+ list[models._VisualRow],+ list[models._LineItem],+ list[models._LocalAxisLine],+]:+ """构造无 caption 的规则表格,并可切换为宽度变化的居中列。"""++ rows: list[models._VisualRow] = []+ lines: list[models._LineItem] = []+ source_index = 0+ for row_index, top in enumerate((10.0, 30.0, 50.0)):+ fragments: list[models._Fragment] = []+ if centered_columns:+ half_width = (2.0, 8.0, 14.0)[row_index]+ column_bounds = (+ (30.0 - half_width, 30.0 + half_width),+ (90.0 - half_width, 90.0 + half_width),+ )+ else:+ column_bounds = ((10.0, 20.0), (50.0, 60.0), (90.0, 100.0))+ for column_index, (left, right) in enumerate(column_bounds):+ bbox = (left, top, right, top + 5.0)+ text = f"r{row_index}c{column_index}"+ fragments.append(+ models._Fragment(+ text=text,+ bbox=bbox,+ local_bbox=bbox,+ line_index=source_index,+ visual_row_id=row_index,+ )+ )+ lines.append(+ models._LineItem(+ text=text,+ bbox=bbox,+ angle=0,+ source_index=source_index,+ effective_height=5.0,+ visual_row_id=row_index,+ )+ )+ source_index += 1+ rows.append(+ models._VisualRow(+ fragments=fragments,+ center_y=top + 2.5,+ bbox=(10.0, top, 100.0, top + 5.0),+ visual_row_id=row_index,+ )+ )+ axis_lines = [_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in (8.0, 33.0, 58.0)[:rule_count]]+ return rows, lines, axis_lines+++def test_rule_table_candidate_accepts_captionless_regular_text_distribution() -> None:+ """验证三横线和连续稳定列足以识别没有显式标题的表格。"""++ rows, lines, axis_lines = _rule_table_fixture()++ candidates = tables._build_rule_table_candidates(+ rows,+ lines,+ (150.0, 100.0),+ 0,+ 5.0,+ axis_lines,+ )++ assert len(candidates) == 1+ assert candidates[0].line_indices == set(range(9))+++def test_rule_table_candidate_accepts_center_aligned_columns_with_varying_widths() -> None:+ """验证左右边界变化但中心稳定的两列表格仍可形成候选。"""++ rows, lines, axis_lines = _rule_table_fixture(centered_columns=True)++ assert tables._count_stable_columns(rows, 5.0) == (2, 1.0)+ candidates = tables._build_rule_table_candidates(+ rows,+ lines,+ (150.0, 100.0),+ 0,+ 5.0,+ axis_lines,+ )++ assert len(candidates) == 1+ assert candidates[0].line_indices == set(range(6))+++def test_two_horizontal_rule_grid_is_deliberately_rejected() -> None:+ """验证即使存在竖线和规则文本,两条长横线也不再形成表格候选。"""++ rows, lines, axis_lines = _rule_table_fixture(rule_count=2)+ axis_lines.extend(+ [+ _axis_line("vertical", (0.0, 8.0, 0.1, 58.0)),+ _axis_line("vertical", (55.0, 8.0, 55.1, 58.0)),+ _axis_line("vertical", (109.9, 8.0, 110.0, 58.0)),+ ]+ )++ candidates = tables._build_rule_table_candidates(+ rows,+ lines,+ (150.0, 100.0),+ 0,+ 5.0,+ axis_lines,+ )++ assert candidates == []+++def test_duplicate_horizontal_paths_do_not_satisfy_three_rule_requirement() -> None:+ """验证同一 y 位置的重复 PDF path 只计为一条横线。"""++ axis_lines = [+ _axis_line("horizontal", (0.0, 10.0, 100.0, 10.1)),+ _axis_line("horizontal", (0.0, 10.5, 100.0, 10.6)),+ _axis_line("horizontal", (0.0, 30.0, 100.0, 30.1)),+ ]++ assert tables._group_long_horizontal_rules(axis_lines, 5.0) == []+++def test_chart_tick_rows_fail_dense_multi_cell_distribution() -> None:+ """验证多个图表刻度行因纵向不连续而不能冒充规则表格。"""++ rows: list[models._VisualRow] = []+ lines: list[models._LineItem] = []+ source_index = 0+ for row_index, (top, anchors) in enumerate(+ (+ (10.0, (10.0, 30.0, 50.0, 70.0, 90.0)),+ (20.0, (50.0,)),+ (30.0, (45.0,)),+ (75.0, (10.0, 30.0, 50.0, 70.0, 90.0)),+ (85.0, (50.0,)),+ (95.0, (45.0,)),+ )+ ):+ fragments: list[models._Fragment] = []+ for anchor in anchors:+ bbox = (anchor, top, anchor + 5.0, top + 5.0)+ text = f"tick-{source_index}"+ fragments.append(+ models._Fragment(+ text=text,+ bbox=bbox,+ local_bbox=bbox,+ line_index=source_index,+ visual_row_id=row_index,+ )+ )+ lines.append(+ models._LineItem(+ text=text,+ bbox=bbox,+ angle=0,+ source_index=source_index,+ effective_height=5.0,+ visual_row_id=row_index,+ )+ )+ source_index += 1+ rows.append(+ models._VisualRow(+ fragments=fragments,+ center_y=top + 2.5,+ bbox=geometry._bbox_union_many([fragment.bbox for fragment in fragments]),+ visual_row_id=row_index,+ )+ )+ axis_lines = [_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in (0.0, 55.0, 110.0)]++ candidates = tables._build_rule_table_candidates(+ rows,+ lines,+ (150.0, 120.0),+ 0,+ 5.0,+ axis_lines,+ )++ assert candidates == []+++def test_split_table_footnote_marker_is_joined_before_matching() -> None:+ """验证旋转表拆开的 For 与星号脚注在视觉行拼接后可被识别。"""++ row = models._VisualRow(+ fragments=[+ models._Fragment("For", (0.0, 0.0, 10.0, 5.0), (0.0, 0.0, 10.0, 5.0), 0),+ models._Fragment("*rainfall", (12.0, 0.0, 35.0, 5.0), (12.0, 0.0, 35.0, 5.0), 1),+ ],+ center_y=2.5,+ bbox=(0.0, 0.0, 35.0, 5.0),+ )++ assert tables._is_table_note_text(tables._visual_row_text(row))+ assert tables._is_table_note_text("1 Numeric table footnote")++[email protected]("projection_mode", ["empty", "error"])+def test_failed_table_projection_does_not_claim_text(+ monkeypatch: pytest.MonkeyPatch,+ projection_mode: str,+) -> None:+ """验证投影为空或抛错时完整回滚候选,文本行仍可进入正文路径。"""++ line = models._LineItem(+ text="cell",+ bbox=(10.0, 10.0, 30.0, 20.0),+ angle=0,+ source_index=0,+ effective_height=10.0,+ )+ source = models._PageSource(+ page_size=(100.0, 100.0),+ lines=[line],+ chars=[],+ drawing_lines=[],+ )+ candidate = models._TableCandidate(+ bbox=(0.0, 0.0, 50.0, 50.0),+ local_bbox=(0.0, 0.0, 50.0, 50.0),+ angle=0,+ score=1.0,+ core_bbox=(0.0, 0.0, 50.0, 50.0),+ line_indices={0},+ )+ projection = MagicMock(return_value="")+ if projection_mode == "error":+ projection.side_effect = RuntimeError("projection failed")+ monkeypatch.setattr(tables, "project_pdf_table_text", projection)++ blocks, claimed = tables._materialize_table_blocks(source, [candidate])++ assert blocks == []+ assert claimed == set()++diff --git a/tests/unittest/test_flash_pdf_text_blocks.py b/tests/unittest/test_flash_pdf_text_blocks.pynew file mode 100644index 00000000..fee5da81--- /dev/null+++ b/tests/unittest/test_flash_pdf_text_blocks.py@@ -0,0 +1,510 @@+from __future__ import annotations+++import pytest++from mineru.backend.flash.native_pdf import (+ line_layout,+ line_merging,+ models,+ native_text,+ text_blocks,+)+++from _flash_pdf_test_utils import (+ _text_line,+)+++def test_hanging_indent_groups_neutral_entries_and_ignores_centered_heading() -> None:+ """验证不含序号的重复悬挂缩进逐条分组,且居中标题不参与条目。"""++ body_font = ("Body", 0)+ italic_font = ("BodyItalic", 1)+ lines = [+ _text_line(+ "Centered heading",+ (35.0, 0.0, 85.0, 10.0),+ 0,+ font_signature=("Heading", 0),+ font_coverage=1.0,+ ),+ _text_line("Alpha begins", (0.0, 20.0, 100.0, 30.0), 1, font_signature=body_font, font_coverage=1.0),+ _text_line(+ "alpha italic continuation",+ (15.0, 30.0, 100.0, 40.0),+ 2,+ font_signature=italic_font,+ font_coverage=1.0,+ ),+ _text_line("alpha closes", (15.0, 40.0, 70.0, 50.0), 3, font_signature=body_font, font_coverage=1.0),+ _text_line("Beta begins", (0.0, 50.0, 100.0, 60.0), 4, font_signature=body_font, font_coverage=1.0),+ _text_line("beta continues", (15.0, 60.0, 100.0, 70.0), 5, font_signature=body_font, font_coverage=1.0),+ _text_line("Gamma begins", (0.0, 70.0, 100.0, 80.0), 6, font_signature=body_font, font_coverage=1.0),+ _text_line("gamma continues", (15.0, 80.0, 100.0, 90.0), 7, font_signature=body_font, font_coverage=1.0),+ ]+ lane = models._TextLane(+ left=0.0,+ right=100.0,+ lines=[(line, line.bbox) for line in lines],+ )++ group_map = text_blocks._build_hanging_indent_group_map(lane, [], [])+ blocks = text_blocks._build_text_blocks(lines, [], (120.0, 120.0))++ assert 0 not in group_map+ assert [group_map[index] for index in range(1, 8)] == [0, 0, 0, 1, 1, 2, 2]+ assert [block["content"] for block in blocks] == [+ "Centered heading",+ "Alpha begins alpha italic continuation alpha closes",+ "Beta begins beta continues",+ "Gamma begins gamma continues",+ ]+++def test_hanging_indent_accepts_reference_spacing_and_italic_tail() -> None:+ """验证 1.25 倍行高的参考文献间距不会拆掉前一条斜体尾行。"""++ body_font = ("Body", 0)+ lines = [+ _text_line(+ "Alpha begins",+ (0.0, 0.0, 100.0, 10.0),+ 0,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line(+ "alpha continues",+ (15.0, 10.0, 100.0, 20.0),+ 1,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line(+ "alpha italic tail",+ (15.0, 20.0, 75.0, 30.0),+ 2,+ font_signature=("BodyItalic", 1),+ font_coverage=1.0,+ ),+ _text_line(+ "Beta begins",+ (0.0, 42.5, 100.0, 52.5),+ 3,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line(+ "beta continues",+ (15.0, 52.5, 100.0, 62.5),+ 4,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line(+ "Gamma begins",+ (0.0, 75.0, 100.0, 85.0),+ 5,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line(+ "gamma continues",+ (15.0, 85.0, 100.0, 95.0),+ 6,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ ]+ lane = models._TextLane(+ left=0.0,+ right=100.0,+ lines=[(line, line.bbox) for line in lines],+ )++ group_map = text_blocks._build_hanging_indent_group_map(lane, [], [])+ blocks = text_blocks._build_text_blocks(lines, [], (120.0, 120.0))++ assert [group_map[index] for index in range(7)] == [0, 0, 0, 1, 1, 2, 2]+ assert [block["content"] for block in blocks] == [+ "Alpha begins alpha continues alpha italic tail",+ "Beta begins beta continues",+ "Gamma begins gamma continues",+ ]+++def test_first_line_indent_and_large_gap_do_not_form_hanging_indent_groups() -> None:+ """验证普通首行缩进及跨越大间距的行不会误触发悬挂缩进模式。"""++ lines = [+ _text_line("First paragraph", (15.0, 0.0, 100.0, 10.0), 0),+ _text_line("first continuation", (0.0, 10.0, 100.0, 20.0), 1),+ _text_line("Second paragraph", (15.0, 20.0, 100.0, 30.0), 2),+ _text_line("second continuation", (0.0, 30.0, 100.0, 40.0), 3),+ _text_line("Detached start", (0.0, 70.0, 100.0, 80.0), 4),+ _text_line("detached continuation", (15.0, 80.0, 100.0, 90.0), 5),+ ]+ lane = models._TextLane(+ left=0.0,+ right=100.0,+ lines=[(line, line.bbox) for line in lines],+ )++ assert text_blocks._build_hanging_indent_group_map(lane, [], []) == {}+++def test_twelve_point_gutter_keeps_two_text_lanes_and_paragraphs_separate() -> None:+ """验证约 12pt 行高和栏沟仍识别为双栏,左右正文不会交叉拼接。"""++ lines: list[models._LineItem] = []+ for row_index, top in enumerate((100.0, 112.0, 124.0)):+ lines.extend(+ [+ _text_line(f"left-{row_index}", (49.0, top, 300.0, top + 12.0), row_index * 2),+ _text_line(f"right-{row_index}", (312.0, top, 563.0, top + 12.0), row_index * 2 + 1),+ ]+ )++ lanes = line_layout._infer_text_lanes(+ [(line, line.bbox) for line in lines],+ 612.0,+ 12.0,+ )+ blocks = text_blocks._build_text_blocks(lines, [], (612.0, 792.0))++ regular_lanes = [lane for lane in lanes if not lane.is_span]+ assert [(lane.left, lane.right) for lane in regular_lanes] == [+ (49.0, 300.0),+ (312.0, 563.0),+ ]+ assert len(blocks) == 2+ assert all("right-" not in block["content"] for block in blocks if "left-" in block["content"])+ assert all("left-" not in block["content"] for block in blocks if "right-" in block["content"])+++def test_cross_column_caption_tail_stays_in_span_lane_and_one_text_block() -> None:+ """验证仅占单栏宽的短 caption 尾行仍回收到连续跨栏 caption。"""++ lines: list[models._LineItem] = [+ _text_line("caption line one", (0.0, 10.0, 200.0, 20.0), 0),+ _text_line("caption line two", (0.0, 22.0, 200.0, 32.0), 1),+ _text_line("caption tail", (0.0, 34.0, 70.0, 44.0), 2),+ _text_line("ordinary left short line", (0.0, 70.0, 70.0, 80.0), 3),+ ]+ for row_index, top in enumerate((100.0, 112.0, 124.0, 136.0, 148.0)):+ lines.extend(+ [+ _text_line(+ f"left body {row_index}",+ (0.0, top, 90.0, top + 10.0),+ 4 + 2 * row_index,+ ),+ _text_line(+ f"right body {row_index}",+ (110.0, top, 200.0, top + 10.0),+ 5 + 2 * row_index,+ ),+ ]+ )++ lanes = line_layout._infer_text_lanes(+ [(line, line.bbox) for line in lines],+ 200.0,+ 10.0,+ )+ blocks = text_blocks._build_text_blocks(lines, [], (200.0, 180.0))++ span_lane = next(lane for lane in lanes if lane.is_span)+ assert {line.source_index for line, _bbox in span_lane.lines} == {0, 1, 2}+ assert all(line.source_index != 3 for line, _bbox in span_lane.lines)+ caption_blocks = [block for block in blocks if "caption line one" in block["content"]]+ assert len(caption_blocks) == 1+ assert "caption tail" in caption_blocks[0]["content"]+++def test_slight_bbox_overlap_contributes_to_gap_estimate_and_separates_caption() -> None:+ """验证轻微纵向重叠按零净空统计,短图例不会与后续长 caption 合并。"""++ body_lines = [+ _text_line("body-0", (312.0, 0.0, 563.0, 12.0), 0),+ _text_line("body-1", (312.0, 11.95, 563.0, 23.95), 1),+ _text_line("body-2", (312.0, 23.9, 563.0, 35.9), 2),+ ]+ legend = _text_line("Right camera", (458.0, 60.0, 509.0, 72.0), 3)+ caption = _text_line(+ "Figure 1: a long caption spanning the full column",+ (312.0, 79.0, 563.0, 91.0),+ 4,+ )+ lane = models._TextLane(+ left=312.0,+ right=563.0,+ lines=[*((line, line.bbox) for line in body_lines), (legend, legend.bbox), (caption, caption.bbox)],+ )++ regular_gap, gap_mad = line_layout._estimate_lane_gap(lane)++ assert (regular_gap, gap_mad) == (0.0, 0.0)+ assert not line_layout._should_connect_text_rows(+ (legend, legend.bbox),+ (caption, caption.bbox),+ lane,+ regular_gap,+ gap_mad,+ [],+ [],+ )+++def test_local_previous_left_edge_exposes_first_line_indent() -> None:+ """验证局部版心左移后仍能识别下一行相对前一物理行的首行缩进。"""++ previous = _text_line(+ "previous paragraph without punctuation",+ (0.0, 0.0, 80.0, 10.0),+ 0,+ )+ current = _text_line(+ "Indented new paragraph",+ (10.0, 12.0, 100.0, 22.0),+ 1,+ )+ lane = models._TextLane(+ left=20.0,+ right=100.0,+ lines=[(previous, previous.bbox), (current, current.bbox)],+ )++ assert not line_layout._should_connect_text_rows(+ (previous, previous.bbox),+ (current, current.bbox),+ lane,+ 2.0,+ 0.0,+ [],+ [],+ )+++def test_terminal_full_lane_row_breaks_after_abnormal_clearance() -> None:+ """验证满栏句末行后的净空超过常规间距半行高时强制另起段落。"""++ previous = _text_line("Figure caption ends.", (0.0, 0.0, 100.0, 10.0), 0)+ current = _text_line("new paragraph fills the lane", (0.0, 17.0, 100.0, 27.0), 1)+ lane = models._TextLane(+ left=0.0,+ right=100.0,+ lines=[(previous, previous.bbox), (current, current.bbox)],+ )++ assert not line_layout._should_connect_text_rows(+ (previous, previous.bbox),+ (current, current.bbox),+ lane,+ 1.0,+ 0.0,+ [],+ [],+ )+++def test_effective_height_connects_body_line_after_tall_math_glyph() -> None:+ """验证高数学字形拉长原始 bbox 时仍按有效行高连接下一正文行。"""++ previous = _text_line(+ "support window Ωp centered at the pixel",+ (312.0, 100.0, 563.0, 118.82),+ 0,+ effective_height=12.0,+ )+ current = _text_line(+ "by",+ (312.0, 112.0, 325.0, 124.0),+ 1,+ effective_height=12.0,+ )+ lane = models._TextLane(+ left=312.0,+ right=563.0,+ lines=[(previous, previous.bbox), (current, current.bbox)],+ )++ assert current.bbox[1] - previous.bbox[3] == pytest.approx(-6.82)+ assert line_layout._effective_text_row_gap(+ (previous, previous.bbox),+ (current, current.bbox),+ ) == pytest.approx(0.0)+ assert line_layout._should_connect_text_rows(+ (previous, previous.bbox),+ (current, current.bbox),+ lane,+ 0.0,+ 0.0,+ [],+ [],+ )+++def test_inline_scripts_and_touching_low_coverage_runs_are_recovered() -> None:+ """验证紧贴上下标与低覆盖率同行后缀恢复,同时保留外置公式编号。"""++ script_lines = [+ _text_line("O(ω", (0.0, 0.0, 100.0, 18.8), 0, visual_row_id=0, effective_height=12.0),+ _text_line("2", (100.3, 0.8, 104.0, 7.0), 1, visual_row_id=1, effective_height=6.0),+ _text_line("Di", (0.0, 40.0, 100.0, 52.0), 2, visual_row_id=2, effective_height=12.0),+ _text_line("p", (96.9, 46.0, 101.0, 53.0), 3, visual_row_id=3, effective_height=7.0),+ ]++ merged_scripts = native_text._merge_native_inline_scripts(script_lines, (200.0, 100.0))++ assert [line.text for line in merged_scripts] == ["O(ω2", "Dip"]++ caption_prefix = _text_line(+ "(4",+ (0.0, 70.0, 12.0, 82.0),+ 4,+ font_signature=("Body", 0),+ font_coverage=1.0,+ )+ caption_suffix = _text_line(+ "th row).",+ (12.1, 70.0, 50.0, 82.0),+ 5,+ font_signature=("Body", 0),+ font_coverage=0.7,+ )+ formula_body = _text_line(+ "formula",+ (0.0, 90.0, 50.0, 102.0),+ 6,+ font_signature=("Math", 0),+ font_coverage=1.0,+ )+ formula_number = _text_line(+ "(4)",+ (51.2, 90.0, 60.0, 102.0),+ 7,+ font_signature=("Body", 0),+ font_coverage=1.0,+ )++ assert line_merging._can_merge_same_baseline_pair(+ caption_prefix,+ caption_prefix.bbox,+ caption_suffix,+ caption_suffix.bbox,+ [],+ )+ assert not line_merging._can_merge_same_baseline_pair(+ formula_body,+ formula_body.bbox,+ formula_number,+ formula_number.bbox,+ [],+ )+++def test_full_lane_large_height_mismatch_only_recovers_aligned_continuation() -> None:+ """验证满栏混合字体 URL 可续接,而短公式与显式字体样式边界仍分离。"""++ previous = _text_line(+ "video sequences have been made avail-",+ (0.0, 0.0, 100.0, 12.0),+ 0,+ effective_height=12.0,+ font_signature=("Body", 0),+ font_coverage=1.0,+ )+ full_width_url = _text_line(+ "able at http://example.test/data",+ (0.0, 12.0, 100.0, 24.0),+ 1,+ effective_height=7.69,+ font_signature=("Mono", 0),+ font_coverage=1.0,+ )+ short_formula = _text_line(+ "x = 1",+ (0.0, 12.0, 60.0, 24.0),+ 2,+ effective_height=7.69,+ font_signature=("Math", 0),+ font_coverage=1.0,+ )+ styled_reference = _text_line(+ "italic bibliography continuation",+ (0.0, 12.0, 100.0, 24.0),+ 3,+ effective_height=7.69,+ font_signature=("BodyItalic", 1),+ font_coverage=1.0,+ )+ lane = models._TextLane(left=0.0, right=100.0)++ assert line_layout._should_connect_text_rows(+ (previous, previous.bbox),+ (full_width_url, full_width_url.bbox),+ lane,+ 0.0,+ 0.0,+ [],+ [],+ )+ assert not line_layout._should_connect_text_rows(+ (previous, previous.bbox),+ (short_formula, short_formula.bbox),+ lane,+ 0.0,+ 0.0,+ [],+ [],+ )+ assert not line_layout._should_connect_text_rows(+ (previous, previous.bbox),+ (styled_reference, styled_reference.bbox),+ lane,+ 0.0,+ 0.0,+ [],+ [],+ )+++def test_smaller_footnote_after_abnormal_gap_forces_text_block_break() -> None:+ """验证字号不足前行 88% 且净空偏大时,正文与脚注强制分块。"""++ body = _text_line(+ "body continuation",+ (0.0, 0.0, 100.0, 10.0),+ 0,+ effective_height=10.0,+ font_signature=("Body", 0),+ font_coverage=1.0,+ )+ footnote = _text_line(+ "small footnote",+ (0.0, 16.0, 100.0, 24.7),+ 1,+ effective_height=8.7,+ font_signature=("Body", 0),+ font_coverage=1.0,+ )+ lane = models._TextLane(+ left=0.0,+ right=100.0,+ lines=[(body, body.bbox), (footnote, footnote.bbox)],+ )++ assert not line_layout._should_connect_text_rows(+ (body, body.bbox),+ (footnote, footnote.bbox),+ lane,+ 3.0,+ 0.0,+ [],+ [],+ )++diff --git a/tests/unittest/test_flash_pdf_titles.py b/tests/unittest/test_flash_pdf_titles.pynew file mode 100644index 00000000..167509ca--- /dev/null+++ b/tests/unittest/test_flash_pdf_titles.py@@ -0,0 +1,487 @@+from __future__ import annotations++import inspect++import pytest++from mineru.backend.flash.native_pdf import (+ line_layout,+ line_merging,+ text_blocks,+ titles,+)+++from _flash_pdf_test_utils import (+ _text_line,+)++[email protected]("heading_text", ["1. INTRODUCTION", "completely unrelated words"])+def test_paragraph_title_classification_is_independent_of_heading_content(heading_text: str) -> None:+ """验证相同版式和字体的不同内容得到完全相同的段落标题类型。"""++ body_font = ("Body", 0)+ heading_font = ("Heading", 1)+ lines = [+ _text_line("body one", (0.0, 10.0, 100.0, 20.0), 0, font_signature=body_font, font_coverage=1.0),+ _text_line("body two", (0.0, 22.0, 100.0, 32.0), 1, font_signature=body_font, font_coverage=1.0),+ _text_line(heading_text, (0.0, 45.0, 40.0, 55.0), 2, font_signature=heading_font, font_coverage=1.0),+ _text_line("body three", (0.0, 68.0, 100.0, 78.0), 3, font_signature=body_font, font_coverage=1.0),+ _text_line("body four", (0.0, 80.0, 100.0, 90.0), 4, font_signature=body_font, font_coverage=1.0),+ _text_line("body five", (0.0, 92.0, 100.0, 102.0), 5, font_signature=body_font, font_coverage=1.0),+ ]++ titles._classify_page_titles(lines, (100.0, 150.0), page_index=1, container_bboxes=[])++ assert lines[2].semantic_type == "paragraph_title"+++def test_heading_like_content_with_body_layout_remains_text() -> None:+ """验证标题式字符串在正文几何、正文字体和常规行距下仍保持普通文本。"""++ body_font = ("Body", 0)+ lines = [+ _text_line(+ f"body {index}",+ (0.0, 10.0 + 12.0 * index, 100.0, 20.0 + 12.0 * index),+ index,+ font_signature=body_font,+ font_coverage=1.0,+ )+ for index in range(6)+ ]+ lines[2].text = "1. INTRODUCTION"++ titles._classify_page_titles(lines, (100.0, 120.0), page_index=1, container_bboxes=[])++ assert lines[2].semantic_type is None+++def test_centered_smaller_paragraph_title_uses_layout_contrast_only() -> None:+ """验证同字体的小字号居中标题可由栏宽和上下留白识别。"""++ body_font = ("Body", 0)+ lines = [+ _text_line("body one", (0.0, 10.0, 100.0, 20.0), 0, font_signature=body_font, font_coverage=1.0),+ _text_line("body two", (0.0, 22.0, 100.0, 32.0), 1, font_signature=body_font, font_coverage=1.0),+ _text_line(+ "neutral label",+ (30.0, 45.0, 70.0, 53.0),+ 2,+ effective_height=8.0,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line("body three", (0.0, 66.0, 100.0, 76.0), 3, font_signature=body_font, font_coverage=1.0),+ _text_line("body four", (0.0, 78.0, 100.0, 88.0), 4, font_signature=body_font, font_coverage=1.0),+ _text_line("body five", (0.0, 90.0, 100.0, 100.0), 5, font_signature=body_font, font_coverage=1.0),+ ]++ titles._classify_page_titles(lines, (100.0, 150.0), page_index=1, container_bboxes=[])++ assert lines[2].semantic_type == "paragraph_title"+++def test_multiline_document_title_does_not_absorb_author_line() -> None:+ """验证首页两行大字号标题合并为文档标题,较小作者行保持普通文本。"""++ body_font = ("Body", 0)+ title_font = ("Title", 0)+ lines = [+ _text_line(+ "title line one",+ (15.0, 20.0, 85.0, 34.4),+ 0,+ effective_height=14.4,+ font_signature=title_font,+ font_coverage=1.0,+ ),+ _text_line(+ "title line two",+ (10.0, 33.8, 90.0, 48.2),+ 1,+ effective_height=14.4,+ font_signature=title_font,+ font_coverage=1.0,+ ),+ _text_line(+ "author names",+ (20.0, 60.0, 80.0, 69.1),+ 2,+ effective_height=9.1,+ font_signature=title_font,+ font_coverage=1.0,+ ),+ _text_line("body one", (0.0, 110.0, 100.0, 120.0), 3, font_signature=body_font, font_coverage=1.0),+ _text_line("body two", (0.0, 122.0, 100.0, 132.0), 4, font_signature=body_font, font_coverage=1.0),+ _text_line("body three", (0.0, 134.0, 100.0, 144.0), 5, font_signature=body_font, font_coverage=1.0),+ ]++ titles._classify_page_titles(lines, (100.0, 200.0), page_index=0, container_bboxes=[])++ assert [line.semantic_type for line in lines[:3]] == ["doc_title", "doc_title", None]+++def test_cross_column_document_title_uses_thirteen_tenths_body_height_fallback() -> None:+ """验证首页跨栏居中标题达到正文 1.30 倍时可命中,作者行保持正文类型。"""++ body_font = ("Body", 0)+ title_font = ("Title", 0)+ lines = [+ _text_line(+ "wide title",+ (20.0, 20.0, 180.0, 33.0),+ 0,+ effective_height=13.0,+ font_signature=title_font,+ font_coverage=1.0,+ ),+ _text_line(+ "author row",+ (60.0, 42.0, 140.0, 52.0),+ 1,+ effective_height=10.0,+ font_signature=title_font,+ font_coverage=1.0,+ ),+ ]+ for row_index, top in enumerate((80.0, 92.0, 104.0, 116.0)):+ lines.extend(+ [+ _text_line(+ f"left body {row_index}",+ (10.0, top, 90.0, top + 10.0),+ 2 + row_index * 2,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line(+ f"right body {row_index}",+ (110.0, top, 190.0, top + 10.0),+ 3 + row_index * 2,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ ]+ )++ titles._classify_page_titles(+ lines,+ (200.0, 200.0),+ page_index=0,+ container_bboxes=[],+ )++ assert lines[0].semantic_type == "doc_title"+ assert lines[1].semantic_type != "paragraph_title"+++def test_complete_visual_row_promotes_number_and_demotes_inline_body() -> None:+ """验证同字体编号整行晋升,标题字体与正文同排时整行降级并重新合并。"""++ body_font = ("Body", 0)+ title_font = ("Title", 0)+ lines = [+ _text_line("body one", (0.0, 5.0, 100.0, 15.0), 0, font_signature=body_font, font_coverage=1.0),+ _text_line("body two", (0.0, 17.0, 100.0, 27.0), 1, font_signature=body_font, font_coverage=1.0),+ _text_line(+ "2",+ (0.0, 42.0, 8.0, 52.0),+ 2,+ visual_row_id=20,+ split_from_row=True,+ font_signature=title_font,+ font_coverage=1.0,+ dominant_font_weight=700.0,+ ),+ _text_line(+ "neutral heading",+ (15.0, 42.0, 60.0, 52.0),+ 3,+ visual_row_id=20,+ split_from_row=True,+ font_signature=title_font,+ font_coverage=1.0,+ dominant_font_weight=700.0,+ ),+ _text_line("body three", (0.0, 65.0, 100.0, 75.0), 4, font_signature=body_font, font_coverage=1.0),+ _text_line(+ "inline label",+ (0.0, 82.0, 32.0, 92.0),+ 5,+ visual_row_id=30,+ split_from_row=True,+ font_signature=title_font,+ font_coverage=1.0,+ dominant_font_weight=700.0,+ ),+ _text_line(+ "inline body",+ (34.0, 82.0, 100.0, 92.0),+ 6,+ visual_row_id=30,+ split_from_row=True,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line("body four", (0.0, 94.0, 100.0, 104.0), 7, font_signature=body_font, font_coverage=1.0),+ ]++ titles._classify_page_titles(+ lines,+ (100.0, 140.0),+ page_index=1,+ container_bboxes=[],+ )+ merged = line_merging._merge_title_resolved_visual_rows(lines, (100.0, 140.0))++ numbered_title = next(line for line in merged if line.visual_row_id == 20)+ inline_row = next(line for line in merged if line.visual_row_id == 30)+ assert numbered_title.semantic_type == "paragraph_title"+ assert numbered_title.text == "2 neutral heading"+ assert inline_row.semantic_type is None+ assert inline_row.text == "inline label inline body"+++def test_low_coverage_mixed_weight_visual_row_demotes_inline_title() -> None:+ """验证低字体覆盖率的同一视觉行仍按字重冲突识别为行内粗体正文。"""++ body_font = ("Body", 0)+ lines = [+ _text_line(+ "body one",+ (0.0, 0.0, 100.0, 10.0),+ 0,+ font_signature=body_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ _text_line(+ "body two",+ (0.0, 12.0, 100.0, 22.0),+ 1,+ font_signature=body_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ _text_line(+ "body three",+ (0.0, 24.0, 100.0, 34.0),+ 2,+ font_signature=body_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ _text_line(+ "inline label",+ (0.0, 50.0, 35.0, 62.0),+ 3,+ visual_row_id=30,+ split_from_row=True,+ font_signature=("Heading", 0),+ font_coverage=0.6,+ dominant_font_weight=700.0,+ ),+ _text_line(+ "inline body",+ (37.0, 50.0, 100.0, 62.0),+ 4,+ visual_row_id=30,+ run_index=1,+ split_from_row=True,+ font_signature=body_font,+ font_coverage=0.6,+ dominant_font_weight=400.0,+ ),+ _text_line(+ "body continuation",+ (0.0, 64.0, 100.0, 74.0),+ 5,+ font_signature=body_font,+ font_coverage=1.0,+ dominant_font_weight=400.0,+ ),+ ]++ titles._classify_page_titles(+ lines,+ (100.0, 100.0),+ page_index=1,+ container_bboxes=[],+ )+ merged = line_merging._merge_title_resolved_visual_rows(lines, (100.0, 100.0))++ inline_row = next(line for line in merged if line.visual_row_id == 30)+ assert inline_row.semantic_type is None+ assert inline_row.text == "inline label inline body"+++def test_full_width_normal_height_inline_heading_merges_with_body_continuation() -> None:+ """验证满栏正常字号粗体行降为正文,并只与其下方常规正文续接。"""++ body_font = ("Body", 0)+ heading_font = ("Heading", 1)+ lines = [+ _text_line("body one", (0.0, 0.0, 100.0, 10.0), 0, font_signature=body_font, font_coverage=1.0),+ _text_line("body two", (0.0, 12.0, 100.0, 22.0), 1, font_signature=body_font, font_coverage=1.0),+ _text_line(+ "inline heading",+ (0.0, 40.0, 100.0, 50.0),+ 2,+ font_signature=heading_font,+ font_coverage=1.0,+ dominant_font_weight=700.0,+ ),+ _text_line(+ "continuation one",+ (0.0, 52.0, 100.0, 62.0),+ 3,+ effective_height=8.0,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line("continuation two", (0.0, 64.0, 100.0, 74.0), 4, font_signature=body_font, font_coverage=1.0),+ _text_line("continuation three", (0.0, 76.0, 100.0, 86.0), 5, font_signature=body_font, font_coverage=1.0),+ ]++ titles._classify_page_titles(+ lines,+ (100.0, 120.0),+ page_index=1,+ container_bboxes=[],+ )+ blocks = text_blocks._build_text_blocks(lines, [], (100.0, 120.0))++ inline_block = next(block for block in blocks if block["content"].startswith("inline heading"))+ assert lines[2].semantic_type is None+ assert inline_block["type"] == "text"+ assert "continuation one" in inline_block["content"]+ assert "body two" not in inline_block["content"]+++def test_dense_same_font_two_run_row_requires_complete_high_occupancy_geometry() -> None:+ """验证双 run 正文仅在同字体、同基线、连续编号且占用充分时恢复。"""++ body_font = ("Body", 0)+ dense_members = [+ _text_line(+ "left",+ (0.0, 0.0, 48.0, 10.0),+ 0,+ visual_row_id=10,+ run_index=0,+ split_from_row=True,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line(+ "right",+ (52.0, 0.0, 100.0, 10.0),+ 1,+ visual_row_id=10,+ run_index=1,+ split_from_row=True,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ ]+ sparse_members = [+ _text_line(+ "sparse left",+ (0.0, 20.0, 30.0, 30.0),+ 2,+ visual_row_id=20,+ run_index=0,+ split_from_row=True,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line(+ "sparse right",+ (70.0, 20.0, 100.0, 30.0),+ 3,+ visual_row_id=20,+ run_index=1,+ split_from_row=True,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ ]+ partial_formula_row = [+ _text_line(+ "formula body",+ (0.0, 40.0, 48.0, 50.0),+ 4,+ visual_row_id=30,+ run_index=0,+ split_from_row=True,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line(+ "sidecar",+ (52.0, 40.0, 100.0, 50.0),+ 5,+ visual_row_id=30,+ run_index=2,+ split_from_row=True,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ ]+ different_font_members = [+ dense_members[0],+ _text_line(+ "different",+ (52.0, 0.0, 100.0, 10.0),+ 6,+ visual_row_id=10,+ run_index=1,+ split_from_row=True,+ font_signature=("Math", 0),+ font_coverage=1.0,+ ),+ ]++ assert line_merging._is_dense_same_font_two_run_row(dense_members, (100.0, 100.0))+ assert not line_merging._is_dense_same_font_two_run_row(sparse_members, (100.0, 100.0))+ assert not line_merging._is_dense_same_font_two_run_row(partial_formula_row, (100.0, 100.0))+ assert not line_merging._is_dense_same_font_two_run_row(different_font_members, (100.0, 100.0))++ merged = line_merging._merge_title_resolved_visual_rows(+ dense_members + sparse_members,+ (100.0, 100.0),+ )+ assert [line.text for line in merged if line.visual_row_id == 10] == ["left right"]+ assert len([line for line in merged if line.visual_row_id == 20]) == 2+++def test_paragraph_title_detector_does_not_read_line_text() -> None:+ """守卫段落标题候选、打分和邻行扩展不读取文本内容。"""++ source = "\n".join(+ inspect.getsource(function)+ for function in (+ titles._classify_page_titles,+ titles._infer_lane_body_profile,+ titles._classify_document_title,+ titles._document_title_uses_page_fallback,+ titles._classify_paragraph_titles_in_lane,+ titles._visual_row_has_body_style_sibling,+ titles._is_near_full_mixed_inline_row,+ titles._is_full_width_inline_heading,+ titles._has_following_body_row,+ titles._unify_visual_row_title_types,+ titles._protect_front_matter_title_types,+ titles._infer_front_matter_boundary,+ titles._normalized_title_gap,+ titles._line_near_visual_container,+ line_layout._title_fonts_compatible,+ titles._expand_paragraph_title_neighbors,+ )+ )++ assert ".text" not in source++