Skip to content

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

fix: refine Flash layout for Chinese paper samples

myhlolia5a9fd491e81
diff --git "a/demo/pdfs/\344\270\255\346\226\207\350\256\272\346\226\2073.pdf" "b/demo/pdfs/\344\270\255\346\226\207\350\256\272\346\226\2073.pdf"
new file mode 100644
index 00000000..5544377a
Binary files /dev/null and "b/demo/pdfs/\344\270\255\346\226\207\350\256\272\346\226\2073.pdf" differ
diff --git "a/demo/pdfs/\344\270\255\346\226\207\350\256\272\346\226\2074.pdf" "b/demo/pdfs/\344\270\255\346\226\207\350\256\272\346\226\2074.pdf"
new file mode 100644
index 00000000..5cbda75d
Binary files /dev/null and "b/demo/pdfs/\344\270\255\346\226\207\350\256\272\346\226\2074.pdf" differ
diff --git a/mineru/model/flash/pdf/formulas.py b/mineru/model/flash/pdf/formulas.py
index 66a41d5f..d9a757c2 100644
--- a/mineru/model/flash/pdf/formulas.py
+++ b/mineru/model/flash/pdf/formulas.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import re
import statistics
+import unicodedata
from dataclasses import dataclass, replace
from typing import Any
@@ -564,15 +565,8 @@ def _build_formula_like_blocks(
if block is None:
continue
blocks.append(block)
- claimed_source_indices.update(
- member_line.source_index
- for member_line, _member_bbox in members
- )
- lane.lines = [
- item
- for item in lane.lines
- if item[0].source_index not in claimed_source_indices
- ]
+ claimed_source_indices.update(member_line.source_index for member_line, _member_bbox in members)
+ lane.lines = [item for item in lane.lines if item[0].source_index not in claimed_source_indices]
for line, bbox in list(lane.lines):
if (
(
@@ -652,6 +646,14 @@ def _build_formula_like_blocks(
dominant_body_font,
median_height,
)
+ if _formula_component_has_left_prose(
+ members,
+ lane,
+ median_height,
+ ):
+ for member_line, _member_bbox in members:
+ member_line.paragraph_formula_context = True
+ continue
if len(members) < 2:
continue
if (
@@ -692,7 +694,10 @@ def _build_formula_like_blocks(
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 and not line.formula_candidate_only
+ line
+ for line in lines
+ if line.source_index not in claimed_source_indices
+ and (not line.formula_candidate_only or line.paragraph_formula_context)
]
return blocks, remaining_lines
@@ -703,6 +708,42 @@ def _formula_line_has_math_operator(text: str) -> bool:
return any(character in _FORMULA_OPERATOR_CHARS for character in text)
+def _formula_component_has_left_prose(
+ members: list[tuple[_LineItem, BBox]],
+ lane: _TextLane,
+ median_height: float,
+) -> bool:
+ """识别贴栏左缘且在首个运算符前带正文引导语的伪行间公式。"""
+
+ for line, bbox in members:
+ if abs(bbox[0] - lane.left) > 0.75 * median_height:
+ continue
+ normalized = unicodedata.normalize("NFKC", line.text).strip()
+ operator_positions = [index for index, character in enumerate(normalized) if character in _FORMULA_OPERATOR_CHARS]
+ if not operator_positions:
+ continue
+ prefix = normalized[: min(operator_positions)]
+ han_count = len(re.findall(r"[\u3400-\u9fff]", prefix))
+ has_clause_punctuation = (
+ re.search(
+ r"[,;:。!?!?))]",
+ prefix,
+ )
+ is not None
+ )
+ has_english_lead = (
+ re.search(
+ r"\b(?:where|when|with|given|using|denote[ds]?|defined)\b",
+ prefix,
+ re.IGNORECASE,
+ )
+ is not None
+ )
+ if (han_count >= 2 and has_clause_punctuation) or has_english_lead:
+ return True
+ return False
+
+
def _is_wide_tagged_formula_member(
anchor_line: _LineItem,
member_line: _LineItem,
@@ -736,20 +777,13 @@ def _is_single_line_numbered_formula(
if parts is None:
return False
prefix, marker = parts
- if (
- not prefix
- or not _FORMULA_NUMBER_MARKER_RE.fullmatch(marker)
- or not _formula_line_has_math_operator(prefix)
- ):
+ if not prefix or not _FORMULA_NUMBER_MARKER_RE.fullmatch(marker) or not _formula_line_has_math_operator(prefix):
return False
lane_width = max(0.1, lane.right - lane.left)
width_ratio = (bbox[2] - bbox[0]) / lane_width
if not 0.12 <= width_ratio <= 0.98:
return False
- if (
- abs(_bbox_center_x(bbox) - 0.5 * (lane.left + lane.right))
- > 0.2 * lane_width
- ):
+ if abs(_bbox_center_x(bbox) - 0.5 * (lane.left + lane.right)) > 0.2 * lane_width:
return False
if bbox[3] - bbox[1] > 4.0 * median_height:
return False
@@ -1571,44 +1605,24 @@ def _is_formula_body_barrier(
line.font_signature == dominant_body_font
and line.font_coverage >= 0.75
and bbox[2] - bbox[0] >= 0.3 * lane_width
- and 0.8 * median_height
- <= line_height
- <= 1.25 * median_height
+ and 0.8 * median_height <= line_height <= 1.25 * median_height
)
lane_width = max(0.1, lane.right - lane.left)
body_style_scales = [
_line_style_scale(other_line, other_bbox)
for other_line, other_bbox in lane.lines
- if other_bbox[2] - other_bbox[0] >= 0.35 * lane_width
- and not _formula_line_has_math_operator(other_line.text)
+ if other_bbox[2] - other_bbox[0] >= 0.35 * lane_width and not _formula_line_has_math_operator(other_line.text)
]
- body_scale = (
- statistics.median(body_style_scales)
- if body_style_scales
- else median_height
- )
+ body_scale = statistics.median(body_style_scales) if body_style_scales else median_height
line_scale = _line_style_scale(line, bbox)
line_width = bbox[2] - bbox[0]
- left_aligned = (
- abs(bbox[0] - lane.left)
- <= max(3.0, 0.75 * body_scale)
- )
+ left_aligned = abs(bbox[0] - lane.left) <= max(3.0, 0.75 * body_scale)
return (
not _formula_line_has_math_operator(line.text)
- and (
- line_width >= 0.3 * lane_width
- or (
- left_aligned
- and line_width >= 0.08 * lane_width
- )
- )
+ and (line_width >= 0.3 * lane_width or (left_aligned and line_width >= 0.08 * lane_width))
and 0.75 * body_scale <= line_scale <= 1.35 * body_scale
and (
- (
- dominant_body_font is not None
- and line.font_signature == dominant_body_font
- and line.font_coverage >= 0.75
- )
+ (dominant_body_font is not None and line.font_signature == dominant_body_font and line.font_coverage >= 0.75)
or left_aligned
)
)
@@ -1658,17 +1672,12 @@ def _is_formula_body_prefix(
return False
if abs(bbox[0] - lane.left) > max(3.0, 0.75 * median_height):
return False
- if (
- not line.style_scale_repaired
- and not anchor_line.style_scale_repaired
- ):
+ if not line.style_scale_repaired and not anchor_line.style_scale_repaired:
return (
dominant_body_font is not None
and line.font_signature == dominant_body_font
and line.font_coverage >= minimum_font_coverage
- and 0.8 * median_height
- <= line_height
- <= 1.25 * median_height
+ and 0.8 * median_height <= line_height <= 1.25 * median_height
)
lane_width = max(0.1, lane.right - lane.left)
if bbox[2] - bbox[0] < 0.08 * lane_width:
@@ -1679,23 +1688,13 @@ def _is_formula_body_prefix(
_line_style_scale(other_line, other_bbox)
for other_line, other_bbox in lane.lines
if other_bbox[2] - other_bbox[0] >= 0.35 * lane_width
- and abs(other_bbox[0] - lane.left)
- <= max(3.0, 0.75 * median_height)
+ and abs(other_bbox[0] - lane.left) <= max(3.0, 0.75 * median_height)
and not _formula_line_has_math_operator(other_line.text)
]
- body_scale = (
- statistics.median(body_style_scales)
- if body_style_scales
- else median_height
- )
+ body_scale = statistics.median(body_style_scales) if body_style_scales else median_height
line_scale = _line_style_scale(line, bbox)
- return (
- 0.75 * body_scale <= line_scale <= 1.35 * body_scale
- and (
- dominant_body_font is None
- or line.font_signature == dominant_body_font
- or line.font_coverage <= minimum_font_coverage
- )
+ return 0.75 * body_scale <= line_scale <= 1.35 * body_scale and (
+ dominant_body_font is None or line.font_signature == dominant_body_font or line.font_coverage <= minimum_font_coverage
)
diff --git a/mineru/model/flash/pdf/graphics.py b/mineru/model/flash/pdf/graphics.py
index 30d4ee03..2ad2fab0 100644
--- a/mineru/model/flash/pdf/graphics.py
+++ b/mineru/model/flash/pdf/graphics.py
@@ -75,11 +75,7 @@ def _form_supersedes_nested_bbox(form_bbox: BBox, nested_bbox: BBox) -> bool:
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
- )
+ return form_area > 0 and nested_area < 0.5 * form_area and _bbox_overlap_in_first(nested_bbox, form_bbox) >= 0.9
def _tighten_form_image_bbox(
@@ -91,8 +87,7 @@ def _tighten_form_image_bbox(
internal_paths = [
path_info.bbox
for path_info in source.path_infos
- if path_info.form_depth > 0
- and _bbox_overlap_in_first(path_info.bbox, form_bbox) >= 0.9
+ if path_info.form_depth > 0 and _bbox_overlap_in_first(path_info.bbox, form_bbox) >= 0.9
]
internal_drawing_lines = [
drawing_line.bbox
@@ -102,15 +97,9 @@ def _tighten_form_image_bbox(
# 至少两个嵌套 Path 和四个矢量元素,避免只凭普通边框或少量文本裁剪 Form。
if len(internal_paths) < 2 or len(internal_paths) + len(internal_drawing_lines) < 4:
return form_bbox
- internal_text = [
- line.bbox
- for line in source.lines
- if _bbox_overlap_in_first(line.bbox, form_bbox) >= 0.9
- ]
+ internal_text = [line.bbox for line in source.lines if _bbox_overlap_in_first(line.bbox, form_bbox) >= 0.9]
evidence_bbox = _clip_bbox(
- _bbox_union_many(
- internal_paths + internal_drawing_lines + internal_text
- ),
+ _bbox_union_many(internal_paths + internal_drawing_lines + internal_text),
source.page_size,
)
if evidence_bbox is None:
@@ -134,11 +123,7 @@ def _select_form_image_bboxes(source: _PageSource) -> list[BBox]:
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
- ]
+ 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:
@@ -161,8 +146,7 @@ def _select_form_image_bboxes(source: _PageSource) -> list[BBox]:
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
+ _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
@@ -250,10 +234,7 @@ def _build_graphic_like_blocks(
candidates = [
candidate
for candidate in line_candidates
- if not any(
- _bbox_overlap_in_smaller(candidate.core_bbox, core_bbox) >= 0.5
- for core_bbox in strong_core_bboxes
- )
+ if not any(_bbox_overlap_in_smaller(candidate.core_bbox, core_bbox) >= 0.5 for core_bbox in strong_core_bboxes)
]
candidates.extend(
_GraphicCandidate(
@@ -274,10 +255,7 @@ def _build_graphic_like_blocks(
),
)
for core_bbox in strong_core_bboxes
- if not any(
- _bbox_overlap_in_smaller(core_bbox, table_bbox) >= 0.5
- for table_bbox in table_bboxes
- )
+ if not any(_bbox_overlap_in_smaller(core_bbox, table_bbox) >= 0.5 for table_bbox in table_bboxes)
)
if not candidates:
return [], set()
@@ -307,10 +285,7 @@ def _build_graphic_like_blocks(
)
for row_lines in row_groups.values():
- if any(
- line.source_index in protected_caption_indices | protected_body_tail_indices
- for line in row_lines
- ):
+ if any(line.source_index in protected_caption_indices | protected_body_tail_indices for line in row_lines):
continue
row_lane_index = _graphic_lane_index(row_lines[0].bbox, lanes)
matches: list[tuple[int, float, int]] = []
@@ -336,9 +311,7 @@ def _build_graphic_like_blocks(
)
for line in row_lines
)
- mean_distance = statistics.fmean(
- _bbox_distance(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
@@ -350,9 +323,7 @@ def _build_graphic_like_blocks(
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
+ 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
@@ -400,8 +371,7 @@ def _parallel_graphic_rule_pairs(
right_height = max(0.1, right_image[3] - right_image[1])
image_overlap = max(
0.0,
- min(left_image[3], right_image[3])
- - max(left_image[1], right_image[1]),
+ min(left_image[3], right_image[3]) - max(left_image[1], right_image[1]),
)
if image_overlap < 0.7 * min(left_height, right_height):
continue
@@ -416,26 +386,19 @@ def _parallel_graphic_rule_pairs(
rule_bbox
for rule_bbox in long_rules
if _bbox_axis_overlap_ratio(rule_bbox, left_image, axis="x") >= 0.8
- and -0.25 * median_height
- <= left_image[1] - rule_bbox[3]
- <= 3.0 * median_height
+ and -0.25 * median_height <= left_image[1] - rule_bbox[3] <= 3.0 * median_height
]
right_rules = [
rule_bbox
for rule_bbox in long_rules
if _bbox_axis_overlap_ratio(rule_bbox, right_image, axis="x") >= 0.8
- and -0.25 * median_height
- <= right_image[1] - rule_bbox[3]
- <= 3.0 * median_height
+ and -0.25 * median_height <= right_image[1] - rule_bbox[3] <= 3.0 * median_height
]
for left_rule in left_rules:
for right_rule in right_rules:
if left_rule[2] >= right_rule[0]:
continue
- if (
- abs(_bbox_center_y(left_rule) - _bbox_center_y(right_rule))
- > 0.5 * median_height
- ):
+ if abs(_bbox_center_y(left_rule) - _bbox_center_y(right_rule)) > 0.5 * median_height:
continue
rule_gap = right_rule[0] - left_rule[2]
if not 0.5 * median_height <= rule_gap <= 5.0 * median_height:
@@ -457,11 +420,7 @@ def _parallel_graphic_row_split_boundary(
) -> float | None:
"""用横线栏沟和字符投影确认并排图形上方文本的安全切分点。"""
- if (
- not members
- or any(member.angle != 0 for member in members)
- or len({member.semantic_type for member in members}) != 1
- ):
+ if not members or any(member.angle != 0 for member in members) or len({member.semantic_type for member in members}) != 1:
return None
row_bbox = _bbox_union_many([member.bbox for member in members])
if any(_bbox_intersects(row_bbox, table_bbox) for table_bbox in table_bboxes):
@@ -476,15 +435,13 @@ def _parallel_graphic_row_split_boundary(
for char in member.chars
if str(char.get("char") or "").isprintable()
and not str(char.get("char") or "").isspace()
- and (bbox := _clip_bbox(_coerce_bbox(char.get("bbox")), page_size))
- is not None
+ and (bbox := _clip_bbox(_coerce_bbox(char.get("bbox")), page_size)) is not None
]
if not glyph_bboxes:
return None
boundary = 0.5 * (left_rule[2] + right_rule[0])
if any(
- _bbox_center_x(bbox) < left_rule[0] - median_height
- or _bbox_center_x(bbox) > right_rule[2] + median_height
+ _bbox_center_x(bbox) < left_rule[0] - median_height or _bbox_center_x(bbox) > right_rule[2] + median_height
for bbox in glyph_bboxes
):
return None
@@ -492,22 +449,15 @@ def _parallel_graphic_row_split_boundary(
right_glyphs = [bbox for bbox in glyph_bboxes if _bbox_center_x(bbox) > boundary]
if len(left_glyphs) < 3 or len(right_glyphs) < 3:
return None
- left_width = max(bbox[2] for bbox in left_glyphs) - min(
- bbox[0] for bbox in left_glyphs
- )
- right_width = max(bbox[2] for bbox in right_glyphs) - min(
- bbox[0] for bbox in right_glyphs
- )
+ left_width = max(bbox[2] for bbox in left_glyphs) - min(bbox[0] for bbox in left_glyphs)
+ right_width = max(bbox[2] for bbox in right_glyphs) - min(bbox[0] for bbox in right_glyphs)
if min(left_width, right_width) < 4.0 * median_height:
return None
left_edge = max(bbox[2] for bbox in left_glyphs)
right_edge = min(bbox[0] for bbox in right_glyphs)
if right_edge - left_edge < 0.75 * median_height:
return None
- if not (
- left_edge <= left_rule[2] <= right_edge
- and left_edge <= right_rule[0] <= right_edge
- ):
+ if not (left_edge <= left_rule[2] <= right_edge and left_edge <= right_rule[0] <= right_edge):
return None
return boundary
@@ -523,14 +473,10 @@ def _split_parallel_graphic_rule_rows(
) -> list[_LineItem]:
"""按成对图形、独立顶边横线和栏沟字符投影拆分并排图形上方文本。"""
- horizontal_lines = [
- line for line in lines if line.angle == 0 and line.effective_height > 0
- ]
+ horizontal_lines = [line for line in lines if line.angle == 0 and line.effective_height > 0]
if len(horizontal_lines) < 1 or len(image_bboxes) < 2:
return list(lines)
- median_height = statistics.median(
- line.effective_height for line in horizontal_lines
- )
+ median_height = statistics.median(line.effective_height for line in horizontal_lines)
rule_pairs = _parallel_graphic_rule_pairs(
drawing_lines,
image_bboxes,
@@ -559,10 +505,7 @@ def _split_parallel_graphic_rule_rows(
if boundary is None:
continue
row_boundaries = boundaries_by_row.setdefault(row_key, [])
- if not any(
- abs(boundary - existing) <= 0.5 * median_height
- for existing in row_boundaries
- ):
+ if not any(abs(boundary - existing) <= 0.5 * median_height for existing in row_boundaries):
row_boundaries.append(boundary)
if not boundaries_by_row:
return list(lines)
@@ -626,9 +569,7 @@ def _split_parallel_graphic_rule_rows(
)
is not None
]
- run_text = _normalize_native_run_text(
- "".join(str(char.get("char") or "") for char in run_chars)
- )
+ run_text = _normalize_native_run_text("".join(str(char.get("char") or "") for char in run_chars))
if not run_text or not run_bboxes:
continue
if run_index < len(source_indices):
@@ -655,9 +596,7 @@ def _split_parallel_graphic_rule_rows(
consumed_source_indices.update(member.source_index for member in members)
split_lines.extend(rebuilt)
- output = [
- line for line in lines if line.source_index not in consumed_source_indices
- ]
+ output = [line for line in lines if line.source_index not in consumed_source_indices]
output.extend(split_lines)
output.sort(key=lambda line: (line.angle, line.bbox[1], line.bbox[0], line.source_index))
return output
@@ -700,13 +639,10 @@ def _graphic_caption_line_indices_to_preserve(
break
if _bbox_center_y(candidate_line.bbox) <= _bbox_center_y(previous.bbox):
continue
- if (
- abs(candidate_line.bbox[0] - seed.bbox[0]) > median_height
- or (
- seed.font_signature is not None
- and candidate_line.font_signature is not None
- and seed.font_signature != candidate_line.font_signature
- )
+ if abs(candidate_line.bbox[0] - seed.bbox[0]) > median_height or (
+ seed.font_signature is not None
+ and candidate_line.font_signature is not None
+ and seed.font_signature != candidate_line.font_signature
):
continue
protected.add(candidate_line.source_index)
@@ -797,11 +733,7 @@ def _detect_strong_graphic_bboxes(source: _PageSource) -> list[BBox]:
if not source.path_infos:
return []
- effective_heights = [
- _line_effective_height(line, line.bbox)
- for line in source.lines
- if line.angle == 0
- ]
+ 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
candidates = [
*_detect_complex_path_containers(
@@ -898,14 +830,20 @@ def _detect_axis_path_graphics(
horizontal_y = _bbox_center_y(horizontal.bbox)
for vertical in vertical_axes:
vertical_x = _bbox_center_x(vertical.bbox)
- touches_x = min(
- abs(vertical_x - horizontal.bbox[0]),
- abs(vertical_x - horizontal.bbox[2]),
- ) <= tolerance
- touches_y = min(
- abs(horizontal_y - vertical.bbox[1]),
- abs(horizontal_y - vertical.bbox[3]),
- ) <= tolerance
+ touches_x = (
+ min(
+ abs(vertical_x - horizontal.bbox[0]),
+ abs(vertical_x - horizontal.bbox[2]),
+ )
+ <= tolerance
+ )
+ touches_y = (
+ min(
+ abs(horizontal_y - vertical.bbox[1]),
+ abs(horizontal_y - vertical.bbox[3]),
+ )
+ <= tolerance
+ )
if not (touches_x and touches_y):
continue
plot_bbox = _bbox_union(horizontal.bbox, vertical.bbox)
@@ -1048,11 +986,7 @@ def _strong_graphic_lane_index(
0.0,
min(core_bbox[2], lane.right) - max(core_bbox[0], lane.left),
)
- if (
- overlap / core_width >= 0.9
- and core_bbox[0] >= lane.left - tolerance
- and core_bbox[2] <= lane.right + tolerance
- ):
+ if overlap / core_width >= 0.9 and core_bbox[0] >= lane.left - tolerance and core_bbox[2] <= lane.right + tolerance:
matching_indices.append(lane_index)
return matching_indices[0] if len(matching_indices) == 1 else -1
@@ -1207,10 +1141,7 @@ def _image_members_to_content(
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
- ]
+ 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))
@@ -1252,8 +1183,7 @@ def _inline_raster_gap_member(
right_height = max(0.1, right_bbox[3] - right_bbox[1])
vertical_overlap = max(
0.0,
- min(left_bbox[3], right_bbox[3])
- - max(left_bbox[1], right_bbox[1]),
+ min(left_bbox[3], right_bbox[3]) - max(left_bbox[1], right_bbox[1]),
)
horizontal_gap = right_bbox[0] - left_bbox[2]
if (
@@ -1273,20 +1203,13 @@ def _inline_raster_gap_member(
and line.angle == 0
and line.split_from_row
and line.visual_row_id is not None
- and left_bbox[2] - edge_tolerance
- <= _bbox_center_x(line.bbox)
- <= right_bbox[0] + edge_tolerance
- and band_top - edge_tolerance
- <= _bbox_center_y(line.bbox)
- <= band_bottom + edge_tolerance
+ and left_bbox[2] - edge_tolerance <= _bbox_center_x(line.bbox) <= right_bbox[0] + edge_tolerance
+ and band_top - edge_tolerance <= _bbox_center_y(line.bbox) <= band_bottom + edge_tolerance
]
if len(gap_members) != 1:
return None
member = gap_members[0]
- if (
- abs(member.bbox[0] - left_bbox[2]) > edge_tolerance
- or abs(member.bbox[2] - right_bbox[0]) > edge_tolerance
- ):
+ if abs(member.bbox[0] - left_bbox[2]) > edge_tolerance or abs(member.bbox[2] - right_bbox[0]) > edge_tolerance:
return None
return member
@@ -1332,9 +1255,7 @@ def _merge_inline_raster_image_candidates(
]
median_height = statistics.median(effective_heights) if effective_heights else 1.0
- adjacency: dict[int, set[int]] = {
- index: set() for index in range(len(candidate_bboxes))
- }
+ adjacency: dict[int, set[int]] = {index: set() for index in range(len(candidate_bboxes))}
gap_members: dict[tuple[int, int], _LineItem] = {}
for first_index, first_bbox in enumerate(candidate_bboxes):
for second_index, second_bbox in enumerate(candidate_bboxes):
@@ -1390,8 +1311,7 @@ def _merge_inline_raster_image_candidates(
[*image_bboxes, *[member.bbox for member in members]],
)
if any(
- _bbox_overlap_in_smaller(group_bbox, container_bbox)
- >= _IMAGE_CONTAINER_OVERLAP_THRESHOLD
+ _bbox_overlap_in_smaller(group_bbox, container_bbox) >= _IMAGE_CONTAINER_OVERLAP_THRESHOLD
for container_bbox in container_bboxes
):
continue
@@ -1406,11 +1326,7 @@ def _merge_inline_raster_image_candidates(
merged_specs.append((group_bbox, next(iter(visual_row_ids))))
consumed_indices.update(ordered_indices)
- merged_specs.extend(
- (bbox, None)
- for index, bbox in enumerate(candidate_bboxes)
- if index not in consumed_indices
- )
+ merged_specs.extend((bbox, None) for index, bbox in enumerate(candidate_bboxes) if index not in consumed_indices)
merged_specs.sort(key=lambda item: (item[0][1], item[0][0], item[0][3], item[0][2]))
return merged_specs
@@ -1424,6 +1340,83 @@ def _image_bboxes_are_near_equal(first: BBox, second: BBox) -> bool:
)
+def _merge_vertical_raster_tiles(
+ bboxes: list[BBox],
+ page_size: tuple[float, float],
+) -> list[BBox]:
+ """把同宽且纵向连续的点阵切片合成一张完整图片。"""
+
+ page_width, page_height = page_size
+ page_area = max(0.0, page_width) * max(0.0, page_height)
+ if len(bboxes) < 3 or page_area <= 0:
+ return list(bboxes)
+
+ endpoint_tolerance = max(0.75, 0.002 * page_width)
+ endpoint_groups: list[list[tuple[int, BBox]]] = []
+ for index, bbox in sorted(
+ enumerate(bboxes),
+ key=lambda item: (item[1][0], item[1][2], item[1][1]),
+ ):
+ target = next(
+ (
+ group
+ for group in endpoint_groups
+ if abs(bbox[0] - statistics.median(item[1][0] for item in group)) <= endpoint_tolerance
+ and abs(bbox[2] - statistics.median(item[1][2] for item in group)) <= endpoint_tolerance
+ ),
+ None,
+ )
+ if target is None:
+ endpoint_groups.append([(index, bbox)])
+ else:
+ target.append((index, bbox))
+
+ merged: list[BBox] = []
+ consumed: set[int] = set()
+ for group in endpoint_groups:
+ ordered = sorted(group, key=lambda item: (item[1][1], item[1][3]))
+ segments: list[list[tuple[int, BBox]]] = []
+ for item in ordered:
+ if not segments:
+ segments.append([item])
+ continue
+ previous_bbox = segments[-1][-1][1]
+ current_bbox = item[1]
+ previous_height = max(0.1, previous_bbox[3] - previous_bbox[1])
+ current_height = max(0.1, current_bbox[3] - current_bbox[1])
+ maximum_gap = max(
+ 1.0,
+ 0.5 * max(previous_height, current_height),
+ )
+ if current_bbox[1] - previous_bbox[3] <= maximum_gap:
+ segments[-1].append(item)
+ else:
+ segments.append([item])
+
+ for segment in segments:
+ if len(segment) < 3:
+ continue
+ segment_bboxes = [bbox for _index, bbox in segment]
+ union_bbox = _bbox_union_many(segment_bboxes)
+ union_height = max(0.1, union_bbox[3] - union_bbox[1])
+ covered_height = sum(max(0.0, bbox[3] - bbox[1]) for bbox in segment_bboxes)
+ if (
+ _bbox_area(union_bbox) / page_area < _MIN_RASTER_IMAGE_PAGE_AREA_RATIO
+ or union_bbox[2] - union_bbox[0] < 0.12 * page_width
+ or union_bbox[2] - union_bbox[0] > 0.9 * page_width
+ or covered_height / union_height < 0.9
+ ):
+ continue
+ merged.append(union_bbox)
+ consumed.update(index for index, _bbox in segment)
+
+ merged.extend(bbox for index, bbox in enumerate(bboxes) if index not in consumed)
+ return sorted(
+ merged,
+ key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]),
+ )
+
+
def _build_raster_image_blocks(
source: _PageSource,
container_blocks: list[dict[str, Any]],
@@ -1435,43 +1428,37 @@ def _build_raster_image_blocks(
if page_area <= 0:
return [], set()
- container_bboxes = [
- bbox
- for block in container_blocks
- if (bbox := _coerce_bbox(block.get("bbox"))) is not None
- ]
+ container_bboxes = [bbox for block in container_blocks if (bbox := _coerce_bbox(block.get("bbox"))) is not None]
signature_bboxes: list[BBox] = []
for raw_bbox in source.signature_bboxes:
bbox = _clip_bbox(_coerce_bbox(raw_bbox), source.page_size)
if bbox is None:
continue
if any(
- _bbox_overlap_in_smaller(bbox, container_bbox)
- >= _IMAGE_CONTAINER_OVERLAP_THRESHOLD
+ _bbox_overlap_in_smaller(bbox, container_bbox) >= _IMAGE_CONTAINER_OVERLAP_THRESHOLD
for container_bbox in container_bboxes
):
continue
- if not any(
- _image_bboxes_are_near_equal(bbox, existing_bbox)
- for existing_bbox in signature_bboxes
- ):
+ if not any(_image_bboxes_are_near_equal(bbox, existing_bbox) for existing_bbox in signature_bboxes):
# 已由注释可见性和 /AP 严格确认的签名不再套用普通点阵图面积门槛。
signature_bboxes.append(bbox)
+ clipped_raster_bboxes = [
+ bbox for raw_bbox in source.image_bboxes if (bbox := _clip_bbox(_coerce_bbox(raw_bbox), source.page_size)) is not None
+ ]
raster_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:
+ for bbox in _merge_vertical_raster_tiles(
+ clipped_raster_bboxes,
+ source.page_size,
+ ):
+ if _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
- if any(
- _image_bboxes_are_near_equal(bbox, signature_bbox)
- for signature_bbox in signature_bboxes
- ):
+ if any(_image_bboxes_are_near_equal(bbox, signature_bbox) for signature_bbox in signature_bboxes):
continue
raster_bboxes.append(bbox)
if not raster_bboxes and not signature_bboxes:
@@ -1488,9 +1475,7 @@ def _build_raster_image_blocks(
else []
)
candidate_specs.extend((bbox, None) for bbox in signature_bboxes)
- candidate_specs.sort(
- key=lambda item: (item[0][1], item[0][0], item[0][3], item[0][2])
- )
+ candidate_specs.sort(key=lambda item: (item[0][1], item[0][0], item[0][3], item[0][2]))
candidate_bboxes = [bbox for bbox, _row_id in candidate_specs]
members_by_candidate: list[list[_LineItem]] = [[] for _ in candidate_bboxes]
@@ -1500,9 +1485,7 @@ def _build_raster_image_blocks(
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)
+ candidate_index for candidate_index, bbox in enumerate(candidate_bboxes) if _point_in_bbox(center, bbox)
]
if not matching_indices:
continue
diff --git a/mineru/model/flash/pdf/line_layout.py b/mineru/model/flash/pdf/line_layout.py
index 83da7ac7..dbece59b 100644
--- a/mineru/model/flash/pdf/line_layout.py
+++ b/mineru/model/flash/pdf/line_layout.py
@@ -59,11 +59,7 @@ def _font_signatures_share_family(
first_family = _normalized_font_family(first)
second_family = _normalized_font_family(second)
- return (
- first_family is not None
- and second_family is not None
- and first_family == second_family
- )
+ return first_family is not None and second_family is not None and first_family == second_family
def _font_weights_conflict(first: _LineItem, second: _LineItem) -> bool:
@@ -104,10 +100,7 @@ def _should_connect_semantic_rows(
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.5 * pair_height
- ):
+ if previous_line.semantic_type == "paragraph_title" and vertical_gap > 0.5 * pair_height:
return False
font_conflicts = (
previous_line.font_signature is not None
@@ -122,19 +115,13 @@ def _should_connect_semantic_rows(
and (
previous_line.dominant_font_weight is None
or current_line.dominant_font_weight is None
- or abs(
- previous_line.dominant_font_weight
- - current_line.dominant_font_weight
- )
- < 100.0
+ or abs(previous_line.dominant_font_weight - current_line.dominant_font_weight) < 100.0
)
)
if font_conflicts and not uncertain_document_title_font:
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
- )
+ 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
@@ -146,10 +133,8 @@ def _line_style_scale(line: _LineItem, local_bbox: BBox) -> float:
return max(
0.1,
line.em_height
- if line.style_scale_repaired
- and line.em_height > 0
- else line.effective_height
- or (local_bbox[3] - local_bbox[1]),
+ if line.style_scale_repaired and line.em_height > 0
+ else line.effective_height or (local_bbox[3] - local_bbox[1]),
)
@@ -158,10 +143,7 @@ def _line_canonical_style_scale(line: _LineItem, local_bbox: BBox) -> float:
return max(
0.1,
- line.em_height
- if line.em_height > 0
- else line.effective_height
- or (local_bbox[3] - local_bbox[1]),
+ line.em_height if line.em_height > 0 else line.effective_height or (local_bbox[3] - local_bbox[1]),
)
@@ -191,9 +173,7 @@ def _effective_text_row_gap(
current_bbox[1] - previous_bbox[3],
-0.25 * _line_effective_height(previous_line, previous_bbox),
)
- return current_bbox[1] - (
- previous_bbox[1] + _line_effective_height(previous_line, previous_bbox)
- )
+ return current_bbox[1] - (previous_bbox[1] + _line_effective_height(previous_line, previous_bbox))
def _effective_body_text_row_gap(
@@ -236,10 +216,7 @@ def _infer_text_lanes(
anchor_tolerance = max(3.0, 0.75 * median_height)
anchor_geometry = [
- item
- for item in line_geometry
- if item[0].semantic_type
- not in {"header", "footer", "page_number", "aside_text"}
+ item for item in line_geometry if item[0].semantic_type not in {"header", "footer", "page_number", "aside_text"}
]
regular_lines = [
item
@@ -290,12 +267,21 @@ def _infer_text_lanes(
]
nested_column_band = None
- if len(filtered_intervals) == 1:
+ if len(filtered_intervals) == 1 and anchor_geometry:
+ nested_outer_interval = (
+ (
+ min(item[1][0] for item in anchor_geometry),
+ max(item[1][2] for item in anchor_geometry),
+ )
+ if recalculate_intervals
+ else filtered_intervals[0][:2]
+ )
nested_column_band = _infer_nested_column_band(
anchor_geometry,
local_page_width,
median_height,
- filtered_intervals[0][:2],
+ nested_outer_interval,
+ enhanced=recalculate_intervals,
)
if nested_column_band is not None:
nested_lanes, band_top, band_bottom = nested_column_band
@@ -308,8 +294,7 @@ def _infer_text_lanes(
line, bbox = item
center_y = _bbox_center_y(bbox)
if (
- line.semantic_type
- in {"header", "footer", "page_number", "page_footnote", "aside_text"}
+ line.semantic_type in {"header", "footer", "page_number", "page_footnote", "aside_text"}
or not band_top <= center_y <= band_bottom
):
fallback_lane.lines.append(item)
@@ -317,8 +302,7 @@ def _infer_text_lanes(
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,
+ max(0.0, min(bbox[2], lane.right) - max(bbox[0], lane.left)) / line_width,
lane,
)
for lane in nested_lanes
@@ -334,11 +318,7 @@ def _infer_text_lanes(
nested_lanes,
anchor_tolerance,
)
- if (
- len(coverage_scores) > 1
- and coverage_scores[1] >= 0.2
- and not fits_only_one_lane
- ):
+ if len(coverage_scores) > 1 and coverage_scores[1] >= 0.2 and not fits_only_one_lane:
span_lines.append(item)
continue
if best_coverage >= 0.5 or fits_only_one_lane:
@@ -391,11 +371,7 @@ def _infer_text_lanes(
)
# 同时覆盖两个稳定正文栏的行仍属于跨栏内容;只进入单侧栏且未越过栏沟的
# 宽正文行则回到该栏,避免窄图注把正文错误挤入 span lane。
- if (
- len(coverage_scores) > 1
- and coverage_scores[1] >= 0.2
- and not fits_only_one_lane
- ):
+ if len(coverage_scores) > 1 and coverage_scores[1] >= 0.2 and not fits_only_one_lane:
span_lines.append(item)
continue
if len(lanes) == 1 or fits_only_one_lane:
@@ -434,16 +410,9 @@ def _fits_only_one_lane(
lane_index = ordered.index(best_lane)
if lane_index > 0 and bbox[0] < ordered[lane_index - 1].right - tolerance:
return False
- if (
- lane_index + 1 < len(ordered)
- and bbox[2] > ordered[lane_index + 1].left - 0.25 * tolerance
- ):
+ if lane_index + 1 < len(ordered) and bbox[2] > ordered[lane_index + 1].left - 0.25 * tolerance:
return False
- return (
- best_lane.left - tolerance
- <= _bbox_center_x(bbox)
- <= best_lane.right + max(tolerance, bbox[2] - best_lane.right)
- )
+ return best_lane.left - tolerance <= _bbox_center_x(bbox) <= best_lane.right + max(tolerance, bbox[2] - best_lane.right)
def _expand_nested_lane_intervals_from_members(
@@ -454,18 +423,13 @@ def _expand_nested_lane_intervals_from_members(
for lane in lanes:
alignment_tolerance = max(1.0, 0.5 * tolerance)
- body_members = [
- bbox
- for line, bbox in lane.lines
- if line.semantic_type is None
- ]
+ body_members = [bbox for line, bbox in lane.lines if line.semantic_type is None]
if not body_members:
continue
aligned_members = [
bbox
for bbox in body_members
- if abs(bbox[0] - lane.left) <= alignment_tolerance
- or abs(bbox[2] - lane.right) <= alignment_tolerance
+ if abs(bbox[0] - lane.left) <= alignment_tolerance or abs(bbox[2] - lane.right) <= alignment_tolerance
]
if not aligned_members:
continue
@@ -487,6 +451,8 @@ def _infer_nested_column_band(
local_page_width: float,
median_height: float,
outer_interval: tuple[float, float],
+ *,
+ enhanced: bool = False,
) -> tuple[list[_TextLane], float, float] | None:
"""在全宽版心内查找仅占局部纵向区间的并列正文栏。"""
@@ -495,7 +461,10 @@ def _infer_nested_column_band(
item
for item in line_geometry
if item[0].semantic_type is None
- and max(4.0 * _line_effective_height(*item), 0.12 * local_page_width)
+ and max(
+ 4.0 * _line_effective_height(*item),
+ 0.12 * local_page_width,
+ )
<= item[1][2] - item[1][0]
<= 0.62 * outer_width
]
@@ -510,11 +479,7 @@ def _infer_nested_column_band(
(
cluster
for cluster in center_clusters
- if abs(
- center
- - statistics.median(_bbox_center_x(member[1]) for member in cluster)
- )
- <= center_tolerance
+ if abs(center - statistics.median(_bbox_center_x(member[1]) for member in cluster)) <= center_tolerance
),
None,
)
@@ -524,17 +489,27 @@ def _infer_nested_column_band(
target.append(item)
supported = [cluster for cluster in center_clusters if len(cluster) >= 3]
- supported.sort(
- key=lambda cluster: statistics.median(_bbox_center_x(item[1]) for item in cluster)
+ supported.sort(key=lambda cluster: statistics.median(_bbox_center_x(item[1]) for item in cluster))
+ best_pair: (
+ tuple[
+ tuple[int, float, float],
+ list[tuple[_LineItem, BBox]],
+ list[tuple[_LineItem, BBox]],
+ tuple[float, float],
+ tuple[float, float],
+ ]
+ | None
+ ) = None
+ cluster_pairs = (
+ [
+ (left_cluster, right_cluster)
+ for left_index, left_cluster in enumerate(supported[:-1])
+ for right_cluster in supported[left_index + 1 :]
+ ]
+ if enhanced
+ else list(zip(supported, supported[1:]))
)
- best_pair: tuple[
- tuple[int, float, float],
- list[tuple[_LineItem, BBox]],
- list[tuple[_LineItem, BBox]],
- tuple[float, float],
- tuple[float, float],
- ] | None = None
- for left_cluster, right_cluster in zip(supported, supported[1:]):
+ for left_cluster, right_cluster in cluster_pairs:
left_interval = (
statistics.median(item[1][0] for item in left_cluster),
statistics.median(item[1][2] for item in left_cluster),
@@ -607,9 +582,7 @@ def _reattach_span_lane_continuations(
median_height,
)
while True:
- span_lane.lines.sort(
- key=lambda item: (item[1][1], item[1][0], item[0].source_index)
- )
+ span_lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
candidates: list[
tuple[
float,
@@ -624,8 +597,7 @@ def _reattach_span_lane_continuations(
preceding = [
item
for item in span_lane.lines
- if item[0].semantic_type == candidate_line.semantic_type
- and item[1][1] < candidate_bbox[1]
+ if item[0].semantic_type == candidate_line.semantic_type and item[1][1] < candidate_bbox[1]
]
if len(preceding) < 2:
continue
@@ -634,13 +606,9 @@ def _reattach_span_lane_continuations(
last_height = _line_effective_height(*last)
if (
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 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
+ or not -0.25 * median_height <= _effective_text_row_gap(previous, last) <= 0.75 * median_height
):
continue
gap = _effective_text_row_gap(last, candidate)
@@ -648,9 +616,7 @@ def _reattach_span_lane_continuations(
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 max(last_height, candidate_height) / min(last_height, candidate_height) > 1.35
or not _title_fonts_compatible(last[0], candidate_line)
):
continue
@@ -685,9 +651,7 @@ def _reattach_span_lane_continuations(
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)
- )
+ span_lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
def _reattach_cross_lane_short_tails(
@@ -780,16 +744,10 @@ def _reattach_repeated_indented_span_tails(
span_lane.lines,
key=lambda item: (item[1][1], item[1][0], item[0].source_index),
)
- matches: list[
- tuple[_TextLane, tuple[_LineItem, BBox], tuple[_LineItem, BBox], float]
- ] = []
+ matches: list[tuple[_TextLane, tuple[_LineItem, BBox], tuple[_LineItem, BBox], float]] = []
for span_index, span_row in enumerate(span_rows):
span_line, span_bbox = span_row
- next_span_top = (
- span_rows[span_index + 1][1][1]
- if span_index + 1 < len(span_rows)
- else float("inf")
- )
+ next_span_top = span_rows[span_index + 1][1][1] if span_index + 1 < len(span_rows) else float("inf")
for regular_lane in regular_lanes:
for candidate in regular_lane.lines:
candidate_line, candidate_bbox = candidate
@@ -804,15 +762,12 @@ def _reattach_repeated_indented_span_tails(
or candidate_bbox[1] >= next_span_top
or not -0.25 * median_height <= gap <= 0.75 * median_height
or not 0.75 * median_height <= indent <= 6.0 * median_height
- or max(span_height, candidate_height)
- / min(span_height, candidate_height)
- > 1.35
+ or max(span_height, candidate_height) / min(span_height, candidate_height) > 1.35
or not _title_fonts_compatible(span_line, 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
+ 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
)
@@ -822,11 +777,7 @@ def _reattach_repeated_indented_span_tails(
if len(matches) < 2:
return
median_indent = statistics.median(match[3] for match in matches)
- supported = [
- match
- for match in matches
- if abs(match[3] - median_indent) <= max(0.75 * median_height, 0.25 * median_indent)
- ]
+ supported = [match for match in matches if abs(match[3] - median_indent) <= max(0.75 * median_height, 0.25 * median_indent)]
if len(supported) < 2:
return
for regular_lane, candidate, _span_row, _indent in supported:
@@ -836,9 +787,7 @@ def _reattach_repeated_indented_span_tails(
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)
- )
+ span_lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
def _estimate_lane_gap(lane: _TextLane) -> tuple[float, float]:
@@ -863,9 +812,10 @@ def _estimate_lane_gap(lane: _TextLane) -> tuple[float, float]:
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:
+ 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))
@@ -897,10 +847,7 @@ def _is_structural_typography_gap(
0.75 * pair_height,
3.0 * gap_mad,
)
- return prominent_gap and (
- pair_height / minimum_height >= 1.12
- or reliable_style_change
- )
+ return prominent_gap and (pair_height / minimum_height >= 1.12 or reliable_style_change)
def _should_connect_text_rows(
@@ -927,19 +874,13 @@ def _should_connect_text_rows(
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 + max(0.25 * previous_height, 3.0 * gap_mad)
- ):
+ if current_height < 0.88 * previous_height and vertical_gap > regular_gap + max(0.25 * previous_height, 3.0 * gap_mad):
return False
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
current_returns_to_lane_left = (
abs(current_bbox[0] - lane.left) <= 0.75 * pair_height
- and -0.5 * pair_height
- <= previous_bbox[0] - lane.left
- <= 2.0 * pair_height
+ and -0.5 * pair_height <= previous_bbox[0] - lane.left <= 2.0 * pair_height
)
reliable_font_match = (
previous_line.font_signature is None
@@ -951,10 +892,7 @@ def _should_connect_text_rows(
previous_line.font_signature,
current_line.font_signature,
)
- or (
- current_width <= 0.5 * lane_width
- and previous_line.font_signature[1] == current_line.font_signature[1]
- )
+ or (current_width <= 0.5 * lane_width and previous_line.font_signature[1] == current_line.font_signature[1])
)
previous_indent = previous_bbox[0] - lane.left
repeated_indent_continuation = (
@@ -969,9 +907,7 @@ def _should_connect_text_rows(
and (aligned_left_edges or current_returns_to_lane_left)
and reliable_font_match
and not _font_weights_conflict(previous_line, current_line)
- and -0.25 * pair_height
- <= vertical_gap
- <= regular_gap + max(0.75 * pair_height, 3.0 * gap_mad)
+ and -0.25 * pair_height <= vertical_gap <= regular_gap + max(0.75 * pair_height, 3.0 * gap_mad)
)
height_ratio = max(previous_height, current_height) / min(previous_height, current_height)
font_style_changed = (
@@ -1009,15 +945,9 @@ def _should_connect_text_rows(
and aligned_left_edges
and height_ratio <= 1.25
and not _font_weights_conflict(previous_line, current_line)
- and -0.25 * pair_height
- <= vertical_gap
- <= regular_gap + max(0.35 * pair_height, 3.0 * gap_mad)
+ and -0.25 * pair_height <= vertical_gap <= regular_gap + max(0.35 * pair_height, 3.0 * gap_mad)
)
- if (
- font_style_changed
- and _font_weights_conflict(previous_line, current_line)
- and not fallback_font_continuation
- ):
+ if font_style_changed and _font_weights_conflict(previous_line, current_line) and not fallback_font_continuation:
# 显式样式位与显著字重同时变化仍是硬边界,不能被满栏几何放宽。
return False
if (
@@ -1038,8 +968,7 @@ def _should_connect_text_rows(
both_fill_lane
and aligned_left_edges
and not font_style_changed
- and vertical_gap
- <= regular_gap + max(0.75 * min(previous_height, current_height), 3.0 * gap_mad)
+ and vertical_gap <= regular_gap + max(0.75 * min(previous_height, current_height), 3.0 * gap_mad)
)
if height_ratio > 1.35 and not safe_short_tail and not full_width_continuation:
# 满栏混合字体可跨字号续接,但显式正体/斜体等样式边界仍保持原分段语义。
@@ -1048,9 +977,11 @@ def _should_connect_text_rows(
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 and not safe_short_tail:
+ 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
+ and not safe_short_tail
+ ):
return False
if _connection_crosses_table(previous_line.bbox, current_line.bbox, table_bboxes):
return False
@@ -1100,11 +1031,7 @@ def _should_connect_text_rows(
and not fallback_font_continuation
):
return False
- if (
- abnormal_gap
- and min(previous_width, current_width) <= 0.65 * lane_width
- and not safe_short_tail
- ):
+ if abnormal_gap and min(previous_width, current_width) <= 0.65 * lane_width and not safe_short_tail:
return False
return True
diff --git a/mineru/model/flash/pdf/line_merging.py b/mineru/model/flash/pdf/line_merging.py
index d0701c99..a4f7953f 100644
--- a/mineru/model/flash/pdf/line_merging.py
+++ b/mineru/model/flash/pdf/line_merging.py
@@ -4,7 +4,9 @@
from __future__ import annotations
+import re
import statistics
+import unicodedata
from ....types import BBox
@@ -230,14 +232,10 @@ def _overlapping_inline_cluster_pair_is_connected(
)
if (
local_page_width is not None
- and (
- first_line.style_scale_repaired
- or second_line.style_scale_repaired
- )
+ and (first_line.style_scale_repaired or second_line.style_scale_repaired)
and left_bbox[2] <= 0.5 * local_page_width
and right_bbox[0] >= 0.5 * local_page_width
- and right_bbox[0] - left_bbox[2]
- >= 0.02 * local_page_width
+ and right_bbox[0] - left_bbox[2] >= 0.02 * local_page_width
):
return False
@@ -377,10 +375,7 @@ def _merge_overlapping_inline_cluster(
restored_inline_cluster=True,
compact_formula_cluster=compact_formula_cluster,
formula_candidate_only=all(line.formula_candidate_only for line in ordered_members),
- style_scale_repaired=any(
- line.style_scale_repaired
- for line in ordered_members
- ),
+ style_scale_repaired=any(line.style_scale_repaired for line in ordered_members),
inline_math_regions=[
*(region for line in ordered_members for region in line.inline_math_regions),
*detected_regions,
@@ -658,10 +653,7 @@ def _merge_same_baseline_group(
),
run_index=min(member.run_index for member in members),
effective_height=statistics.median(member.effective_height for member in members),
- em_height=statistics.median(
- member.em_height or member.effective_height
- for member in members
- ),
+ em_height=statistics.median(member.em_height or 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(
@@ -681,10 +673,7 @@ def _merge_same_baseline_group(
restored_inline_cluster=any(member.restored_inline_cluster for member in members),
compact_formula_cluster=any(member.compact_formula_cluster for member in members),
formula_candidate_only=all(member.formula_candidate_only for member in members),
- style_scale_repaired=any(
- member.style_scale_repaired
- for member in members
- ),
+ style_scale_repaired=any(member.style_scale_repaired for member in members),
inline_math_regions=[region for member in members for region in member.inline_math_regions],
)
if merged.chars:
@@ -847,6 +836,98 @@ def _merge_title_resolved_visual_rows(
line.source_index,
)
)
+ return _merge_numbered_title_fragments(
+ output,
+ page_size,
+ )
+
+
+def _merge_numbered_title_fragments(
+ lines: list[_LineItem],
+ page_size: tuple[float, float],
+) -> list[_LineItem]:
+ """合并 PDF 字体分割导致的章节编号与同基线标题文字。"""
+
+ marker_re = re.compile(
+ r"^\d+(?:\s*\.\s*\d+)*\.?$",
+ )
+ geometry = [
+ (
+ line,
+ _rotate_bbox_to_upright(
+ line.bbox,
+ page_size,
+ line.angle,
+ ),
+ )
+ for line in lines
+ if line.semantic_type == "paragraph_title"
+ ]
+ consumed: set[int] = set()
+ merged: list[_LineItem] = []
+ for marker, marker_bbox in geometry:
+ if marker.source_index in consumed:
+ continue
+ normalized = re.sub(
+ r"\s+",
+ " ",
+ unicodedata.normalize("NFKC", marker.text),
+ ).strip()
+ if marker_re.match(normalized) is None:
+ continue
+ marker_height = _line_effective_height(
+ marker,
+ marker_bbox,
+ )
+ companions = [
+ (candidate, candidate_bbox)
+ for candidate, candidate_bbox in geometry
+ if candidate is not marker
+ and candidate.source_index not in consumed
+ and candidate.angle == marker.angle
+ and candidate_bbox[0] >= marker_bbox[2]
+ and candidate_bbox[0] - marker_bbox[2] <= 4.0 * marker_height
+ and _bbox_axis_overlap_ratio(
+ marker_bbox,
+ candidate_bbox,
+ axis="y",
+ )
+ >= 0.5
+ ]
+ if not companions:
+ continue
+ companion, _companion_bbox = min(
+ companions,
+ key=lambda item: (
+ item[1][0] - marker_bbox[2],
+ item[1][1],
+ ),
+ )
+ merged.append(
+ _merge_dense_split_visual_row(
+ [marker, companion],
+ page_size,
+ )
+ )
+ consumed.update({marker.source_index, companion.source_index})
+ output = [line for line in lines if line.source_index not in consumed]
+ output.extend(merged)
+ 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
@@ -1022,10 +1103,7 @@ def _merge_dense_split_visual_row(
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),
- em_height=statistics.median(
- _line_effective_height(member, bbox)
- for member, bbox in ordered_geometry
- ),
+ em_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(
@@ -1045,10 +1123,7 @@ def _merge_dense_split_visual_row(
restored_inline_cluster=any(member.restored_inline_cluster for member in ordered_members),
compact_formula_cluster=any(member.compact_formula_cluster for member in ordered_members),
formula_candidate_only=all(member.formula_candidate_only for member in ordered_members),
- style_scale_repaired=any(
- member.style_scale_repaired
- for member in ordered_members
- ),
+ style_scale_repaired=any(member.style_scale_repaired for member in ordered_members),
inline_math_regions=[region for member in ordered_members for region in member.inline_math_regions],
)
if merged.chars:
diff --git a/mineru/model/flash/pdf/models.py b/mineru/model/flash/pdf/models.py
index d6baf20d..0432a73e 100644
--- a/mineru/model/flash/pdf/models.py
+++ b/mineru/model/flash/pdf/models.py
@@ -46,7 +46,10 @@ class _LineItem:
restored_inline_cluster: bool = False
compact_formula_cluster: bool = False
formula_candidate_only: bool = False
+ paragraph_formula_context: bool = False
structural_title: bool = False
+ explicit_section_title: bool = False
+ title_suppressed: bool = False
style_scale_repaired: bool = False
inline_math_regions: list[BBox] = field(default_factory=list)
diff --git a/mineru/model/flash/pdf/native_text.py b/mineru/model/flash/pdf/native_text.py
index 456ef020..19c93d91 100644
--- a/mineru/model/flash/pdf/native_text.py
+++ b/mineru/model/flash/pdf/native_text.py
@@ -7,6 +7,8 @@ from __future__ import annotations
import math
import re
import statistics
+import unicodedata
+from collections import Counter
from typing import Any, Literal, Mapping, Sequence
from pdftext.schema import Char
@@ -118,6 +120,53 @@ def _build_native_line_items(
return output
+def _extract_decorative_text_rules(
+ lines: list[_LineItem],
+ page_size: tuple[float, float],
+) -> tuple[list[_LineItem], list[_AxisLine]]:
+ """把宽幅私用区重复字形转为装饰分隔线,避免其进入文本块。"""
+
+ retained: list[_LineItem] = []
+ decorative_rules: list[_AxisLine] = []
+ for line in lines:
+ local_bbox = _rotate_bbox_to_upright(
+ line.bbox,
+ page_size,
+ line.angle,
+ )
+ local_page_width = page_size[1] if line.angle in {90, 270} else page_size[0]
+ local_page_height = page_size[0] if line.angle in {90, 270} else page_size[1]
+ compact_text = "".join(
+ char for char in line.text if not char.isspace() and (char.isprintable() or unicodedata.category(char) == "Co")
+ )
+ private_use_count = sum(unicodedata.category(char) == "Co" for char in compact_text)
+ repeated_count = max(
+ Counter(compact_text).values(),
+ default=0,
+ )
+ local_width = max(0.0, local_bbox[2] - local_bbox[0])
+ local_height = max(0.1, local_bbox[3] - local_bbox[1])
+ is_decorative_rule = (
+ len(compact_text) >= 8
+ and private_use_count / len(compact_text) >= 0.8
+ and repeated_count / len(compact_text) >= 0.8
+ and local_width >= 0.4 * local_page_width
+ and local_width / local_height >= 20.0
+ and _bbox_center_y(local_bbox) <= 0.2 * local_page_height
+ )
+ if not is_decorative_rule:
+ retained.append(line)
+ continue
+ decorative_rules.append(
+ _AxisLine(
+ bbox=line.bbox,
+ width=min(1.0, local_height),
+ orientation=("vertical" if line.angle in {90, 270} else "horizontal"),
+ )
+ )
+ return retained, decorative_rules
+
+
def _pdftext_angle_degrees(value: Any) -> float:
"""把 pdftext 弧度方向转换为 0 到 360 度,非法值按 0 度处理。"""
@@ -319,10 +368,7 @@ def _split_native_visual_runs(
char_idx = char.get("char_idx")
visual_bbox = (
visual_bboxes.get(char_idx)
- if visual_bboxes is not None
- and isinstance(char_idx, int)
- and raw_char.isprintable()
- and not raw_char.isspace()
+ if visual_bboxes is not None and isinstance(char_idx, int) and raw_char.isprintable() and not raw_char.isspace()
else None
)
bbox = _clip_bbox(
@@ -464,20 +510,11 @@ def _resplit_native_visual_runs(
page_size,
line.angle,
)
- local_page_height = (
- page_size[0]
- if line.angle in {90, 270}
- else page_size[1]
- )
- local_page_width = (
- page_size[1]
- if line.angle in {90, 270}
- else page_size[0]
- )
+ local_page_height = page_size[0] if line.angle in {90, 270} else page_size[1]
+ local_page_width = page_size[1] if line.angle in {90, 270} else page_size[0]
if (
line.semantic_type is not None
- or local_bbox[2] - local_bbox[0]
- < 0.45 * local_page_width
+ or local_bbox[2] - local_bbox[0] < 0.45 * local_page_width
or _bbox_center_y(local_bbox) < 0.07 * local_page_height
or _bbox_center_y(local_bbox) > 0.93 * local_page_height
):
@@ -505,13 +542,8 @@ def _resplit_native_visual_runs(
)
column_split = (
len(local_members) == 2
- and all(
- bbox[2] - bbox[0]
- >= 0.15 * local_page_width
- for bbox in local_members
- )
- and local_members[1][0] - local_members[0][2]
- >= 0.02 * local_page_width
+ and all(bbox[2] - bbox[0] >= 0.15 * local_page_width for bbox in local_members)
+ and local_members[1][0] - local_members[0][2] >= 0.02 * local_page_width
and local_members[0][2] <= 0.52 * local_page_width
and local_members[1][0] >= 0.48 * local_page_width
)
@@ -519,11 +551,7 @@ def _resplit_native_visual_runs(
output.append(line)
continue
for member_index, member in enumerate(members):
- member.source_index = (
- line.source_index
- if member_index == 0
- else next_source_index
- )
+ member.source_index = line.source_index if member_index == 0 else next_source_index
if member_index > 0:
next_source_index += 1
member.visual_row_id = line.visual_row_id
@@ -542,9 +570,7 @@ def _resplit_native_visual_runs(
output.append(member)
output.sort(
key=lambda item: (
- item.visual_row_id
- if item.visual_row_id is not None
- else math.inf,
+ item.visual_row_id if item.visual_row_id is not None else math.inf,
item.run_index,
item.source_index,
)
diff --git a/mineru/model/flash/pdf/pipeline.py b/mineru/model/flash/pdf/pipeline.py
index a3976509..526558f5 100644
--- a/mineru/model/flash/pdf/pipeline.py
+++ b/mineru/model/flash/pdf/pipeline.py
@@ -23,6 +23,7 @@ from .text_styles import (
)
from .models import (
+ _AxisLine,
_DocumentBodyProfile,
_DocumentTitleProfile,
_LineItem,
@@ -43,6 +44,7 @@ from .geometry import (
)
from .native_text import (
_build_native_line_items,
+ _extract_decorative_text_rules,
_get_pdf_drawing_lines,
_median_native_glyph_width,
_sanitize_pdf_control_text,
@@ -98,6 +100,7 @@ from .auxiliary_text import (
)
from .titles import (
_classify_body_height_section_titles,
+ _classify_explicit_section_titles,
_classify_secondary_document_title_bands,
_classify_document_structural_titles,
_classify_page_titles,
@@ -188,6 +191,58 @@ def _filter_repeated_raster_watermark_bboxes(
]
+def _table_detection_drawing_lines(
+ source: _PageSource,
+ confirmed_header_separators: set[BBox] | None = None,
+) -> list[_AxisLine]:
+ """从表格候选路径中移除已确认页眉下方的通栏分隔线。"""
+
+ confirmed = confirmed_header_separators or set()
+ return [drawing_line for drawing_line in source.drawing_lines if drawing_line.bbox not in confirmed]
+
+
+def _detect_repeated_header_separator_bboxes(
+ sources: list[_PageSource],
+) -> list[set[BBox]]:
+ """用至少三页重复的页首几何和上方刊头文本确认页眉分隔线。"""
+
+ candidates_by_signature: dict[
+ tuple[float, float, float],
+ list[tuple[int, BBox]],
+ ] = {}
+ for page_index, source in enumerate(sources):
+ page_width, page_height = source.page_size
+ if page_width <= 0 or page_height <= 0:
+ continue
+ for drawing_line in source.drawing_lines:
+ bbox = drawing_line.bbox
+ center_y = _bbox_center_y(bbox)
+ if (
+ drawing_line.orientation != "horizontal"
+ or center_y > 0.15 * page_height
+ or bbox[2] - bbox[0] < 0.6 * page_width
+ or sum(line.angle == 0 and line.bbox[3] <= center_y for line in source.lines) < 2
+ ):
+ continue
+ signature = (
+ round(bbox[0] / page_width, 2),
+ round(bbox[2] / page_width, 2),
+ round(center_y / page_height, 3),
+ )
+ candidates_by_signature.setdefault(
+ signature,
+ [],
+ ).append((page_index, bbox))
+
+ output = [set() for _source in sources]
+ for members in candidates_by_signature.values():
+ if len({page_index for page_index, _bbox in members}) < 3:
+ continue
+ for page_index, bbox in members:
+ output[page_index].add(bbox)
+ return output
+
+
def _analyze_native_document(
pdf_doc: PDFDocument,
*,
@@ -218,6 +273,11 @@ def _analyze_native_document(
page_rotation=pdf_doc.page_rotation(page_idx),
)
drawing_lines = _get_pdf_drawing_lines(pdf_doc, page_idx)
+ lines, decorative_rules = _extract_decorative_text_rules(
+ lines,
+ page_size,
+ )
+ drawing_lines.extend(decorative_rules)
page_style_lines.append(detect_pdf_text_style_lines(lines, drawing_lines))
page_link_lines.append(
detect_pdf_text_link_lines(
@@ -259,6 +319,9 @@ def _analyze_native_document(
geometry_diagnostics.append(geometry_plan.to_dict())
_classify_raw_page_marginals(page_sources)
+ repeated_header_separators = _detect_repeated_header_separator_bboxes(
+ page_sources,
+ )
prepared_pages = [
_prepare_page_source(
source,
@@ -266,6 +329,7 @@ def _analyze_native_document(
origins=geometry.origins,
geometry_plan=geometry_plan,
page_index=page_index,
+ table_header_separator_bboxes=(repeated_header_separators[page_index]),
)
for page_index, (source, geometry) in enumerate(zip(page_sources, page_text_geometries, strict=True))
]
@@ -363,6 +427,7 @@ def _prepare_page_source(
origins: dict[int, tuple[float, float]] | None = None,
geometry_plan: DocumentGeometryPlan | None = None,
page_index: int = 0,
+ table_header_separator_bboxes: set[BBox] | None = None,
) -> _PreparedPage:
"""先认领视觉容器,再标注辅助文本并留下可跨页比较的轻量文本行。"""
@@ -378,10 +443,17 @@ def _prepare_page_source(
form_bboxes + strong_graphic_bboxes + list(source.image_bboxes) + list(source.signature_bboxes),
)
rule_code_bboxes = [block["bbox"] for block in rule_code_blocks]
+ table_analysis_source = replace(
+ analysis_source,
+ drawing_lines=_table_detection_drawing_lines(
+ source,
+ table_header_separator_bboxes,
+ ),
+ )
candidates = [
candidate
for candidate in _detect_table_candidates(
- analysis_source,
+ table_analysis_source,
excluded_bboxes=strong_graphic_bboxes + rule_code_bboxes,
)
if not any(_form_supersedes_nested_bbox(form_bbox, candidate.bbox) for form_bbox in form_bboxes)
@@ -471,8 +543,7 @@ def _prepare_page_source(
)
for line in remaining_lines
]
- if geometry_plan is not None
- and geometry_plan.document_style_anomaly
+ if geometry_plan is not None and geometry_plan.document_style_anomaly
else []
)
remaining_lines = _merge_same_baseline_text_lines(
@@ -569,16 +640,8 @@ def _rebuild_canonical_formula_blocks(
prepared.page_size,
prepared.table_bboxes,
)
- formula_candidate_lines = [
- line
- for line in replay_lines
- if line.formula_candidate_only
- ]
- replay_lines = [
- line
- for line in replay_lines
- if not line.formula_candidate_only
- ]
+ formula_candidate_lines = [line for line in replay_lines if line.formula_candidate_only]
+ replay_lines = [line for line in replay_lines if not line.formula_candidate_only]
formula_input = _restore_dense_split_visual_rows(
replay_lines + formula_candidate_lines,
prepared.page_size,
@@ -605,9 +668,7 @@ def _formula_block_inventory(
return sorted(
tuple(float(value) for value in block["bbox"])
for block in blocks
- if block.get("type") == "equation"
- and isinstance(block.get("bbox"), (list, tuple))
- and len(block["bbox"]) == 4
+ if block.get("type") == "equation" and isinstance(block.get("bbox"), (list, tuple)) and len(block["bbox"]) == 4
)
@@ -634,10 +695,7 @@ def _finalize_prepared_page(
*(line for line in unresolved_lines if line.semantic_type is None),
*prepared.formula_candidate_lines,
]
- original_style_scale_state = {
- line.source_index: line.style_scale_repaired
- for line in formula_input
- }
+ original_style_scale_state = {line.source_index: line.style_scale_repaired for line in formula_input}
if prepared.canonical_formula_geometry:
for line in formula_input:
line.style_scale_repaired = True
@@ -656,16 +714,10 @@ def _finalize_prepared_page(
prepared.table_bboxes,
prepared.page_size,
)
- if (
- prepared.canonical_formula_geometry
- and prepared.canonical_formula_source_lines
- ):
+ if prepared.canonical_formula_geometry and prepared.canonical_formula_source_lines:
canonical_formula_blocks = _rebuild_canonical_formula_blocks(
prepared,
- {
- line.source_index
- for line in semantic_lines
- },
+ {line.source_index for line in semantic_lines},
)
if _formula_block_inventory(
canonical_formula_blocks,
@@ -690,6 +742,12 @@ def _finalize_prepared_page(
block["bbox"] for block in prepared.fixed_blocks if not isinstance(block.get("_inline_visual_row_id"), int)
]
caption_container_bboxes = [block["bbox"] for block in prepared.fixed_blocks if block.get("type") in {"image", "code"}]
+ _classify_explicit_section_titles(
+ remaining_lines,
+ prepared.page_size,
+ container_bboxes=title_container_bboxes,
+ document_body_profile=document_body_profile,
+ )
_classify_body_height_section_titles(
remaining_lines,
prepared.page_size,
diff --git a/mineru/model/flash/pdf/tables.py b/mineru/model/flash/pdf/tables.py
index 456932ef..f4e60693 100644
--- a/mineru/model/flash/pdf/tables.py
+++ b/mineru/model/flash/pdf/tables.py
@@ -163,10 +163,7 @@ def _detect_table_candidates(
]
local_closed_grid_excluded_bboxes = [
*local_excluded_bboxes,
- *[
- _rotate_bbox_to_upright(bbox, source.page_size, angle)
- for bbox in source.form_bboxes
- ],
+ *[_rotate_bbox_to_upright(bbox, source.page_size, angle) for bbox in source.form_bboxes],
]
rule_candidates.extend(
_build_rule_table_candidates(
@@ -194,10 +191,7 @@ def _detect_table_candidates(
merged_rule_candidates = [
candidate
for candidate in _merge_table_candidates(rule_candidates)
- if not any(
- _bbox_overlap_in_smaller(candidate.bbox, filled_bbox) >= 0.2
- for filled_bbox in filled_grid_bboxes
- )
+ if not any(_bbox_overlap_in_smaller(candidate.bbox, filled_bbox) >= 0.2 for filled_bbox in filled_grid_bboxes)
]
candidates = [*filled_grid_candidates, *merged_rule_candidates]
_externalize_table_continuation_captions(
@@ -357,26 +351,17 @@ def _detect_filled_grid_table_candidates(
outer_height = outer_bbox[3] - outer_bbox[1]
outer_area = _bbox_area(outer_bbox)
if not (
- _FILLED_GRID_MIN_PAGE_AREA_RATIO
- <= outer_area / page_area
- <= _FILLED_GRID_MAX_PAGE_AREA_RATIO
+ _FILLED_GRID_MIN_PAGE_AREA_RATIO <= outer_area / page_area <= _FILLED_GRID_MAX_PAGE_AREA_RATIO
and outer_width >= _FILLED_GRID_MIN_PAGE_WIDTH_RATIO * page_width
and outer_height >= _FILLED_GRID_MIN_PAGE_HEIGHT_RATIO * page_height
):
continue
- if any(
- _bbox_overlap_in_smaller(outer_bbox, excluded_bbox) >= 0.5
- for excluded_bbox in excluded_bboxes
- ):
+ if any(_bbox_overlap_in_smaller(outer_bbox, excluded_bbox) >= 0.5 for excluded_bbox in excluded_bboxes):
continue
cells = _select_maximal_filled_grid_cells(rectangles, outer_bbox)
bands = _group_filled_grid_cells_into_bands(cells, outer_bbox)
- accepted_bands = [
- band
- for band in bands
- if _filled_grid_band_covers_outer_width(band, outer_bbox)
- ]
+ accepted_bands = [band for band in bands if _filled_grid_band_covers_outer_width(band, outer_bbox)]
if len(accepted_bands) < 4:
continue
accepted_bands.sort(
@@ -385,17 +370,12 @@ def _detect_filled_grid_table_candidates(
min(cell[0] for cell in band),
)
)
- covered_height = sum(
- max(cell[3] for cell in band) - min(cell[1] for cell in band)
- for band in accepted_bands
- )
+ covered_height = sum(max(cell[3] for cell in band) - min(cell[1] for cell in band) for band in accepted_bands)
vertical_coverage = covered_height / outer_height
if vertical_coverage < 0.75:
continue
if any(
- min(cell[1] for cell in next_band)
- - max(cell[3] for cell in current_band)
- > 0.05 * outer_height
+ min(cell[1] for cell in next_band) - max(cell[3] for cell in current_band) > 0.05 * outer_height
for current_band, next_band in zip(
accepted_bands,
accepted_bands[1:],
@@ -425,10 +405,7 @@ def _detect_filled_grid_table_candidates(
key=lambda item: (item[1], item[2], item[3]),
reverse=True,
):
- if any(
- _bbox_overlap_in_smaller(candidate.bbox, accepted.bbox) >= 0.9
- for accepted in output
- ):
+ if any(_bbox_overlap_in_smaller(candidate.bbox, accepted.bbox) >= 0.9 for accepted in output):
continue
output.append(candidate)
return sorted(output, key=lambda candidate: (candidate.bbox[1], candidate.bbox[0]))
@@ -474,18 +451,11 @@ def _select_maximal_filled_grid_cells(
)
and _bbox_area(other) >= 1.08 * _bbox_area(rectangle)
and _bbox_area(other) <= 0.8 * outer_area
- and abs(
- (rectangle[2] - rectangle[0])
- - (other[2] - other[0])
- )
- <= 0.01 * outer_width
+ and abs((rectangle[2] - rectangle[0]) - (other[2] - other[0])) <= 0.01 * outer_width
for other in nested_rectangles
):
continue
- if any(
- _bbox_overlap_in_smaller(rectangle, accepted) >= 0.95
- for accepted in output
- ):
+ if any(_bbox_overlap_in_smaller(rectangle, accepted) >= 0.95 for accepted in output):
continue
output.append(rectangle)
return sorted(output, key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]))
@@ -517,12 +487,7 @@ def _group_filled_grid_cells_into_bands(
bands: list[list[BBox]] = []
for cell in sorted(cells, key=lambda bbox: (bbox[1], bbox[0], bbox[3])):
target = next(
- (
- band
- for band in bands
- if abs(cell[1] - band[0][1]) <= y_tolerance
- and abs(cell[3] - band[0][3]) <= y_tolerance
- ),
+ (band for band in bands if abs(cell[1] - band[0][1]) <= y_tolerance and abs(cell[3] - band[0][3]) <= y_tolerance),
None,
)
if target is None:
@@ -556,10 +521,8 @@ def _filled_grid_band_covers_outer_width(
return (
covered_width >= 0.9 * outer_width
and maximum_gap <= 0.01 * outer_width
- and abs(min(cell[0] for cell in band) - outer_bbox[0])
- <= 0.02 * outer_width
- and abs(max(cell[2] for cell in band) - outer_bbox[2])
- <= 0.02 * outer_width
+ and abs(min(cell[0] for cell in band) - outer_bbox[0]) <= 0.02 * outer_width
+ and abs(max(cell[2] for cell in band) - outer_bbox[2]) <= 0.02 * outer_width
)
@@ -669,16 +632,34 @@ def _build_rule_table_candidates(
rule_bbox,
excluded_bboxes,
)
- if not _every_rule_interval_has_multi_cell_row(
- core_rows,
- interval_rules,
+ caption_line = _find_table_caption(
+ lines,
+ rule_bbox,
+ page_size,
+ angle,
median_height,
+ )
+ caption_anchored_compact_grid = (
+ caption_line is not None
+ and len(interval_rules) >= 3
+ and rule_bbox[3] - rule_bbox[1] <= 0.15 * (page_size[0] if angle in {90, 270} else page_size[1])
+ )
+ if (
+ not _every_rule_interval_has_multi_cell_row(
+ core_rows,
+ interval_rules,
+ median_height,
+ )
+ and not caption_anchored_compact_grid
):
continue
- if not _rule_intervals_are_column_compatible(
- core_rows,
- interval_rules,
- median_height,
+ if (
+ not _rule_intervals_are_column_compatible(
+ core_rows,
+ interval_rules,
+ median_height,
+ )
+ and not caption_anchored_compact_grid
):
continue
@@ -711,12 +692,6 @@ def _build_rule_table_candidates(
if len(dense_rows) == 2
else 0
)
- if len(dense_rows) < 3 and compact_grid_columns == 0:
- continue
- # 真表格的多单元行会在整个数据带内反复出现;少数图题、图例和
- # 坐标刻度偶然形成的多列行不能支撑一大片正文区域。
- if len(dense_rows) / len(row_segment) < 0.2:
- continue
stable_columns, column_coverage = _count_stable_columns(
dense_rows,
median_height,
@@ -724,6 +699,18 @@ def _build_rule_table_candidates(
if compact_grid_columns > 0:
# 两行样本容易把左右/中心锚点误算成不同稳定列,使用物理网格列数。
stable_columns = compact_grid_columns
+ caption_supported_compact_rows = (
+ caption_anchored_compact_grid
+ and len(dense_rows) >= 2
+ and stable_columns >= 3
+ and column_coverage >= 0.5
+ )
+ if len(dense_rows) < 3 and compact_grid_columns == 0 and not caption_supported_compact_rows:
+ continue
+ # 真表格的多单元行会在整个数据带内反复出现;少数图题、图例和
+ # 坐标刻度偶然形成的多列行不能支撑一大片正文区域。
+ if len(dense_rows) / len(row_segment) < 0.2:
+ continue
if stable_columns < 2 or column_coverage < 0.5:
continue
if _looks_like_page_column_prose(
@@ -769,13 +756,6 @@ def _build_rule_table_candidates(
continue
accepted_rows, dense_rows, stable_columns, _coverage = accepted
- caption_line = _find_table_caption(
- lines,
- rule_bbox,
- page_size,
- angle,
- median_height,
- )
candidate = _expand_rule_table_candidate(
boundary_rules,
accepted_rows,
@@ -786,12 +766,7 @@ def _build_rule_table_candidates(
median_height,
caption_line,
)
- candidate.score = float(
- 2
- + len(dense_rows)
- + stable_columns
- + min(fill_band_count, 8)
- )
+ candidate.score = float(2 + len(dense_rows) + stable_columns + min(fill_band_count, 8))
candidates.append(candidate)
return _expand_candidates_to_connected_rule_grids(
candidates,
@@ -818,10 +793,7 @@ def _expand_candidates_to_connected_rule_grids(
grid_bboxes = [
grid_bbox
for grid_bbox in _connected_rule_grid_bboxes(axis_lines, median_height)
- if not any(
- _bbox_overlap_in_smaller(grid_bbox, excluded_bbox) >= 0.5
- for excluded_bbox in excluded_bboxes
- )
+ if not any(_bbox_overlap_in_smaller(grid_bbox, excluded_bbox) >= 0.5 for excluded_bbox in excluded_bboxes)
]
if not grid_bboxes:
return candidates
@@ -852,8 +824,7 @@ def _expand_candidates_to_connected_rule_grids(
grid_bbox = max(
matches,
key=lambda bbox: (
- min(core_local_bbox[3], bbox[3])
- - max(core_local_bbox[1], bbox[1]),
+ min(core_local_bbox[3], bbox[3]) - max(core_local_bbox[1], bbox[1]),
_bbox_area(bbox),
),
)
@@ -902,10 +873,7 @@ def _build_closed_rule_grid_candidates(
candidates: list[_TableCandidate] = []
for component in _connected_rule_grid_components(axis_lines, median_height):
grid_bbox = _bbox_union_many([rule.bbox for rule in component])
- if any(
- _bbox_overlap_in_smaller(grid_bbox, excluded_bbox) >= 0.5
- for excluded_bbox in excluded_bboxes
- ):
+ if any(_bbox_overlap_in_smaller(grid_bbox, excluded_bbox) >= 0.5 for excluded_bbox in excluded_bboxes):
continue
core_rows = _rows_inside_rule_interval(
rows,
@@ -956,9 +924,7 @@ def _build_closed_rule_grid_candidates(
median_height,
caption_line,
)
- candidate.score = float(
- 100 + len(component) + len(vertical_positions)
- )
+ candidate.score = float(100 + len(component) + len(vertical_positions))
candidates.append(candidate)
return candidates
@@ -985,20 +951,13 @@ def _closed_grid_vertical_track_positions(
min(line.bbox[3], bottom) - max(line.bbox[1], top),
)
position = _bbox_center_x(line.bbox)
- if (
- overlap / grid_height >= 0.9
- and left - edge_tolerance <= position <= right + edge_tolerance
- ):
+ if overlap / grid_height >= 0.9 and left - edge_tolerance <= position <= right + edge_tolerance:
raw_positions.append(position)
position_tolerance = max(1.0, 0.1 * median_height)
position_groups: list[list[float]] = []
for position in sorted(raw_positions):
- if (
- position_groups
- and abs(position - statistics.mean(position_groups[-1]))
- <= position_tolerance
- ):
+ if position_groups and abs(position - statistics.mean(position_groups[-1])) <= position_tolerance:
position_groups[-1].append(position)
else:
position_groups.append([position])
@@ -1017,9 +976,7 @@ def _count_occupied_closed_grid_columns(
center_x = _bbox_center_x(fragment.local_bbox)
matching_columns = [
index
- for index, (left, right) in enumerate(
- zip(vertical_positions, vertical_positions[1:])
- )
+ for index, (left, right) in enumerate(zip(vertical_positions, vertical_positions[1:]))
if left < center_x < right
]
if len(matching_columns) == 1:
@@ -1095,31 +1052,20 @@ def _rule_bands_share_grid_tracks(
if line.orientation == "vertical"
and line.bbox[1] <= top_y + track_tolerance
and line.bbox[3] >= bottom_y - track_tolerance
- and overlap_left - track_tolerance
- <= _bbox_center_x(line.bbox)
- <= overlap_right + track_tolerance
+ and overlap_left - track_tolerance <= _bbox_center_x(line.bbox) <= overlap_right + track_tolerance
]
position_groups: list[list[float]] = []
for position in sorted(raw_positions):
- if (
- position_groups
- and abs(position - statistics.mean(position_groups[-1]))
- <= track_tolerance
- ):
+ if position_groups and abs(position - statistics.mean(position_groups[-1])) <= track_tolerance:
position_groups[-1].append(position)
else:
position_groups.append([position])
positions = [statistics.mean(group) for group in position_groups]
- has_outer_tracks = (
- any(abs(position - overlap_left) <= endpoint_tolerance for position in positions)
- and any(abs(position - overlap_right) <= endpoint_tolerance for position in positions)
+ has_outer_tracks = any(abs(position - overlap_left) <= endpoint_tolerance for position in positions) and any(
+ abs(position - overlap_right) <= endpoint_tolerance for position in positions
)
interior_tracks = [
- position
- for position in positions
- if overlap_left + track_tolerance
- < position
- < overlap_right - track_tolerance
+ position for position in positions if overlap_left + track_tolerance < position < overlap_right - track_tolerance
]
return has_outer_tracks or len(interior_tracks) >= 2
@@ -1155,10 +1101,7 @@ def _group_long_horizontal_rules(
for span_group in span_groups:
unique_lines: list[_LocalAxisLine] = []
for line in sorted(span_group, key=lambda item: _bbox_center_y(item.bbox)):
- if any(
- abs(_bbox_center_y(line.bbox) - _bbox_center_y(item.bbox)) <= 1.0
- for item in unique_lines
- ):
+ 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) >= 2:
@@ -1197,10 +1140,7 @@ def _rows_inside_rule_interval(
output.append(
_VisualRow(
fragments=fragments,
- center_y=sum(
- _bbox_center_y(fragment.local_bbox) for fragment in fragments
- )
- / len(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=clipped_row.visual_row_id,
)
@@ -1217,9 +1157,7 @@ def _every_rule_interval_has_multi_cell_row(
if len(rule_group) < 2:
return False
- for interval_index, (top_rule, bottom_rule) in enumerate(
- zip(rule_group, rule_group[1:])
- ):
+ for interval_index, (top_rule, bottom_rule) in enumerate(zip(rule_group, rule_group[1:])):
top = _bbox_center_y(top_rule.bbox)
bottom = _bbox_center_y(bottom_rule.bbox)
interval_rows = [row for row in rows if top <= row.center_y <= bottom]
@@ -1227,11 +1165,7 @@ def _every_rule_interval_has_multi_cell_row(
continue
# 紧邻顶边界的合并表头可能由 pdftext 输出为一个短 fragment;
# 只放宽高度很小的首区间,避免把远处章节标题接到表格上。
- if (
- interval_index == 0
- and interval_rows
- and bottom - top <= 2.5 * median_height
- ):
+ if interval_index == 0 and interval_rows and bottom - top <= 2.5 * median_height:
continue
return False
return True
@@ -1248,11 +1182,7 @@ def _rule_intervals_are_column_compatible(
for top_rule, bottom_rule in zip(rule_group, rule_group[1:]):
top = _bbox_center_y(top_rule.bbox)
bottom = _bbox_center_y(bottom_rule.bbox)
- interval_rows = [
- row
- for row in rows
- if top <= row.center_y <= bottom and len(row.fragments) >= 2
- ]
+ interval_rows = [row for row in rows if top <= row.center_y <= bottom and len(row.fragments) >= 2]
stable_columns, column_coverage = _count_stable_columns(
interval_rows,
median_height,
@@ -1292,11 +1222,7 @@ def _continuous_table_row_segments(
segments: list[list[_VisualRow]] = []
for row in sorted(rows, key=lambda item: item.center_y):
- if (
- not segments
- or max(0.0, row.bbox[1] - segments[-1][-1].bbox[3])
- > 3.0 * median_height
- ):
+ if not segments or max(0.0, row.bbox[1] - segments[-1][-1].bbox[3]) > 3.0 * median_height:
segments.append([row])
else:
segments[-1].append(row)
@@ -1334,10 +1260,7 @@ def _table_rows_align_with_rule_span(
0.0,
min(rows_bbox[2], rule_bbox[2]) - max(rows_bbox[0], rule_bbox[0]),
)
- return (
- overlap / min(rule_width, rows_width) >= 0.9
- and rows_width >= max(8.0 * median_height, 0.25 * rule_width)
- )
+ return overlap / min(rule_width, rows_width) >= 0.9 and rows_width >= max(8.0 * median_height, 0.25 * rule_width)
def _count_aligned_vertical_rules(
@@ -1368,12 +1291,7 @@ def _compact_fully_ruled_grid_column_count(
"""以完整横竖边界确认两行紧凑网格,并返回物理列数,失败时返回零。"""
rule_height = max(0.1, rule_bbox[3] - rule_bbox[1])
- if (
- len(row_segment) != 2
- or len(dense_rows) != 2
- or len(interval_rules) < 3
- or rule_height > 6.0 * median_height
- ):
+ if len(row_segment) != 2 or len(dense_rows) != 2 or len(interval_rules) < 3 or rule_height > 6.0 * median_height:
return 0
vertical_positions = _full_height_vertical_rule_positions(
@@ -1400,11 +1318,7 @@ def _compact_fully_ruled_grid_column_count(
):
return 0
- grid_boundaries = [
- position
- for position in vertical_positions
- if left_boundary <= position <= right_boundary
- ]
+ grid_boundaries = [position for position in vertical_positions if left_boundary <= position <= right_boundary]
if len(grid_boundaries) < 3:
return 0
grid_intervals = list(zip(grid_boundaries, grid_boundaries[1:]))
@@ -1414,11 +1328,7 @@ def _compact_fully_ruled_grid_column_count(
row_columns: list[int] = []
for fragment in row.fragments:
fragment_center = _bbox_center_x(fragment.local_bbox)
- matching_columns = [
- index
- for index, (left, right) in enumerate(grid_intervals)
- if left <= fragment_center <= right
- ]
+ matching_columns = [index for index, (left, right) in enumerate(grid_intervals) if left <= fragment_center <= right]
if len(matching_columns) != 1:
return 0
column_index = matching_columns[0]
@@ -1448,15 +1358,12 @@ def _full_height_vertical_rule_positions(
continue
overlap = max(
0.0,
- min(line.bbox[3], rule_bbox[3])
- - max(line.bbox[1], rule_bbox[1]),
+ min(line.bbox[3], rule_bbox[3]) - max(line.bbox[1], rule_bbox[1]),
)
if (
overlap / rule_height < 0.8
or line.bbox[3] - line.bbox[1] < 0.8 * rule_height
- or not rule_bbox[0] - median_height
- <= _bbox_center_x(line.bbox)
- <= rule_bbox[2] + median_height
+ or not rule_bbox[0] - median_height <= _bbox_center_x(line.bbox) <= rule_bbox[2] + median_height
):
continue
raw_positions.append(_bbox_center_x(line.bbox))
@@ -1481,17 +1388,11 @@ def _looks_like_page_column_prose(
) -> bool:
"""用双栏占宽率识别夹在远横线间的普通并排正文。"""
- if (
- stable_columns != 2
- or fill_band_count >= 2
- or aligned_vertical_count > 0
- or len(dense_rows) / len(rows) < 0.55
- ):
+ if stable_columns != 2 or fill_band_count >= 2 or aligned_vertical_count > 0 or len(dense_rows) / len(rows) < 0.55:
return False
corridor_width = max(0.1, rule_bbox[2] - rule_bbox[0])
occupied_ratios = [
- sum(fragment.local_bbox[2] - fragment.local_bbox[0] for fragment in row.fragments)
- / corridor_width
+ sum(fragment.local_bbox[2] - fragment.local_bbox[0] for fragment in row.fragments) / corridor_width
for row in dense_rows
]
return statistics.median(occupied_ratios) >= 0.75
@@ -1535,8 +1436,7 @@ def _count_repeated_fill_bands(
for group in groups
if abs(bbox[0] - group[0][0]) <= endpoint_tolerance
and abs(bbox[2] - group[0][2]) <= endpoint_tolerance
- and abs((bbox[3] - bbox[1]) - (group[0][3] - group[0][1]))
- <= endpoint_tolerance
+ and abs((bbox[3] - bbox[1]) - (group[0][3] - group[0][1])) <= endpoint_tolerance
),
None,
)
@@ -1622,14 +1522,14 @@ def _expand_rule_table_candidate(
footnote_rows,
excluded_line_indices=core_line_indices,
)
- annotations = [
- annotation
- for annotation in (caption_annotation, footnote_annotation)
- if annotation is not None
- ]
- annotation_line_indices = set().union(
- *(annotation.line_indices for annotation in annotations),
- ) if annotations else set()
+ annotations = [annotation for annotation in (caption_annotation, footnote_annotation) if annotation is not None]
+ annotation_line_indices = (
+ set().union(
+ *(annotation.line_indices for annotation in annotations),
+ )
+ if annotations
+ else set()
+ )
included_rows = [*caption_rows, *core_rows, *footnote_rows]
local_bbox = _bbox_union(core_local_bbox, _bbox_union_many([row.bbox for row in included_rows]))
return _TableCandidate(
@@ -1675,11 +1575,7 @@ def _build_table_annotation(
line_bboxes: dict[int, BBox] = {}
for fragment in fragments:
existing_bbox = line_bboxes.get(fragment.line_index)
- line_bboxes[fragment.line_index] = (
- fragment.bbox
- if existing_bbox is None
- else _bbox_union(existing_bbox, fragment.bbox)
- )
+ line_bboxes[fragment.line_index] = fragment.bbox if existing_bbox is None else _bbox_union(existing_bbox, fragment.bbox)
return _TableAnnotation(
kind=kind,
bbox=_bbox_union_many(list(line_bboxes.values())),
@@ -1766,11 +1662,7 @@ def _collect_footnote_rows(
bottom = max(bottom, clipped_row.bbox[3])
continue
row_gap = max(0.0, clipped_row.bbox[1] - bottom)
- row_lines = [
- line_by_index[line_index]
- for line_index in line_indices
- if line_index in line_by_index
- ]
+ row_lines = [line_by_index[line_index] for line_index in line_indices if line_index in line_by_index]
row_heights = [
_line_effective_height(
line,
@@ -1780,23 +1672,18 @@ def _collect_footnote_rows(
]
row_height = statistics.median(row_heights) if row_heights else clipped_row.bbox[3] - clipped_row.bbox[1]
row_fonts = {
- line.font_signature
- for line in row_lines
- if line.font_signature is not None and line.font_coverage >= 0.75
+ line.font_signature for line in row_lines if line.font_signature is not None and line.font_coverage >= 0.75
}
if note_chain_started and clipped_row.bbox[3] - rule_bbox[3] > 10.0 * median_height:
break
row_text = _visual_row_text(clipped_row)
explicit_note = _is_table_note_text(row_text)
auxiliary_marker = _extract_auxiliary_table_note_marker(row_text)
- auxiliary_note = (
- auxiliary_marker is not None
- and _table_core_references_marker(
- auxiliary_marker,
- core_lines,
- page_size,
- angle,
- )
+ auxiliary_note = auxiliary_marker is not None and _table_core_references_marker(
+ auxiliary_marker,
+ core_lines,
+ page_size,
+ angle,
)
first_gap_limit = 0.75 if auxiliary_note and not explicit_note else 1.25
if row_gap > (first_gap_limit if not note_chain_started else 1.0) * median_height:
@@ -1827,11 +1714,7 @@ def _collect_footnote_rows(
or note_height is None
or abs(clipped_row.bbox[0] - note_left) > 1.5 * median_height
or not 0.75 <= row_height / note_height <= 1.25
- or (
- note_fonts
- and row_fonts
- and note_fonts.isdisjoint(row_fonts)
- )
+ or (note_fonts and row_fonts and note_fonts.isdisjoint(row_fonts))
or _bbox_axis_overlap_ratio(clipped_row.bbox, rule_bbox, axis="x") < 0.35
):
# 字号、字体或缩进突变表明已进入标题/正文,表注链必须立即终止。
@@ -1864,8 +1747,7 @@ def _table_core_references_marker(
"""要求通用短标记在表格核心中具有上标或紧凑单元格引用。"""
return any(
- _line_has_superscript_marker(line, marker, page_size, angle)
- or _line_has_compact_marker_token(line.text, marker)
+ _line_has_superscript_marker(line, marker, page_size, angle) or _line_has_compact_marker_token(line.text, marker)
for line in core_lines
)
@@ -1925,19 +1807,12 @@ def _line_has_superscript_marker(
normal_height = statistics.median(bbox[3] - bbox[1] for bbox in ordinary_bboxes)
if normal_height <= 0:
continue
- baseline_bboxes = [
- bbox
- for bbox in ordinary_bboxes
- if bbox[3] - bbox[1] >= 0.90 * normal_height
- ]
+ baseline_bboxes = [bbox for bbox in ordinary_bboxes if bbox[3] - bbox[1] >= 0.90 * normal_height]
marker_bboxes = [glyphs[index][1] for index in marker_indices]
marker_height = statistics.median(bbox[3] - bbox[1] for bbox in marker_bboxes)
marker_center = statistics.median(_bbox_center_y(bbox) for bbox in marker_bboxes)
normal_center = statistics.median(_bbox_center_y(bbox) for bbox in baseline_bboxes)
- if (
- marker_height <= 0.85 * normal_height
- and normal_center - marker_center >= 0.12 * normal_height
- ):
+ if marker_height <= 0.85 * normal_height and normal_center - marker_center >= 0.12 * normal_height:
return True
return False
@@ -2081,11 +1956,7 @@ def _count_stable_columns(
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
- ]
+ 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,
@@ -2132,11 +2003,7 @@ def _merge_table_candidate_annotations(
for annotation in candidate.annotations:
existing = next(
- (
- item
- for item in target.annotations
- if item.kind == annotation.kind
- ),
+ (item for item in target.annotations if item.kind == annotation.kind),
None,
)
if existing is None:
@@ -2153,20 +2020,14 @@ def _merge_table_candidate_annotations(
existing.line_indices.update(annotation.line_indices)
for line_index, bbox in annotation.line_bboxes.items():
existing_bbox = existing.line_bboxes.get(line_index)
- existing.line_bboxes[line_index] = (
- bbox
- if existing_bbox is None
- else _bbox_union(existing_bbox, bbox)
- )
+ existing.line_bboxes[line_index] = bbox if existing_bbox is None else _bbox_union(existing_bbox, bbox)
# 重复候选发生角色冲突时以任一候选确认的表体成员为准,避免表头被并入 caption。
retained_annotations: list[_TableAnnotation] = []
for annotation in target.annotations:
annotation.line_indices.difference_update(target.line_indices)
annotation.line_bboxes = {
- line_index: bbox
- for line_index, bbox in annotation.line_bboxes.items()
- if line_index in annotation.line_indices
+ line_index: bbox for line_index, bbox in annotation.line_bboxes.items() if line_index in annotation.line_indices
}
if not annotation.line_indices:
continue
@@ -2196,14 +2057,11 @@ def _materialize_table_blocks(
native_rectangles = coerce_native_table_rectangles(source.path_infos)
for candidate in sorted(candidates, key=lambda item: item.score, reverse=True):
# 候选去重仍使用包含注释的完整框,不能因输出表体收缩而放行重复表格。
- if any(
- _bbox_overlap_in_smaller(candidate.bbox, bbox) >= 0.5
- for bbox in accepted_candidate_bboxes
- ):
+ if any(_bbox_overlap_in_smaller(candidate.bbox, bbox) >= 0.5 for bbox in accepted_candidate_bboxes):
continue
output_angle = candidate.angle
- candidate_annotation_blocks, externalized_line_indices, failed_annotations = (
- _materialize_table_annotations(source, candidate)
+ candidate_annotation_blocks, externalized_line_indices, failed_annotations = _materialize_table_annotations(
+ source, candidate
)
projection_line_indices = _candidate_projection_line_indices(source, candidate)
for annotation in candidate.annotations:
@@ -2227,14 +2085,10 @@ def _materialize_table_blocks(
)
except Exception as exc:
logger.warning(
- "Flash native table recovery failed and fell back to projection: "
- f"bbox={candidate.bbox}, error={exc}"
+ f"Flash native table recovery failed and fell back to projection: bbox={candidate.bbox}, error={exc}"
)
if content:
- logger.debug(
- "Flash native table recovery accepted: "
- f"bbox={body_bbox}, angle={candidate.angle}"
- )
+ logger.debug(f"Flash native table recovery accepted: bbox={body_bbox}, angle={candidate.angle}")
try:
if not content:
# 使用完整原始字符流保留 PDF 物理换行;行索引仅负责表体与注释的所有权认领。
@@ -2337,10 +2191,7 @@ def _build_table_annotation_block(
"angle": candidate.angle,
"content": content,
"_local_line_bboxes": [bbox for _line, bbox in line_geometry],
- "_line_heights": [
- _line_effective_height(line, bbox)
- for line, bbox in line_geometry
- ],
+ "_line_heights": [_line_effective_height(line, bbox) for line, bbox in line_geometry],
"_font_signatures": {
line.font_signature
for line, _bbox in line_geometry
@@ -2354,11 +2205,7 @@ def _build_table_annotation_block(
def _merge_table_annotation_content(line_texts: list[str]) -> str:
"""按正文一致的语言与行末断词规则折叠表格注释原生行。"""
- normalized_lines = [
- normalized
- for text in line_texts
- if (normalized := _normalize_native_run_text(str(text or "")))
- ]
+ normalized_lines = [normalized for text in line_texts if (normalized := _normalize_native_run_text(str(text or "")))]
if not normalized_lines:
return ""
try:
@@ -2454,11 +2301,7 @@ def _expand_candidate_same_baseline_members(
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
- ]
+ 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
diff --git a/mineru/model/flash/pdf/text_blocks.py b/mineru/model/flash/pdf/text_blocks.py
index 282f36c7..918f1c56 100644
--- a/mineru/model/flash/pdf/text_blocks.py
+++ b/mineru/model/flash/pdf/text_blocks.py
@@ -53,8 +53,9 @@ _FIGURE_CAPTION_MARKER_RE = re.compile(
re.IGNORECASE,
)
_INLINE_MATH_RECOVERY_MARKER = "_recovered_inline_math_fragments"
-_FRONT_MATTER_KEYWORDS_RE = re.compile(
- r"^\s*(?:keywords?|key\s+words?|关键词)\s*[::]",
+_PARAGRAPH_FORMULA_CONTEXT_MARKER = "_paragraph_formula_context"
+_FRONT_MATTER_FIELD_RE = re.compile(
+ r"^\s*(?:keywords?|key\s+words?|关键词|中图分类号|文献标识码|文章编号)\s*[::]",
re.IGNORECASE,
)
_LIST_ITEM_RE = re.compile(
@@ -79,6 +80,9 @@ _URL_LINE_RE = re.compile(
r"^\s*(?:https?://|www\.)",
re.IGNORECASE,
)
+_SHORT_SAME_BASELINE_PREFIX_RE = re.compile(
+ r"^(?:[((]\s*\d{1,3}|\d{1,2}\s*[::]\s*\d{2})$",
+)
def _starts_structural_reference_entry(
@@ -732,7 +736,7 @@ def _front_matter_keyword_break_sources(
local_page_height: float,
page_index: int | None,
) -> set[int]:
- """把首页前置信息中的通用关键词行固定为独立文本块起点。"""
+ """把首页关键词和文献元数据行固定为独立文本块起点。"""
if page_index != 0:
return set()
@@ -741,7 +745,7 @@ def _front_matter_keyword_break_sources(
for line, bbox in lane.lines
if line.semantic_type is None
and bbox[1] <= 0.65 * local_page_height
- and _FRONT_MATTER_KEYWORDS_RE.match(line.text) is not None
+ and _FRONT_MATTER_FIELD_RE.match(line.text) is not None
}
@@ -867,9 +871,7 @@ def _build_text_blocks(
split_row_counts: dict[int, int] = {}
for line, _bbox in line_geometry:
if line.visual_row_id is not None and line.split_from_row:
- split_row_counts[line.visual_row_id] = (
- split_row_counts.get(line.visual_row_id, 0) + 1
- )
+ split_row_counts[line.visual_row_id] = split_row_counts.get(line.visual_row_id, 0) + 1
for lane in lanes:
lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
@@ -1021,6 +1023,7 @@ def _build_text_blocks(
if line.font_signature is not None and line.font_coverage >= 0.5
},
"_inline_math_regions": [region for line in component_lines for region in line.inline_math_regions],
+ _PARAGRAPH_FORMULA_CONTEXT_MARKER: any(line.paragraph_formula_context for line in component_lines),
"_lane_interval": (
component_local_lane.left,
component_local_lane.right,
@@ -1036,11 +1039,94 @@ def _build_text_blocks(
),
}
)
+ blocks = _merge_short_same_baseline_prefix_blocks(
+ blocks,
+ page_size,
+ )
blocks = _merge_spatial_text_components(blocks, page_size)
blocks = _merge_list_intro_text_components(blocks)
blocks = _merge_unterminated_text_components(blocks)
blocks = _merge_overlapping_same_line_text_blocks(blocks, page_size)
- return _merge_inline_math_fragment_text_blocks(blocks, page_size)
+ blocks = _merge_inline_math_fragment_text_blocks(
+ blocks,
+ page_size,
+ )
+ return _merge_paragraph_formula_context_blocks(
+ blocks,
+ )
+
+
+def _merge_short_same_baseline_prefix_blocks(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """合并括号序号或时刻等短前缀与右侧同基线正文。"""
+
+ replacements: dict[int, dict[str, Any]] = {}
+ consumed: set[int] = set()
+ for prefix_index, prefix in enumerate(blocks):
+ prefix_rows = prefix.get("_local_line_bboxes")
+ prefix_content = str(prefix.get("content") or "").strip()
+ if (
+ prefix_index in consumed
+ or prefix.get("type") != "text"
+ or not isinstance(prefix_rows, list)
+ or len(prefix_rows) != 1
+ or _SHORT_SAME_BASELINE_PREFIX_RE.match(prefix_content) is None
+ ):
+ continue
+ prefix_bbox = prefix_rows[0]
+ prefix_heights = [
+ float(height)
+ for height in prefix.get("_line_heights", [])
+ if isinstance(height, (int, float)) and float(height) > 0
+ ]
+ prefix_height = statistics.median(prefix_heights) if prefix_heights else max(0.1, prefix_bbox[3] - prefix_bbox[1])
+ angle = int(prefix.get("angle", 0) or 0) % 360
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ matches: list[tuple[float, int]] = []
+ for host_index, host in enumerate(blocks):
+ host_rows = host.get("_local_line_bboxes")
+ if (
+ host_index == prefix_index
+ or host_index in consumed
+ or host.get("type") != "text"
+ or int(host.get("angle", 0) or 0) % 360 != angle
+ or not isinstance(host_rows, list)
+ or not host_rows
+ ):
+ continue
+ host_bbox = host_rows[0]
+ host_width = host_bbox[2] - host_bbox[0]
+ horizontal_gap = host_bbox[0] - prefix_bbox[2]
+ if (
+ host_bbox[0] < prefix_bbox[2]
+ or horizontal_gap > 1.25 * prefix_height
+ or host_width < 0.15 * local_page_width
+ or _bbox_axis_overlap_ratio(
+ prefix_bbox,
+ host_bbox,
+ axis="y",
+ )
+ < 0.5
+ ):
+ continue
+ matches.append((horizontal_gap, host_index))
+ if not matches:
+ continue
+ _gap, host_index = min(matches)
+ replacement_index = min(prefix_index, host_index)
+ replacement = _merge_internal_text_block_group(
+ blocks,
+ [prefix_index, host_index],
+ preserve_visual_spaces=True,
+ )
+ replacement["type"] = "text"
+ replacements[replacement_index] = replacement
+ consumed.update({prefix_index, host_index})
+ return [
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
+ ]
def _blocks_share_boundary_visual_row(
@@ -1259,6 +1345,115 @@ def _merge_inline_math_fragment_text_blocks(
return _merge_inline_math_paragraph_continuations(output, page_size)
+def _merge_paragraph_formula_context_blocks(
+ blocks: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ """把误似行间公式的复杂行内分式与同栏前后正文恢复成一个块。"""
+
+ terminal_re = re.compile(
+ r"[.!?。!?][\]\)})】》”’'\"]*$",
+ )
+ consumed: set[int] = set()
+ replacements: dict[int, dict[str, Any]] = {}
+ seed_indices = [
+ index
+ for index, block in enumerate(blocks)
+ if block.get("type") == "text" and block.get(_PARAGRAPH_FORMULA_CONTEXT_MARKER) is True
+ ]
+ for seed_index in seed_indices:
+ if seed_index in consumed:
+ continue
+ group = {seed_index}
+ changed = True
+ while changed:
+ changed = False
+ for candidate_index, candidate in enumerate(blocks):
+ if candidate_index in group or candidate_index in consumed or candidate.get("type") != "text":
+ continue
+ for member_index in group:
+ member = blocks[member_index]
+ if int(candidate.get("angle", 0) or 0) % 360 != int(member.get("angle", 0) or 0) % 360:
+ continue
+ pair_heights = [
+ float(height)
+ for block in (candidate, member)
+ for height in block.get("_line_heights", [])
+ if isinstance(height, (int, float)) and float(height) > 0
+ ]
+ if not pair_heights:
+ continue
+ pair_height = statistics.median(pair_heights)
+ if not _components_share_lane_role(
+ candidate,
+ member,
+ pair_height,
+ ):
+ continue
+ candidate_bbox = candidate["bbox"]
+ member_bbox = member["bbox"]
+ vertical_gap = max(
+ candidate_bbox[1] - member_bbox[3],
+ member_bbox[1] - candidate_bbox[3],
+ 0.0,
+ )
+ if vertical_gap > 1.5 * pair_height:
+ continue
+ candidate_below = candidate_bbox[1] >= member_bbox[3]
+ member_below = member_bbox[1] >= candidate_bbox[3]
+ if candidate_below and (
+ candidate.get("_hard_break_before") is True
+ or terminal_re.search(str(member.get("content") or "").rstrip()) is not None
+ ):
+ continue
+ if member_below and (
+ member.get("_hard_break_before") is True
+ or terminal_re.search(str(candidate.get("content") or "").rstrip()) is not None
+ ):
+ continue
+ group.add(candidate_index)
+ changed = True
+ break
+ if changed:
+ break
+ if len(group) < 2:
+ continue
+ ordered_group = sorted(group)
+ replacement_index = min(ordered_group)
+ merged = _merge_internal_text_block_group(
+ blocks,
+ ordered_group,
+ )
+ local_rows = [
+ bbox
+ for bbox in merged.get("_local_line_bboxes", [])
+ if isinstance(bbox, (list, tuple))
+ and len(bbox) == 4
+ ]
+ maximum_width = max(
+ (bbox[2] - bbox[0] for bbox in local_rows),
+ default=0.0,
+ )
+ body_rows = [
+ bbox
+ for bbox in local_rows
+ if bbox[2] - bbox[0] >= 0.75 * maximum_width
+ ]
+ if len(body_rows) >= 2:
+ # 复杂分式可能比正文左缘多探出少量 glyph;公开框按重复满行边界稳定收口。
+ merged_bbox = merged["bbox"]
+ merged["bbox"] = (
+ min(bbox[0] for bbox in body_rows),
+ merged_bbox[1],
+ max(bbox[2] for bbox in body_rows),
+ merged_bbox[3],
+ )
+ replacements[replacement_index] = merged
+ consumed.update(ordered_group)
+ return [
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
+ ]
+
+
def _merge_residual_narrow_math_text_blocks(
blocks: list[dict[str, Any]],
page_size: tuple[float, float],
@@ -2205,6 +2400,9 @@ def _merge_internal_text_block_group(
merged["_inline_math_regions"] = [
region for index in ordered_indices for region in blocks[index].get("_inline_math_regions", [])
]
+ merged[_PARAGRAPH_FORMULA_CONTEXT_MARKER] = any(
+ blocks[index].get(_PARAGRAPH_FORMULA_CONTEXT_MARKER) is True for index in ordered_indices
+ )
return merged
diff --git a/mineru/model/flash/pdf/titles.py b/mineru/model/flash/pdf/titles.py
index 5a05298f..ea6a1b21 100644
--- a/mineru/model/flash/pdf/titles.py
+++ b/mineru/model/flash/pdf/titles.py
@@ -4,7 +4,9 @@
from __future__ import annotations
+import re
import statistics
+import unicodedata
from collections import Counter
from dataclasses import replace
from typing import Literal
@@ -45,6 +47,310 @@ from .line_layout import (
_title_fonts_compatible,
)
+
+_NUMBERED_SECTION_TITLE_RE = re.compile(
+ r"^(?P<number>\d+(?:\s*\.\s*\d+)*)\s+(?P<label>\S.*)$",
+)
+_SECTION_NUMBER_ONLY_RE = re.compile(
+ r"^\d+(?:\s*\.\s*\d+)*\.?$",
+)
+_SECTION_TITLE_TERMINAL_RE = re.compile(
+ r"[.!?。!?::;;,,]$",
+)
+_UNNUMBERED_SECTION_HEADING_RE = re.compile(
+ r"^(?:introduction|references?|bibliography|acknowledg(?:e)?ments?|引言|绪论|参考文献|参考资料)$",
+ re.IGNORECASE,
+)
+
+
+def _normalized_section_title_text(text: str) -> str:
+ """规范全半角编号和空白,仅用于结构标题规则判断。"""
+
+ return re.sub(
+ r"\s+",
+ " ",
+ unicodedata.normalize("NFKC", text),
+ ).strip()
+
+
+def _is_plausible_section_number(
+ number: str,
+ label: str = "",
+) -> bool:
+ """排除年代、小数值和整句正文冒充的章节编号。"""
+
+ parts = [int(part) for part in re.findall(r"\d+", number)]
+ if not parts or any(part > 99 for part in parts):
+ return False
+ if len(parts) > 1 and parts[0] == 0:
+ return False
+ if len(parts) == 1 and parts[0] > 12:
+ return False
+ stripped_label = label.lstrip()
+ if stripped_label and not stripped_label[0].isalpha():
+ return False
+ if stripped_label and stripped_label[0].isascii() and stripped_label[0].isalpha() and not stripped_label[0].isupper():
+ return False
+ if len(re.findall(r"\d+(?:\.\d+)?", label)) >= 2:
+ return False
+ return not any(char in label for char in ",,;;::。!?!?")
+
+
+def _section_title_has_body_followers(
+ title_bbox: BBox,
+ geometry: list[tuple[_LineItem, BBox]],
+ body_height: float,
+ local_page_width: float,
+ *,
+ minimum_count: int,
+) -> bool:
+ """检查紧随标题的同栏常规正文行,避免把页码和数值标成标题。"""
+
+ followers = 0
+ for line, bbox in sorted(
+ geometry,
+ key=lambda item: (item[1][1], item[1][0], item[0].source_index),
+ ):
+ if bbox[1] <= title_bbox[1] + 0.4 * body_height:
+ continue
+ if bbox[1] - title_bbox[3] > 8.0 * body_height:
+ break
+ line_height = _line_effective_height(line, bbox)
+ horizontally_related = (
+ _bbox_axis_overlap_ratio(title_bbox, bbox, axis="x") >= 0.15 or abs(bbox[0] - title_bbox[0]) <= 2.5 * body_height
+ )
+ if (
+ line.semantic_type is None
+ and horizontally_related
+ and bbox[2] - bbox[0] >= 0.25 * local_page_width
+ and 0.7 <= line_height / body_height <= 1.4
+ ):
+ followers += 1
+ if followers >= minimum_count:
+ return True
+ return False
+
+
+def _classify_explicit_section_titles(
+ lines: list[_LineItem],
+ page_size: tuple[float, float],
+ *,
+ container_bboxes: list[BBox],
+ document_body_profile: _DocumentBodyProfile | None,
+) -> None:
+ """以通用编号行和紧凑结构转折补齐正文同字号章节标题。"""
+
+ if document_body_profile is None or document_body_profile.body_height <= 0:
+ return
+ body_height = document_body_profile.body_height
+ for angle in sorted(
+ {
+ line.angle
+ for line in lines
+ if (
+ line.semantic_type is None
+ or line.explicit_section_title
+ )
+ and not line.title_suppressed
+ }
+ ):
+ geometry = sorted(
+ [
+ (
+ line,
+ _rotate_bbox_to_upright(
+ line.bbox,
+ page_size,
+ angle,
+ ),
+ )
+ for line in lines
+ if line.angle == angle and line.semantic_type is None and not line.title_suppressed
+ ],
+ key=lambda item: (
+ item[1][1],
+ item[1][0],
+ item[0].source_index,
+ ),
+ )
+ if not geometry:
+ continue
+ 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]
+ local_containers = [
+ _rotate_bbox_to_upright(
+ bbox,
+ page_size,
+ angle,
+ )
+ for bbox in container_bboxes
+ ]
+ numbered_groups: list[list[tuple[_LineItem, BBox]]] = []
+ grouped_sources: set[int] = set()
+ for line, bbox in geometry:
+ normalized = _normalized_section_title_text(line.text)
+ numbered_match = _NUMBERED_SECTION_TITLE_RE.match(
+ normalized,
+ )
+ if numbered_match is not None and _is_plausible_section_number(
+ numbered_match.group("number"),
+ numbered_match.group("label"),
+ ):
+ numbered_groups.append([(line, bbox)])
+ grouped_sources.add(line.source_index)
+ continue
+ if _SECTION_NUMBER_ONLY_RE.match(normalized) is None or not _is_plausible_section_number(normalized):
+ continue
+ marker_height = _line_effective_height(line, bbox)
+ companions = [
+ (candidate, candidate_bbox)
+ for candidate, candidate_bbox in geometry
+ if candidate is not line
+ and candidate.source_index not in grouped_sources
+ and candidate_bbox[0] >= bbox[2]
+ and candidate_bbox[0] - bbox[2] <= 4.0 * max(body_height, marker_height)
+ and _bbox_axis_overlap_ratio(
+ bbox,
+ candidate_bbox,
+ axis="y",
+ )
+ >= 0.5
+ and candidate_bbox[2] - candidate_bbox[0] <= 0.55 * local_page_width
+ and _SECTION_TITLE_TERMINAL_RE.search(
+ _normalized_section_title_text(candidate.text),
+ )
+ is None
+ ]
+ if not companions:
+ continue
+ companion = min(
+ companions,
+ key=lambda item: (
+ item[1][0] - bbox[2],
+ item[1][1],
+ ),
+ )
+ numbered_groups.append([(line, bbox), companion])
+ grouped_sources.update({line.source_index, companion[0].source_index})
+
+ for group in numbered_groups:
+ title_bbox = _bbox_union_many(
+ [bbox for _line, bbox in group],
+ )
+ group_line_ids = {id(line) for line, _bbox in group}
+ preceding = [
+ previous_bbox
+ for previous_line, previous_bbox in geometry
+ if id(previous_line) not in group_line_ids
+ and previous_bbox[3] <= title_bbox[1]
+ and (
+ _bbox_axis_overlap_ratio(
+ previous_bbox,
+ title_bbox,
+ axis="x",
+ )
+ >= 0.15
+ or abs(previous_bbox[0] - title_bbox[0]) <= 2.5 * body_height
+ )
+ ]
+ gap_above = title_bbox[1] - max(previous_bbox[3] for previous_bbox in preceding) if preceding else body_height
+ if (
+ title_bbox[2] - title_bbox[0] > 0.7 * local_page_width
+ or not 0.1 * local_page_height <= _bbox_center_y(title_bbox) <= 0.93 * local_page_height
+ or any(
+ _bbox_axis_overlap_ratio(
+ title_bbox,
+ container_bbox,
+ axis="x",
+ )
+ >= 0.8
+ and _bbox_axis_overlap_ratio(
+ title_bbox,
+ container_bbox,
+ axis="y",
+ )
+ >= 0.8
+ for container_bbox in local_containers
+ )
+ or not _section_title_has_body_followers(
+ title_bbox,
+ geometry,
+ body_height,
+ local_page_width,
+ minimum_count=1,
+ )
+ or gap_above < 0.4 * body_height
+ ):
+ continue
+ for line, _bbox in group:
+ line.semantic_type = "paragraph_title"
+ line.structural_title = True
+ line.explicit_section_title = True
+
+ for line, bbox in geometry:
+ if line.semantic_type is not None:
+ continue
+ normalized = _normalized_section_title_text(line.text)
+ canonical_heading = normalized.strip(
+ "[][]【】()()",
+ ).replace(" ", "")
+ if (
+ _UNNUMBERED_SECTION_HEADING_RE.fullmatch(
+ canonical_heading,
+ )
+ is None
+ or not 2 <= len(normalized) <= 24
+ or _SECTION_TITLE_TERMINAL_RE.search(normalized) is not None
+ or any(char in normalized for char in "[][]")
+ or bbox[2] - bbox[0] > 0.3 * local_page_width
+ or _bbox_center_y(bbox) < 0.35 * local_page_height
+ or not 0.75 <= _line_effective_height(line, bbox) / body_height <= 1.4
+ or any(
+ _bbox_axis_overlap_ratio(
+ bbox,
+ container_bbox,
+ axis="x",
+ )
+ >= 0.8
+ and _bbox_axis_overlap_ratio(
+ bbox,
+ container_bbox,
+ axis="y",
+ )
+ >= 0.8
+ for container_bbox in local_containers
+ )
+ or not _section_title_has_body_followers(
+ bbox,
+ geometry,
+ body_height,
+ local_page_width,
+ minimum_count=2,
+ )
+ ):
+ continue
+ preceding = [
+ previous_bbox
+ for previous_line, previous_bbox in geometry
+ if previous_line is not line
+ and previous_bbox[3] <= bbox[1]
+ and (
+ _bbox_axis_overlap_ratio(
+ previous_bbox,
+ bbox,
+ axis="x",
+ )
+ >= 0.15
+ or abs(previous_bbox[0] - bbox[0]) <= 2.5 * body_height
+ )
+ ]
+ gap_above = bbox[1] - max(previous_bbox[3] for previous_bbox in preceding) if preceding else body_height
+ if gap_above >= 0.5 * body_height:
+ line.semantic_type = "paragraph_title"
+ line.structural_title = True
+ line.explicit_section_title = True
+
+
def _classify_page_titles(
lines: list[_LineItem],
page_size: tuple[float, float],
@@ -57,17 +363,20 @@ def _classify_page_titles(
) -> None:
"""只用页面几何与字体排版标注首页文档标题和各页段落标题。"""
- for angle in sorted({line.angle for line in lines if line.semantic_type is None}):
+ for angle in sorted({line.angle for line in lines if line.semantic_type is None and not line.title_suppressed}):
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 line.angle == angle
+ and (
+ line.semantic_type is None
+ or line.explicit_section_title
+ )
+ and not line.title_suppressed
]
if not line_geometry:
continue
- median_height = statistics.median(
- _line_effective_height(line, bbox) for line, bbox in line_geometry
- )
+ 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)
@@ -78,10 +387,7 @@ def _classify_page_titles(
lanes,
median_height,
)
- local_container_bboxes = [
- _rotate_bbox_to_upright(bbox, page_size, angle)
- for bbox in container_bboxes
- ]
+ local_container_bboxes = [_rotate_bbox_to_upright(bbox, page_size, angle) for bbox in container_bboxes]
grid_title_suppressions.update(
_find_container_visual_row_title_suppressions(
line_geometry,
@@ -159,15 +465,23 @@ def _classify_page_titles(
)
_demote_visual_container_caption_titles(
line_geometry,
+ [_rotate_bbox_to_upright(bbox, page_size, angle) for bbox in (caption_container_bboxes or [])],
+ )
+ _demote_sentence_tail_titles(
[
- _rotate_bbox_to_upright(bbox, page_size, angle)
- for bbox in (caption_container_bboxes or [])
+ (
+ line,
+ _rotate_bbox_to_upright(
+ line.bbox,
+ page_size,
+ angle,
+ ),
+ )
+ for line in lines
+ if line.angle == angle and line.semantic_type in {None, "paragraph_title"} and not line.title_suppressed
],
)
- if (
- document_body_profile is not None
- and document_body_profile.has_style_scale_repairs
- ):
+ if document_body_profile is not None and document_body_profile.has_style_scale_repairs:
_demote_non_structural_anomaly_titles(line_geometry)
if page_index == 0:
_demote_front_matter_non_document_titles(
@@ -184,10 +498,7 @@ def _demote_non_structural_anomaly_titles(
"""在 loose 高度异常文档中只保留预先通过结构转折校验的段落标题。"""
for line, _bbox in line_geometry:
- if (
- line.semantic_type == "paragraph_title"
- and not line.structural_title
- ):
+ if line.semantic_type == "paragraph_title" and not line.structural_title:
line.semantic_type = None
@@ -216,11 +527,7 @@ def _infer_document_body_profile(
prepared.page_size,
line.angle,
)
- local_page_width = (
- prepared.page_size[1]
- if line.angle in {90, 270}
- else prepared.page_size[0]
- )
+ local_page_width = prepared.page_size[1] if line.angle in {90, 270} else prepared.page_size[0]
height = (
_line_canonical_style_scale(line, local_bbox)
if use_canonical_scale
@@ -262,11 +569,7 @@ def _infer_document_body_profile(
height_clusters.append([(height, page_index, normalized_width)])
else:
target.append((height, page_index, normalized_width))
- cross_page_clusters = [
- cluster
- for cluster in height_clusters
- if len({item[1] for item in cluster}) >= 2
- ]
+ cross_page_clusters = [cluster for cluster in height_clusters if len({item[1] for item in cluster}) >= 2]
eligible_clusters = cross_page_clusters or height_clusters
body_cluster = max(
eligible_clusters,
@@ -314,9 +617,7 @@ def _infer_document_body_profile(
body_weight=body_weight,
regular_fonts=regular_fonts,
has_style_scale_repairs=any(
- line.style_scale_repaired
- for prepared in prepared_pages
- for line in prepared.remaining_lines
+ line.style_scale_repaired for prepared in prepared_pages for line in prepared.remaining_lines
),
)
@@ -330,10 +631,7 @@ def _classify_document_structural_titles(
) -> None:
"""用跨页稳定栏带和段前后转折补齐正文同字号标题。"""
- if (
- document_body_profile is None
- or not document_body_profile.has_style_scale_repairs
- ):
+ if document_body_profile is None or not document_body_profile.has_style_scale_repairs:
return
probe_pages = [
replace(
@@ -379,9 +677,7 @@ def _classify_document_structural_titles(
prepared.page_size,
line.angle,
)
- layout_ratio = (
- local_bbox[3] - local_bbox[1]
- ) / body_height
+ layout_ratio = (local_bbox[3] - local_bbox[1]) / body_height
if (
line_key in legacy_title_sources
or layout_ratio >= 1.8
@@ -409,8 +705,7 @@ def _classify_document_structural_titles(
canonical_style_prototypes = {
style_key
for style_key, page_indices in canonical_style_candidate_pages.items()
- if len(set(page_indices)) >= 2
- or max(Counter(page_indices).values(), default=0) >= 3
+ if len(set(page_indices)) >= 2 or max(Counter(page_indices).values(), default=0) >= 3
}
if canonical_style_prototypes:
for prepared in prepared_pages:
@@ -477,7 +772,7 @@ def _classify_secondary_document_title_bands(
)
centered = abs(_bbox_center_x(bbox) - 0.5 * local_page_width) <= 0.08 * local_page_width
if (
- line_scale < 1.35 * body_height
+ line_scale < 1.2 * body_height
or not 0.45 <= width_ratio <= 0.85
or not centered
or not 0.12 * local_page_height <= _bbox_center_y(bbox) <= 0.75 * local_page_height
@@ -501,7 +796,7 @@ def _classify_secondary_document_title_bands(
candidate_bbox[1] - title_members[-1][1][3],
)
if (
- candidate_scale < 1.3 * body_height
+ candidate_scale < 1.15 * body_height
or vertical_gap
> 1.5
* max(
@@ -524,43 +819,58 @@ def _classify_secondary_document_title_bands(
followers = geometry[cursor:]
if len(followers) < 3:
continue
- metadata = followers[:2]
- if any(
- not 0.2 * local_page_width <= metadata_bbox[2] - metadata_bbox[0] <= 0.7 * local_page_width
- or abs(_bbox_center_x(metadata_bbox) - 0.5 * local_page_width) > 0.12 * local_page_width
- or _line_effective_height(
- metadata_line,
- metadata_bbox,
+ matched_metadata: list[tuple[_LineItem, BBox]] | None = None
+ for metadata_count in (2, 3):
+ if len(followers) <= metadata_count:
+ continue
+ metadata = followers[:metadata_count]
+ if any(
+ not 0.2 * local_page_width <= metadata_bbox[2] - metadata_bbox[0] <= 0.7 * local_page_width
+ or abs(_bbox_center_x(metadata_bbox) - 0.5 * local_page_width) > 0.12 * local_page_width
+ or _line_effective_height(
+ metadata_line,
+ metadata_bbox,
+ )
+ > line_scale
+ for metadata_line, metadata_bbox in metadata
+ ):
+ continue
+ metadata_gaps = [
+ max(
+ 0.0,
+ current[1][1] - previous[1][3],
+ )
+ for previous, current in zip(
+ metadata,
+ metadata[1:],
+ )
+ ]
+ _abstract_line, abstract_bbox = followers[metadata_count]
+ title_to_metadata_gap = max(
+ 0.0,
+ metadata[0][1][1] - title_members[-1][1][3],
)
- > line_scale
- for metadata_line, metadata_bbox in metadata
- ):
- continue
- title_to_metadata_gap = max(
- 0.0,
- metadata[0][1][1] - title_members[-1][1][3],
- )
- metadata_gap = max(
- 0.0,
- metadata[1][1][1] - metadata[0][1][3],
- )
- abstract_line, abstract_bbox = followers[2]
- abstract_gap = max(
- 0.0,
- abstract_bbox[1] - metadata[1][1][3],
- )
- if (
- title_to_metadata_gap > 4.5 * body_height
- or metadata_gap > 2.0 * body_height
- or abstract_gap > 4.0 * body_height
- or abstract_bbox[2] - abstract_bbox[0] < 0.7 * local_page_width
- or abstract_bbox[0] > 0.15 * local_page_width
- or abstract_bbox[2] < 0.85 * local_page_width
- ):
+ abstract_gap = max(
+ 0.0,
+ abstract_bbox[1] - metadata[-1][1][3],
+ )
+ if (
+ title_to_metadata_gap <= 4.5 * body_height
+ and all(gap <= 2.0 * body_height for gap in metadata_gaps)
+ and abstract_gap <= 4.0 * body_height
+ and abstract_bbox[2] - abstract_bbox[0] >= 0.7 * local_page_width
+ and abstract_bbox[0] <= 0.15 * local_page_width
+ and abstract_bbox[2] >= 0.85 * local_page_width
+ ):
+ matched_metadata = metadata
+ break
+ if matched_metadata is None:
continue
for title_line, _title_bbox in title_members:
title_line.semantic_type = "doc_title"
consumed_sources.add(title_line.source_index)
+ for metadata_line, _metadata_bbox in matched_metadata:
+ metadata_line.title_suppressed = True
def _canonical_title_style_key(
@@ -588,28 +898,14 @@ def _classify_document_structural_title_candidates(
"""在 canonical 行副本上收集所有满足结构转折的标题候选。"""
body_height = max(0.1, document_body_profile.body_height)
- strong_candidates: list[
- tuple[int, _LineItem, tuple[str, int] | None, float]
- ] = []
- start_candidates: list[
- tuple[int, _LineItem, tuple[str, int] | None, float]
- ] = []
- accepted_anchor_positions: list[
- tuple[int, int, float, float]
- ] = []
+ strong_candidates: list[tuple[int, _LineItem, tuple[str, int] | None, float]] = []
+ start_candidates: list[tuple[int, _LineItem, tuple[str, int] | None, float]] = []
+ accepted_anchor_positions: list[tuple[int, int, float, float]] = []
for page_index, prepared in enumerate(prepared_pages):
container_bboxes = [
- block["bbox"]
- for block in prepared.fixed_blocks
- if not isinstance(block.get("_inline_visual_row_id"), int)
+ block["bbox"] for block in prepared.fixed_blocks if not isinstance(block.get("_inline_visual_row_id"), int)
]
- for angle in sorted(
- {
- line.angle
- for line in prepared.remaining_lines
- if line.semantic_type is None
- }
- ):
+ for angle in sorted({line.angle for line in prepared.remaining_lines if line.semantic_type is None}):
geometry = sorted(
[
(
@@ -621,8 +917,7 @@ def _classify_document_structural_title_candidates(
),
)
for line in prepared.remaining_lines
- if line.angle == angle
- and line.semantic_type is None
+ if line.angle == angle and line.semantic_type is None
],
key=lambda item: (
item[1][1],
@@ -632,20 +927,9 @@ def _classify_document_structural_title_candidates(
)
if len(geometry) < 4:
continue
- local_page_width = (
- prepared.page_size[1]
- if angle in {90, 270}
- else prepared.page_size[0]
- )
- local_page_height = (
- prepared.page_size[0]
- if angle in {90, 270}
- else prepared.page_size[1]
- )
- median_height = statistics.median(
- _line_canonical_style_scale(line, bbox)
- for line, bbox in geometry
- )
+ local_page_width = prepared.page_size[1] if angle in {90, 270} else prepared.page_size[0]
+ local_page_height = prepared.page_size[0] if angle in {90, 270} else prepared.page_size[1]
+ median_height = statistics.median(_line_canonical_style_scale(line, bbox) for line, bbox in geometry)
lanes = _infer_text_lanes(
geometry,
local_page_width,
@@ -661,20 +945,14 @@ def _classify_document_structural_title_candidates(
for bbox in container_bboxes
]
for line, bbox in geometry:
- if (
- page_index == 0
- and _bbox_center_y(bbox)
- < 0.64 * local_page_height
- ):
+ if page_index == 0 and _bbox_center_y(bbox) < 0.64 * local_page_height:
continue
related_lanes = [
lane
for lane in lanes
if not lane.is_span
and len(lane.lines) >= 3
- and lane.left - body_height
- <= _bbox_center_x(bbox)
- <= lane.right + body_height
+ and lane.left - body_height <= _bbox_center_x(bbox) <= lane.right + body_height
]
if not related_lanes:
continue
@@ -687,10 +965,7 @@ def _classify_document_structural_title_candidates(
)
lane_width = max(0.1, lane.right - lane.left)
width_ratio = (bbox[2] - bbox[0]) / lane_width
- style_ratio = (
- _line_canonical_style_scale(line, bbox)
- / body_height
- )
+ style_ratio = _line_canonical_style_scale(line, bbox) / body_height
left_offset = (bbox[0] - lane.left) / body_height
regular_font = _line_uses_document_regular_font(
line,
@@ -712,13 +987,9 @@ def _classify_document_structural_title_candidates(
for other_line, other_bbox in geometry
if other_line is not line
and bbox[1] < other_bbox[1]
- and other_bbox[1] - bbox[3]
- <= 3.0 * body_height
- and lane.left - body_height
- <= other_bbox[0]
- <= lane.left + 3.5 * body_height
- and other_bbox[2] - other_bbox[0]
- >= 0.4 * lane_width
+ and other_bbox[1] - bbox[3] <= 3.0 * body_height
+ and lane.left - body_height <= other_bbox[0] <= lane.left + 3.5 * body_height
+ and other_bbox[2] - other_bbox[0] >= 0.4 * lane_width
]
if not followers:
continue
@@ -726,24 +997,15 @@ def _classify_document_structural_title_candidates(
line.source_index,
(None, None),
)
- layout_ratio = (
- bbox[3] - bbox[1]
- ) / body_height
- if (
- regular_font
- and layout_ratio < 1.3
- and line.font_coverage < 0.75
- ):
+ layout_ratio = (bbox[3] - bbox[1]) / body_height
+ if regular_font and layout_ratio < 1.3 and line.font_coverage < 0.75:
continue
standard_transition = (
gap_above is not None
and gap_below is not None
and gap_above >= 0.65 * body_height
and gap_below >= 0.35 * body_height
- and (
- not regular_font
- or gap_below <= 1.5 * body_height
- )
+ and (not regular_font or gap_below <= 1.5 * body_height)
)
low_coverage_wide_transition = (
gap_above is not None
@@ -758,11 +1020,8 @@ def _classify_document_structural_title_candidates(
if low_coverage_wide_transition and any(
anchor_page_index == page_index
and anchor_angle == angle
- and abs(anchor_left - lane.left)
- <= body_height
- and 0
- < _bbox_center_y(bbox) - anchor_center_y
- <= 12.0 * body_height
+ and abs(anchor_left - lane.left) <= body_height
+ and 0 < _bbox_center_y(bbox) - anchor_center_y <= 12.0 * body_height
for (
anchor_page_index,
anchor_angle,
@@ -781,19 +1040,18 @@ def _classify_document_structural_title_candidates(
and layout_ratio <= 1.3
)
family_key = (
- _normalized_font_family(line.font_signature),
- line.font_signature[1],
- ) if line.font_signature is not None else None
+ (
+ _normalized_font_family(line.font_signature),
+ line.font_signature[1],
+ )
+ if line.font_signature is not None
+ else None
+ )
if (
standard_transition
or low_coverage_wide_transition
or compact_regular_transition
- or (
- gap_above is None
- and gap_below is not None
- and gap_below >= 0.6 * body_height
- and not regular_font
- )
+ or (gap_above is None and gap_below is not None and gap_below >= 0.6 * body_height and not regular_font)
):
strong_candidates.append(
(
@@ -816,13 +1074,7 @@ def _classify_document_structural_title_candidates(
gap_above is None
and bbox[1] <= 0.18 * local_page_height
and width_ratio <= 0.6
- and (
- line.font_coverage >= 0.75
- or (
- not regular_font
- and line.font_coverage >= 0.5
- )
- )
+ and (line.font_coverage >= 0.75 or (not regular_font and line.font_coverage >= 0.5))
):
start_candidates.append(
(
@@ -837,22 +1089,13 @@ def _classify_document_structural_title_candidates(
line.semantic_type = "paragraph_title"
line.structural_title = True
strong_families_by_page = {
- (page_index, family_key)
- for page_index, _line, family_key, _layout_ratio in strong_candidates
- if family_key is not None
+ (page_index, family_key) for page_index, _line, family_key, _layout_ratio in strong_candidates if family_key is not None
}
for page_index, line, family_key, _layout_ratio in start_candidates:
- if (
- not _line_uses_document_regular_font(
- line,
- document_body_profile,
- )
- or (
- family_key is not None
- and (page_index, family_key)
- in strong_families_by_page
- )
- ):
+ if not _line_uses_document_regular_font(
+ line,
+ document_body_profile,
+ ) or (family_key is not None and (page_index, family_key) in strong_families_by_page):
line.semantic_type = "paragraph_title"
line.structural_title = True
@@ -881,15 +1124,9 @@ def _collect_legacy_paragraph_title_sources(
for line in prepared.remaining_lines
]
container_bboxes = [
- block["bbox"]
- for block in prepared.fixed_blocks
- if not isinstance(block.get("_inline_visual_row_id"), int)
- ]
- caption_container_bboxes = [
- block["bbox"]
- for block in prepared.fixed_blocks
- if block.get("type") in {"image", "code"}
+ block["bbox"] for block in prepared.fixed_blocks if not isinstance(block.get("_inline_visual_row_id"), int)
]
+ caption_container_bboxes = [block["bbox"] for block in prepared.fixed_blocks if block.get("type") in {"image", "code"}]
_classify_page_titles(
probe_lines,
prepared.page_size,
@@ -899,11 +1136,7 @@ def _collect_legacy_paragraph_title_sources(
document_body_profile=legacy_profile,
document_title_profile=document_title_profile,
)
- output.update(
- (page_index, line.source_index)
- for line in probe_lines
- if line.semantic_type == "paragraph_title"
- )
+ output.update((page_index, line.source_index) for line in probe_lines if line.semantic_type == "paragraph_title")
return output
@@ -923,21 +1156,18 @@ def _classify_body_height_section_titles(
if body_height <= 0:
return
- for angle in sorted({line.angle for line in lines if line.semantic_type is None}):
+ for angle in sorted({line.angle for line in lines if line.semantic_type is None and not line.title_suppressed}):
line_geometry = sorted(
[
(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 line.angle == angle and line.semantic_type is None and not line.title_suppressed
],
key=lambda item: (item[1][1], item[1][0], item[0].source_index),
)
if len(line_geometry) < 8:
continue
- median_height = statistics.median(
- _line_effective_height(line, bbox)
- for line, bbox in line_geometry
- )
+ 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(
@@ -948,9 +1178,7 @@ def _classify_body_height_section_titles(
lane_by_source: dict[int, _TextLane] = {}
regular_gaps: list[float] = []
for lane in lanes:
- lane.lines.sort(
- key=lambda item: (item[1][1], item[1][0], item[0].source_index)
- )
+ lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
regular_gap, _gap_mad = _estimate_lane_gap(lane)
regular_gaps.append(regular_gap)
for line, _bbox in lane.lines:
@@ -958,16 +1186,9 @@ def _classify_body_height_section_titles(
if not lane_by_source:
continue
- page_regular_gap = (
- statistics.median(regular_gaps)
- if regular_gaps
- else 0.2 * body_height
- )
+ page_regular_gap = statistics.median(regular_gaps) if regular_gaps else 0.2 * body_height
physical_gaps = _build_physical_title_gap_map(line_geometry)
- local_container_bboxes = [
- _rotate_bbox_to_upright(bbox, page_size, angle)
- for bbox in container_bboxes
- ]
+ local_container_bboxes = [_rotate_bbox_to_upright(bbox, page_size, angle) for bbox in container_bboxes]
candidates: list[tuple[_LineItem, BBox, _TextLane]] = []
for line, bbox in line_geometry:
lane = lane_by_source.get(line.source_index)
@@ -996,21 +1217,14 @@ def _classify_body_height_section_titles(
gap_above = physical_gaps.get(line.source_index, (None, None))[0]
if gap_above is not None and gap_above <= 0.25 * body_height:
continue
- starts_body = (
- gap_above is None
- and bbox[1] <= 0.2 * local_page_height
- )
- has_extra_gap = (
- gap_above is not None
- and gap_above - page_regular_gap >= 0.75 * body_height
- )
+ starts_body = gap_above is None and bbox[1] <= 0.2 * local_page_height
+ has_extra_gap = gap_above is not None and gap_above - page_regular_gap >= 0.75 * body_height
has_full_width_follower = any(
follower_bbox[2] - follower_bbox[0]
>= 0.75
* max(
0.1,
- lane_by_source[follower_line.source_index].right
- - lane_by_source[follower_line.source_index].left,
+ lane_by_source[follower_line.source_index].right - lane_by_source[follower_line.source_index].left,
)
for follower_line, follower_bbox in followers
if follower_line.source_index in lane_by_source
@@ -1023,10 +1237,7 @@ def _classify_body_height_section_titles(
1
for peer_line, peer_bbox, _peer_lane in candidates
if abs(peer_bbox[0] - bbox[0]) <= body_height
- and 0.9
- <= _line_effective_height(peer_line, peer_bbox)
- / _line_effective_height(line, bbox)
- <= 1.1
+ and 0.9 <= _line_effective_height(peer_line, peer_bbox) / _line_effective_height(line, bbox) <= 1.1
and _title_fonts_compatible(line, peer_line)
)
if compatible_count >= 2:
@@ -1048,11 +1259,7 @@ def _body_height_section_followers(
for line, bbox in line_geometry:
if line is candidate_line or bbox[1] <= candidate_bbox[1] + 0.4 * body_height:
continue
- if not (
- candidate_bbox[0] - 0.75 * body_height
- <= bbox[0]
- <= candidate_bbox[0] + 1.5 * body_height
- ):
+ if not (candidate_bbox[0] - 0.75 * body_height <= bbox[0] <= candidate_bbox[0] + 1.5 * body_height):
continue
top_pitch = bbox[1] - previous_top
if top_pitch < 0.5 * body_height:
@@ -1092,9 +1299,7 @@ def _infer_document_title_profile(
for page_index, prepared in enumerate(prepared_pages):
probe_lines = [replace(line) for line in prepared.remaining_lines]
container_bboxes = [
- block["bbox"]
- for block in prepared.fixed_blocks
- if not isinstance(block.get("_inline_visual_row_id"), int)
+ block["bbox"] for block in prepared.fixed_blocks if not isinstance(block.get("_inline_visual_row_id"), int)
]
_classify_page_titles(
probe_lines,
@@ -1119,15 +1324,8 @@ def _infer_document_title_profile(
]
if not geometry:
continue
- median_height = statistics.median(
- _line_effective_height(line, bbox)
- for line, bbox in geometry
- )
- local_page_width = (
- prepared.page_size[1]
- if angle in {90, 270}
- else prepared.page_size[0]
- )
+ median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in geometry)
+ local_page_width = prepared.page_size[1] if angle in {90, 270} else prepared.page_size[0]
lanes = _infer_text_lanes(
geometry,
local_page_width,
@@ -1143,14 +1341,10 @@ def _infer_document_title_profile(
]
for lane in lanes:
for line, bbox in lane.lines:
- line_height_ratio = (
- _line_effective_height(line, bbox)
- / document_body_profile.body_height
- )
+ line_height_ratio = _line_effective_height(line, bbox) / document_body_profile.body_height
large_unresolved_seed = (
page_index > 0
- and
- line.semantic_type is None
+ and line.semantic_type is None
and line_height_ratio >= 1.3
and bbox[2] - bbox[0] <= 0.8 * local_page_width
and not _line_inside_visual_container(
@@ -1159,19 +1353,12 @@ def _infer_document_title_profile(
)
)
if (
- (
- line.semantic_type != "paragraph_title"
- and not large_unresolved_seed
- )
+ (line.semantic_type != "paragraph_title" and not large_unresolved_seed)
or line.font_signature is None
or line.font_coverage < 0.75
):
continue
- row_identity = (
- line.visual_row_id
- if line.visual_row_id is not None
- else line.source_index
- )
+ row_identity = line.visual_row_id if line.visual_row_id is not None else line.source_index
row_key = (angle, row_identity)
if row_key in seen_rows:
continue
@@ -1202,11 +1389,7 @@ def _infer_document_title_profile(
clusters: list[list[tuple[str, int, float, float | None, Literal["left", "center"], float, int]]] = []
for seed in sorted(seeds, key=lambda item: (item[0], item[1], item[4], item[2])):
target = next(
- (
- cluster
- for cluster in clusters
- if _title_profile_seed_matches_cluster(seed, cluster)
- ),
+ (cluster for cluster in clusters if _title_profile_seed_matches_cluster(seed, cluster)),
None,
)
if target is None:
@@ -1273,8 +1456,7 @@ def _title_profile_seed_matches_cluster(
seed[3] is None
or not weights
or abs(seed[3] - statistics.median(weights)) < 100.0
- or max(seed[3], statistics.median(weights))
- < 1.15 * min(seed[3], statistics.median(weights))
+ or max(seed[3], statistics.median(weights)) < 1.15 * min(seed[3], statistics.median(weights))
)
return (
seed[0] == reference[0]
@@ -1294,9 +1476,7 @@ def _title_profile_alignment(
"""返回标题行的栏内对齐模式及归一化锚点偏移。"""
lane_width = max(0.1, lane.right - lane.left)
- center_offset = (
- _bbox_center_x(bbox) - (lane.left + lane.right) / 2.0
- ) / lane_width
+ center_offset = (_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) / lane_width
left_offset = (bbox[0] - lane.left) / lane_width
if abs(center_offset) <= 0.12 and bbox[2] - bbox[0] <= 0.85 * lane_width:
return "center", center_offset
@@ -1336,10 +1516,7 @@ def _build_physical_title_gap_map(
if _bbox_axis_overlap_ratio(bbox, other_bbox, axis="x") < 0.1:
# 双栏同高度正文并非当前行的物理上下文,不能抹掉真实标题留白。
continue
- if (
- line.visual_row_id is not None
- and other_line.visual_row_id == line.visual_row_id
- ):
+ if line.visual_row_id is not None and other_line.visual_row_id == line.visual_row_id:
continue
other_center = _bbox_center_y(other_bbox)
if other_center < line_center:
@@ -1402,12 +1579,7 @@ def _find_repeated_grid_title_suppressions(
bands: list[list[tuple[int, int, float]]] = []
for candidate in sorted(candidates, key=lambda item: item[2]):
target = next(
- (
- band
- for band in bands
- if abs(candidate[2] - statistics.median(item[2] for item in band))
- <= 0.5 * median_height
- ),
+ (band for band in bands if abs(candidate[2] - statistics.median(item[2] for item in band)) <= 0.5 * median_height),
None,
)
if target is None:
@@ -1538,30 +1710,18 @@ def _classify_document_title(
centered = abs(_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) <= 0.15 * lane_width
page_centered = abs(_bbox_center_x(bbox) - 0.5 * local_page_width) <= 0.15 * local_page_width
page_width_ratio = (bbox[2] - bbox[0]) / max(0.1, local_page_width)
- spans_columns_fallback = (
- lane.is_span
- and centered
- and width_ratio >= 0.65
- and document_height_ratio >= 1.3
- )
+ 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)
- or (
- not page_centered
- and page_width_ratio < 0.45
- and height_ratio < 1.8
- )
+ or (not page_centered and page_width_ratio < 0.45 and height_ratio < 1.8)
):
continue
top_preference = max(0.0, 0.45 - _bbox_center_y(bbox) / local_page_height)
top_preference_weight = (
- 4.0
- if document_body_profile is not None
- and document_body_profile.has_style_scale_repairs
- else 1.0
+ 4.0 if document_body_profile is not None and document_body_profile.has_style_scale_repairs else 1.0
)
score = (
height_ratio
@@ -1615,11 +1775,7 @@ def _expand_document_title_across_lanes(
) -> float | None:
"""跨错误推断栏扩展紧邻、同字号且对齐的多行文档标题。"""
- title_items = [
- item
- for item in line_geometry
- if item[0].semantic_type == "doc_title"
- ]
+ title_items = [item for item in line_geometry if item[0].semantic_type == "doc_title"]
if not title_items:
return document_title_bottom
selected_ids = {id(line) for line, _bbox in title_items}
@@ -1627,10 +1783,7 @@ def _expand_document_title_across_lanes(
while changed:
changed = False
title_bbox = _bbox_union_many([bbox for _line, bbox in title_items])
- title_height = statistics.median(
- _line_effective_height(line, bbox)
- for line, bbox in title_items
- )
+ title_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in title_items)
anchors = [line for line, _bbox in title_items]
candidates = [
item
@@ -1652,36 +1805,20 @@ def _expand_document_title_across_lanes(
)
if not 0.8 <= candidate_height / max(0.1, title_height) <= 1.25:
continue
- if not any(
- _document_title_fonts_compatible(anchor, candidate_line)
- for anchor in anchors
- ):
+ if not any(_document_title_fonts_compatible(anchor, candidate_line) for anchor in anchors):
continue
vertical_gap = max(
candidate_bbox[1] - title_bbox[3],
title_bbox[1] - candidate_bbox[3],
0.0,
)
- centered = (
- abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(title_bbox))
- <= 0.18 * local_page_width
- )
- aligned = (
- abs(candidate_bbox[0] - title_bbox[0])
- <= 0.75 * title_height
- )
+ centered = abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(title_bbox)) <= 0.18 * local_page_width
+ aligned = abs(candidate_bbox[0] - title_bbox[0]) <= 0.75 * title_height
title_width = max(0.1, title_bbox[2] - title_bbox[0])
candidate_width = candidate_bbox[2] - candidate_bbox[0]
- aligned_continuation = (
- aligned and candidate_width >= 0.25 * title_width
- )
- centered_continuation = (
- centered and candidate_width >= 0.45 * title_width
- )
- if (
- vertical_gap > 1.1 * title_height
- or not (aligned_continuation or centered_continuation)
- ):
+ aligned_continuation = aligned and candidate_width >= 0.25 * title_width
+ centered_continuation = centered and candidate_width >= 0.45 * title_width
+ if vertical_gap > 1.1 * title_height or not (aligned_continuation or centered_continuation):
continue
candidate_line.semantic_type = "doc_title"
title_items.append((candidate_line, candidate_bbox))
@@ -1701,64 +1838,37 @@ def _classify_additional_document_title_bands(
) -> float | None:
"""用居中译题与后续作者行结构补充首页第二文档标题带。"""
- if (
- document_title_bottom is None
- or document_body_profile is None
- or not document_body_profile.has_style_scale_repairs
- ):
+ if document_title_bottom is None or document_body_profile is None or not document_body_profile.has_style_scale_repairs:
return document_title_bottom
body_height = max(0.1, document_body_profile.body_height)
ordered = sorted(
line_geometry,
key=lambda item: (item[1][1], item[1][0], item[0].source_index),
)
- selected_bottoms = [
- bbox[3]
- for line, bbox in ordered
- if line.semantic_type == "doc_title"
- ]
+ selected_bottoms = [bbox[3] for line, bbox in ordered if line.semantic_type == "doc_title"]
for index, (line, bbox) in enumerate(ordered):
if line.semantic_type is not None:
continue
center_y = _bbox_center_y(bbox)
width_ratio = (bbox[2] - bbox[0]) / max(0.1, local_page_width)
- if not (
- document_title_bottom + 4.0 * body_height
- <= center_y
- <= 0.58 * local_page_height
- ):
+ if not (document_title_bottom + 4.0 * body_height <= center_y <= 0.58 * local_page_height):
continue
if not 0.4 <= width_ratio <= 0.8:
continue
- if (
- abs(_bbox_center_x(bbox) - 0.5 * local_page_width)
- > 0.08 * local_page_width
- ):
+ if abs(_bbox_center_x(bbox) - 0.5 * local_page_width) > 0.08 * local_page_width:
continue
if _line_uses_document_regular_font(line, document_body_profile):
continue
following = [
- item
- for item in ordered[index + 1 :]
- if item[0].semantic_type is None
- and _bbox_center_y(item[1]) > center_y
+ item for item in ordered[index + 1 :] if item[0].semantic_type is None and _bbox_center_y(item[1]) > center_y
]
if not following:
continue
_next_line, next_bbox = following[0]
- next_width_ratio = (
- next_bbox[2] - next_bbox[0]
- ) / max(0.1, local_page_width)
- next_centered = (
- abs(_bbox_center_x(next_bbox) - 0.5 * local_page_width)
- <= 0.12 * local_page_width
- )
+ next_width_ratio = (next_bbox[2] - next_bbox[0]) / max(0.1, local_page_width)
+ next_centered = abs(_bbox_center_x(next_bbox) - 0.5 * local_page_width) <= 0.12 * local_page_width
vertical_gap = max(0.0, next_bbox[1] - bbox[3])
- if (
- not next_centered
- or next_width_ratio > 0.45
- or vertical_gap > 2.0 * body_height
- ):
+ if not next_centered or next_width_ratio > 0.45 or vertical_gap > 2.0 * body_height:
continue
line.semantic_type = "doc_title"
selected_bottoms.append(bbox[3])
@@ -1774,21 +1884,14 @@ def _demote_front_matter_non_document_titles(
) -> None:
"""把首页最后标题带后的作者与单位行降回正文。"""
- if (
- document_title_bottom is None
- or document_body_profile is None
- or not document_body_profile.has_style_scale_repairs
- ):
+ if document_title_bottom is None or document_body_profile is None or not document_body_profile.has_style_scale_repairs:
return
boundary = max(
document_title_bottom + 2.5 * document_body_profile.body_height,
0.46 * local_page_height,
)
for line, bbox in line_geometry:
- if (
- line.semantic_type == "paragraph_title"
- and _bbox_center_y(bbox) <= boundary
- ):
+ if line.semantic_type == "paragraph_title" and _bbox_center_y(bbox) <= boundary:
line.semantic_type = None
@@ -1804,30 +1907,19 @@ def _classify_cross_lane_centered_section_titles(
"""用正文栏中心、上下留白和正文邻行补标被单独推成窄栏的标题。"""
stable_lanes = [
- lane
- for lane in lanes
- if not lane.is_span
- and len(lane.lines) >= 5
- and lane.right - lane.left >= 0.2 * local_page_width
+ lane for lane in lanes if not lane.is_span and len(lane.lines) >= 5 and lane.right - lane.left >= 0.2 * local_page_width
]
for line, bbox in line_geometry:
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
- candidate_lanes = [
- lane
- for lane in stable_lanes
- if lane.left <= _bbox_center_x(bbox) <= lane.right
- ]
+ candidate_lanes = [lane for lane in stable_lanes if lane.left <= _bbox_center_x(bbox) <= lane.right]
if not candidate_lanes:
continue
lane = min(
candidate_lanes,
- key=lambda candidate: abs(
- _bbox_center_x(bbox)
- - 0.5 * (candidate.left + candidate.right)
- ),
+ key=lambda candidate: abs(_bbox_center_x(bbox) - 0.5 * (candidate.left + candidate.right)),
)
profile = _infer_lane_body_profile(lane)
lane_width = max(0.1, lane.right - lane.left)
@@ -1835,17 +1927,11 @@ def _classify_cross_lane_centered_section_titles(
line_height = _line_effective_height(line, bbox)
if not 0.08 * lane_width <= line_width <= 0.7 * lane_width:
continue
- if (
- abs(_bbox_center_x(bbox) - 0.5 * (lane.left + lane.right))
- > 0.05 * lane_width
- ):
+ if abs(_bbox_center_x(bbox) - 0.5 * (lane.left + lane.right)) > 0.05 * lane_width:
continue
if not 0.75 <= line_height / max(0.1, profile.body_height) <= 1.3:
continue
- if (
- document_title_bottom is not None
- and bbox[1] <= document_title_bottom + profile.body_height
- ):
+ if document_title_bottom is not None and bbox[1] <= document_title_bottom + profile.body_height:
continue
if _line_inside_visual_container(bbox, container_bboxes) or _line_near_visual_container(
bbox,
@@ -1859,20 +1945,10 @@ def _classify_cross_lane_centered_section_titles(
if item[0] is not line
and item[0].semantic_type is None
and item[1][2] - item[1][0] >= 0.5 * lane_width
- and 0.75
- <= _line_effective_height(*item) / max(0.1, profile.body_height)
- <= 1.3
- ]
- rows_above = [
- item
- for item in body_rows
- if _bbox_center_y(item[1]) < _bbox_center_y(bbox)
- ]
- rows_below = [
- item
- for item in body_rows
- if _bbox_center_y(item[1]) > _bbox_center_y(bbox)
+ and 0.75 <= _line_effective_height(*item) / max(0.1, profile.body_height) <= 1.3
]
+ rows_above = [item for item in body_rows if _bbox_center_y(item[1]) < _bbox_center_y(bbox)]
+ rows_below = [item for item in body_rows if _bbox_center_y(item[1]) > _bbox_center_y(bbox)]
if not rows_above or not rows_below:
continue
previous = max(rows_above, key=lambda item: _bbox_center_y(item[1]))
@@ -1881,8 +1957,7 @@ def _classify_cross_lane_centered_section_titles(
key=lambda item: _bbox_center_y(item[1]),
)
if len(following_rows) < 3 or any(
- _effective_text_row_gap(previous_row, current_row)
- > profile.regular_gap + 0.75 * profile.body_height
+ _effective_text_row_gap(previous_row, current_row) > profile.regular_gap + 0.75 * profile.body_height
for previous_row, current_row in zip(
following_rows[:3],
following_rows[1:3],
@@ -1895,8 +1970,7 @@ def _classify_cross_lane_centered_section_titles(
if (
gap_above < 0.3 * profile.body_height
or gap_below < -0.1 * profile.body_height
- or max(gap_above, gap_below)
- < profile.regular_gap + 0.2 * profile.body_height
+ or max(gap_above, gap_below) < profile.regular_gap + 0.2 * profile.body_height
):
continue
line.semantic_type = "paragraph_title"
@@ -1908,11 +1982,7 @@ def _demote_cross_lane_body_continuation_titles(
) -> None:
"""把紧接上一正文行、同字号同字体的短续行从标题降回正文。"""
- stable_lanes = [
- lane
- for lane in lanes
- if not lane.is_span and len(lane.lines) >= 4
- ]
+ stable_lanes = [lane for lane in lanes if not lane.is_span and len(lane.lines) >= 4]
for line, bbox in line_geometry:
if line.semantic_type != "paragraph_title":
continue
@@ -1945,33 +2015,22 @@ def _demote_cross_lane_body_continuation_titles(
)
if (
same_family
- and 0.9
- <= line_height / max(0.1, previous_height)
- <= 1.1
- and bbox[1] - previous_bbox[3]
- <= 0.2 * max(line_height, previous_height)
- and abs(bbox[0] - previous_bbox[0])
- <= 0.75 * max(line_height, previous_height)
- and previous_bbox[2] - previous_bbox[0]
- >= 2.0 * (bbox[2] - bbox[0])
+ and 0.9 <= line_height / max(0.1, previous_height) <= 1.1
+ and bbox[1] - previous_bbox[3] <= 0.2 * max(line_height, previous_height)
+ and abs(bbox[0] - previous_bbox[0]) <= 0.75 * max(line_height, previous_height)
+ and previous_bbox[2] - previous_bbox[0] >= 2.0 * (bbox[2] - bbox[0])
):
line.semantic_type = None
continue
- candidate_lanes = [
- lane
- for lane in stable_lanes
- if lane.left <= _bbox_center_x(bbox) <= lane.right
- ]
+ candidate_lanes = [lane for lane in stable_lanes if lane.left <= _bbox_center_x(bbox) <= lane.right]
if not candidate_lanes:
continue
lane = min(
candidate_lanes,
- key=lambda candidate: abs(
- _bbox_center_x(bbox)
- - 0.5 * (candidate.left + candidate.right)
- ),
+ key=lambda candidate: abs(_bbox_center_x(bbox) - 0.5 * (candidate.left + candidate.right)),
)
lane_width = max(0.1, lane.right - lane.left)
+ lane_profile = _infer_lane_body_profile(lane)
if bbox[2] - bbox[0] > 0.55 * lane_width:
continue
preceding = [
@@ -2006,7 +2065,19 @@ def _demote_cross_lane_body_continuation_titles(
continue
if previous_bbox[2] - previous_bbox[0] < 0.5 * lane_width:
continue
- if bbox[1] - previous_bbox[3] > 0.15 * max(line_height, previous_height):
+ maximum_gap = 0.15 * max(line_height, previous_height)
+ if (
+ re.search(
+ r"[.!?。!?][\]\)})】》”’'\"]*$",
+ line.text.rstrip(),
+ )
+ is not None
+ ):
+ maximum_gap = max(
+ maximum_gap,
+ lane_profile.regular_gap + 0.35 * lane_profile.body_height,
+ )
+ if bbox[1] - previous_bbox[3] > maximum_gap:
continue
if abs(bbox[0] - lane.left) > max(1.0, 0.75 * line_height):
continue
@@ -2026,11 +2097,7 @@ def _classify_cross_lane_emphasized_section_titles(
"""用正文栏左缘、强调字体和段间留白补标跨栏推断失败的小节标题。"""
stable_lanes = [
- lane
- for lane in lanes
- if not lane.is_span
- and len(lane.lines) >= 5
- and lane.right - lane.left >= 0.2 * local_page_width
+ lane for lane in lanes if not lane.is_span and len(lane.lines) >= 5 and lane.right - lane.left >= 0.2 * local_page_width
]
for line, bbox in line_geometry:
if line.semantic_type is not None or line.font_signature is None:
@@ -2041,11 +2108,7 @@ def _classify_cross_lane_emphasized_section_titles(
continue
if not 0.07 * local_page_height <= _bbox_center_y(bbox) <= 0.93 * local_page_height:
continue
- candidate_lanes = [
- lane
- for lane in stable_lanes
- if lane.left <= _bbox_center_x(bbox) <= lane.right
- ]
+ candidate_lanes = [lane for lane in stable_lanes if lane.left <= _bbox_center_x(bbox) <= lane.right]
if not candidate_lanes:
continue
lane = min(
@@ -2053,11 +2116,7 @@ def _classify_cross_lane_emphasized_section_titles(
key=lambda candidate: abs(bbox[0] - candidate.left),
)
profile = _infer_lane_body_profile(lane)
- if (
- profile.body_font is None
- or line.font_signature == profile.body_font
- or line.font_coverage < 0.75
- ):
+ if profile.body_font is None or line.font_signature == profile.body_font or line.font_coverage < 0.75:
continue
lane_width = max(0.1, lane.right - lane.left)
line_height = _line_effective_height(line, bbox)
@@ -2067,10 +2126,7 @@ def _classify_cross_lane_emphasized_section_titles(
continue
if not 0.8 <= line_height / max(0.1, profile.body_height) <= 1.35:
continue
- if (
- document_title_bottom is not None
- and bbox[1] <= document_title_bottom + 2.0 * profile.body_height
- ):
+ if document_title_bottom is not None and bbox[1] <= document_title_bottom + 2.0 * profile.body_height:
continue
if _line_inside_visual_container(bbox, container_bboxes) or _line_near_visual_container(
bbox,
@@ -2086,16 +2142,8 @@ def _classify_cross_lane_emphasized_section_titles(
and item[0].font_signature == profile.body_font
and item[1][2] - item[1][0] >= 0.45 * lane_width
]
- rows_above = [
- item
- for item in body_rows
- if _bbox_center_y(item[1]) < _bbox_center_y(bbox)
- ]
- rows_below = [
- item
- for item in body_rows
- if _bbox_center_y(item[1]) > _bbox_center_y(bbox)
- ]
+ rows_above = [item for item in body_rows if _bbox_center_y(item[1]) < _bbox_center_y(bbox)]
+ rows_below = [item for item in body_rows if _bbox_center_y(item[1]) > _bbox_center_y(bbox)]
if not rows_above or not rows_below:
continue
previous = max(rows_above, key=lambda item: _bbox_center_y(item[1]))
@@ -2128,8 +2176,7 @@ def _is_wide_leading_title_continuation(
and _bbox_center_y(candidate_bbox) < _bbox_center_y(title_bbox)
and -0.1 * pair_height <= vertical_gap <= 0.15 * pair_height
and _bbox_axis_overlap_ratio(title_bbox, candidate_bbox, axis="x") >= 0.8
- and abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(title_bbox))
- <= 0.5 * pair_height
+ and abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(title_bbox)) <= 0.5 * pair_height
)
@@ -2142,9 +2189,7 @@ def _expand_cross_lane_paragraph_title_neighbors(
while changed:
changed = False
title_items = [
- item
- for item in line_geometry
- if item[0].semantic_type == "paragraph_title"
+ item for item in line_geometry if item[0].semantic_type == "paragraph_title" and not item[0].explicit_section_title
]
for title_line, title_bbox in title_items:
title_height = _line_effective_height(title_line, title_bbox)
@@ -2183,10 +2228,8 @@ def _expand_cross_lane_paragraph_title_neighbors(
if vertical_gap > 0.35 * max(title_height, candidate_height):
continue
if (
- _bbox_axis_overlap_ratio(title_bbox, candidate_bbox, axis="x")
- < 0.2
- and abs(candidate_bbox[0] - title_bbox[0])
- > 2.0 * title_height
+ _bbox_axis_overlap_ratio(title_bbox, candidate_bbox, axis="x") < 0.2
+ and abs(candidate_bbox[0] - title_bbox[0]) > 2.0 * title_height
):
continue
candidate_line.semantic_type = "paragraph_title"
@@ -2212,19 +2255,85 @@ def _demote_visual_container_caption_titles(
continue
if _bbox_axis_overlap_ratio(bbox, container_bbox, axis="x") < 0.35:
continue
- if (
- abs(_bbox_center_x(bbox) - _bbox_center_x(container_bbox))
- > 0.35
- * max(
- container_bbox[2] - container_bbox[0],
- bbox[2] - bbox[0],
- )
+ if abs(_bbox_center_x(bbox) - _bbox_center_x(container_bbox)) > 0.35 * max(
+ container_bbox[2] - container_bbox[0],
+ bbox[2] - bbox[0],
):
continue
line.semantic_type = None
break
+def _demote_sentence_tail_titles(
+ line_geometry: list[tuple[_LineItem, BBox]],
+) -> None:
+ """把紧接未完正文、以句末标点结束的短行标题降回正文。"""
+
+ for line, bbox in line_geometry:
+ if (
+ line.semantic_type != "paragraph_title"
+ or re.search(
+ r"[.!?。!?][\]\)})】》”’'\"]*$",
+ line.text.rstrip(),
+ )
+ is None
+ ):
+ continue
+ line_height = _line_effective_height(line, bbox)
+ preceding = [
+ item
+ for item in line_geometry
+ if item[0] is not line
+ and item[0].semantic_type is None
+ and item[1][3] <= bbox[1]
+ and abs(item[1][0] - bbox[0]) <= 0.75 * line_height
+ ]
+ if not preceding:
+ continue
+ previous_line, previous_bbox = max(
+ preceding,
+ key=lambda item: item[1][3],
+ )
+ previous_height = _line_effective_height(
+ previous_line,
+ previous_bbox,
+ )
+ same_family = (
+ previous_line.font_signature is None
+ or line.font_signature is None
+ or _font_signatures_share_family(
+ previous_line.font_signature,
+ line.font_signature,
+ )
+ )
+ bbox_height = max(0.1, bbox[3] - bbox[1])
+ previous_bbox_height = max(
+ 0.1,
+ previous_bbox[3] - previous_bbox[1],
+ )
+ compatible_height = (same_family and 0.75 <= line_height / max(0.1, previous_height) <= 1.25) or (
+ 0.8 <= bbox_height / previous_bbox_height <= 1.2
+ )
+ if (
+ compatible_height
+ and bbox[1] - previous_bbox[3]
+ <= 0.9
+ * max(
+ line_height,
+ previous_height,
+ bbox_height,
+ previous_bbox_height,
+ )
+ and previous_bbox[2] - previous_bbox[0] >= 1.5 * (bbox[2] - bbox[0])
+ and re.search(
+ r"[.!?。!?][\]\)})】》”’'\"]*$",
+ previous_line.text.rstrip(),
+ )
+ is None
+ ):
+ line.semantic_type = None
+
+
def _document_title_fonts_compatible(
first: _LineItem,
second: _LineItem,
@@ -2252,27 +2361,15 @@ def _document_title_uses_page_fallback(
"""判断首页标题是否依赖跨栏 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
+ _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 = (
- document_body_profile.body_height
- if document_body_profile is not None
- else statistics.median(column_body_heights)
- )
- return any(
- 1.3 <= title_height / max(0.1, document_body_height) < 1.4
- for title_height in title_heights
+ document_body_profile.body_height if document_body_profile is not None else statistics.median(column_body_heights)
)
+ return any(1.3 <= title_height / max(0.1, document_body_height) < 1.4 for title_height in title_heights)
def _classify_paragraph_titles_in_lane(
@@ -2308,10 +2405,7 @@ def _classify_paragraph_titles_in_lane(
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
- )
+ 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 (
@@ -2329,15 +2423,12 @@ def _classify_paragraph_titles_in_lane(
document_body_profile,
document_title_profile,
)
- title_profile_size_conflict = (
- title_prototype is None
- and _line_conflicts_document_title_profile(
- line,
- bbox,
- lane,
- document_body_profile,
- document_title_profile,
- )
+ title_profile_size_conflict = title_prototype is None and _line_conflicts_document_title_profile(
+ line,
+ bbox,
+ lane,
+ document_body_profile,
+ document_title_profile,
)
inside_visual_container = _line_inside_visual_container(
bbox,
@@ -2348,9 +2439,7 @@ def _classify_paragraph_titles_in_lane(
container_bboxes,
profile.body_height,
)
- if inside_visual_container or (
- near_visual_container and title_prototype is None
- ):
+ if inside_visual_container or (near_visual_container and title_prototype is None):
continue
recurrent_regular_font = _line_uses_document_regular_font(
@@ -2363,10 +2452,7 @@ def _classify_paragraph_titles_in_lane(
and line_height >= 0.9 * document_body_profile.body_height
)
reference_body_height = profile.body_height
- if (
- profile.body_row_count < 3
- and document_body_profile is not None
- ):
+ if profile.body_row_count < 3 and document_body_profile is not None:
reference_body_height = document_body_profile.body_height
if document_regular_body_candidate and document_body_profile is not None:
reference_body_height = max(
@@ -2377,11 +2463,7 @@ def _classify_paragraph_titles_in_lane(
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
- if (
- line.median_glyph_width is not None
- and bbox[2] - bbox[0] <= 1.25 * line.median_glyph_width
- and height_ratio < 1.18
- ):
+ if line.median_glyph_width is not None and bbox[2] - bbox[0] <= 1.25 * line.median_glyph_width and height_ratio < 1.18:
continue
style_differs = (
not recurrent_regular_font
@@ -2481,9 +2563,7 @@ def _classify_paragraph_titles_in_lane(
)
weak_regular_pitch_body_candidate = (
document_body_profile is not None
- and 0.9
- <= line_height / document_body_profile.body_height
- <= 1.1
+ and 0.9 <= line_height / document_body_profile.body_height <= 1.1
and title_prototype is None
and (not centered or width_ratio >= 0.75)
and not weight_emphasized
@@ -2501,18 +2581,11 @@ def _classify_paragraph_titles_in_lane(
continue
prototype_promotion = (
title_prototype is not None
- and (
- width_ratio <= 0.9
- or (bbox[2] - bbox[0]) / max(0.1, local_page_width) <= 0.8
- )
+ and (width_ratio <= 0.9 or (bbox[2] - bbox[0]) / max(0.1, local_page_width) <= 0.8)
and (centered or left_aligned)
and (
- (
- document_body_profile is not None
- and line_height >= 1.18 * document_body_profile.body_height
- )
- or
- near_visual_container
+ (document_body_profile is not None and line_height >= 1.18 * document_body_profile.body_height)
+ or near_visual_container
or (has_following_body_row and gap_above_excess >= 0.1)
or gap_above_excess >= 0.35
)
@@ -2533,25 +2606,16 @@ def _classify_paragraph_titles_in_lane(
continue
if (
document_body_profile is not None
- and 0.9
- <= line_height / document_body_profile.body_height
- <= 1.1
+ and 0.9 <= line_height / document_body_profile.body_height <= 1.1
and title_prototype is None
and centered
and not has_following_body_row
and not compact_text_section
):
continue
- if (
- height_ratio < 0.9
- and not inside_front_matter
- and not has_following_body_row
- and not compact_text_section
- ):
+ if height_ratio < 0.9 and not inside_front_matter and not has_following_body_row and not compact_text_section:
continue
- if width_ratio >= 0.9 and height_ratio < 1.15 and not (
- style_differs and gap_above >= 0.65
- ):
+ 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 or compact_local_transition:
@@ -2577,22 +2641,13 @@ def _classify_paragraph_titles_in_lane(
if left_aligned:
score += 0.25
- precisely_centered = (
- abs(
- _bbox_center_x(bbox)
- - (lane.left + lane.right) / 2.0
- )
- <= 0.05 * lane_width
- )
+ precisely_centered = abs(_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) <= 0.05 * lane_width
centered_structural_fallback = (
0.75 <= height_ratio <= 1.15
and precisely_centered
and width_ratio <= 0.7
and not inside_front_matter
- and not (
- page_index == 0
- and _bbox_center_y(bbox) <= 0.2 * local_page_height
- )
+ and not (page_index == 0 and _bbox_center_y(bbox) <= 0.2 * local_page_height)
and 0.35 <= gap_above <= 1.5
and 0.2 <= gap_below <= 1.5
and has_following_body_row
@@ -2611,11 +2666,7 @@ def _classify_paragraph_titles_in_lane(
or centered_structural_fallback
or compact_text_section
)
- if (
- score >= 4.0
- and (has_spacing_signal or compact_local_transition)
- and strong_layout_signal
- ):
+ if score >= 4.0 and (has_spacing_signal or compact_local_transition) and strong_layout_signal:
if _is_full_width_inline_heading(
rows,
index,
@@ -2688,16 +2739,14 @@ def _matching_document_title_prototype(
if (
prototype.font_family != font_family
or prototype.font_flags != line.font_signature[1]
- or abs(height_ratio - prototype.height_ratio)
- > 0.1 * prototype.height_ratio
+ or abs(height_ratio - prototype.height_ratio) > 0.1 * prototype.height_ratio
):
continue
if (
prototype.weight is not None
and line.dominant_font_weight is not None
and abs(prototype.weight - line.dominant_font_weight) >= 100.0
- and max(prototype.weight, line.dominant_font_weight)
- >= 1.15 * min(prototype.weight, line.dominant_font_weight)
+ and max(prototype.weight, line.dominant_font_weight) >= 1.15 * min(prototype.weight, line.dominant_font_weight)
):
continue
alignment = _title_profile_alignment(
@@ -2705,11 +2754,7 @@ def _matching_document_title_prototype(
lane,
document_body_profile.body_height,
)
- if (
- alignment is None
- or alignment[0] != prototype.alignment
- or abs(alignment[1] - prototype.anchor_offset) > 0.15
- ):
+ if alignment is None or alignment[0] != prototype.alignment or abs(alignment[1] - prototype.anchor_offset) > 0.15:
continue
candidates.append(prototype)
return max(
@@ -2727,11 +2772,7 @@ def _line_inside_visual_container(
center_x = _bbox_center_x(line_bbox)
center_y = _bbox_center_y(line_bbox)
- return any(
- bbox[0] <= center_x <= bbox[2]
- and bbox[1] <= center_y <= bbox[3]
- for bbox in container_bboxes
- )
+ return any(bbox[0] <= center_x <= bbox[2] and bbox[1] <= center_y <= bbox[3] for bbox in container_bboxes)
def _line_conflicts_document_title_profile(
@@ -2777,8 +2818,7 @@ def _line_conflicts_document_title_profile(
prototype.weight is not None
and line.dominant_font_weight is not None
and abs(prototype.weight - line.dominant_font_weight) >= 100.0
- and max(prototype.weight, line.dominant_font_weight)
- >= 1.15 * min(prototype.weight, line.dominant_font_weight)
+ and max(prototype.weight, line.dominant_font_weight) >= 1.15 * min(prototype.weight, line.dominant_font_weight)
):
continue
if abs(height_ratio - prototype.height_ratio) > 0.15 * prototype.height_ratio:
@@ -2792,11 +2832,7 @@ def _title_font_families_compatible(first: str, second: str) -> bool:
if first == second:
return True
style_suffixes = (",bold", "bold", ",regular", "regular", ",medium", "medium")
- return any(
- first.removesuffix(suffix) == second
- or second.removesuffix(suffix) == first
- for suffix in style_suffixes
- )
+ return any(first.removesuffix(suffix) == second or second.removesuffix(suffix) == first for suffix in style_suffixes)
def _protect_front_matter_title_types(
@@ -2809,8 +2845,7 @@ def _protect_front_matter_title_types(
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
+ 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):
@@ -2825,9 +2860,7 @@ def _protect_front_matter_title_types(
):
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
- )
+ lane.lines[index][0].semantic_type = "text" if index in connected_indices else None
def _visual_row_has_body_style_sibling(
@@ -2840,9 +2873,7 @@ def _visual_row_has_body_style_sibling(
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
+ 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)
@@ -2889,11 +2920,7 @@ def _continues_local_body_row(
if previous_line.semantic_type is not None:
return False
previous_visual_row = (
- [
- item
- for item in rows[:index]
- if item[0].visual_row_id == previous_line.visual_row_id
- ]
+ [item for item in rows[:index] if item[0].visual_row_id == previous_line.visual_row_id]
if previous_line.visual_row_id is not None
else [rows[index - 1]]
)
@@ -2912,12 +2939,9 @@ def _continues_local_body_row(
)
):
return False
- previous_bbox = _bbox_union_many(
- [member_bbox for _member, member_bbox in previous_visual_row]
- )
+ previous_bbox = _bbox_union_many([member_bbox for _member, member_bbox in previous_visual_row])
previous_height = statistics.median(
- _line_effective_height(member, member_bbox)
- for member, member_bbox in previous_visual_row
+ _line_effective_height(member, member_bbox) for member, member_bbox in previous_visual_row
)
line_height = _line_effective_height(line, bbox)
pair_height = max(previous_height, line_height)
@@ -2929,9 +2953,7 @@ def _continues_local_body_row(
0.8 <= line_height / previous_height <= 1.25
and previous_bbox[2] - previous_bbox[0] >= 0.75 * lane_width
and abs(bbox[0] - previous_bbox[0]) <= 2.0 * pair_height
- and -0.25 * pair_height
- <= gap
- <= profile.regular_gap + pair_height
+ and -0.25 * pair_height <= gap <= profile.regular_gap + pair_height
)
@@ -3000,8 +3022,7 @@ def _is_full_width_inline_heading(
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
+ and _effective_text_row_gap(rows[index], rows[index + 1]) <= profile.regular_gap + 0.25 * profile.body_height
)
@@ -3023,16 +3044,11 @@ def _has_following_body_row(
_bbox_axis_overlap_ratio(current[1], bbox, axis="x") >= 0.35
or abs(current[1][0] - bbox[0]) <= 0.75 * profile.body_height
)
- current_centered = abs(
- _bbox_center_x(current[1]) - (lane_left + lane_width / 2.0)
- ) <= 0.12 * lane_width
+ current_centered = abs(_bbox_center_x(current[1]) - (lane_left + lane_width / 2.0)) <= 0.12 * lane_width
compact_left_aligned = (
- current[1][2] - current[1][0] <= 0.35 * lane_width
- and abs(current[1][0] - lane_left) <= 0.65 * profile.body_height
+ current[1][2] - current[1][0] <= 0.35 * lane_width and abs(current[1][0] - lane_left) <= 0.65 * profile.body_height
)
- maximum_gap = (
- 1.5 if current_centered else 1.25 if compact_left_aligned else 0.75
- ) * profile.body_height
+ maximum_gap = (1.5 if current_centered else 1.25 if compact_left_aligned else 0.75) * profile.body_height
height_ratio = _line_effective_height(line, bbox) / profile.body_height
width_ratio = (bbox[2] - bbox[0]) / lane_width
return (
@@ -3085,20 +3101,13 @@ def _unify_visual_row_title_types(
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"
- ]
+ 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
+ 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
)
@@ -3135,9 +3144,7 @@ def _infer_front_matter_boundary(
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
+ 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 (
@@ -3237,9 +3244,7 @@ def _expand_paragraph_title_neighbors(
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
- ):
+ 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)
diff --git a/mineru/model/flash/pdf/visual_annotations.py b/mineru/model/flash/pdf/visual_annotations.py
index 8db8fdcf..0e4ce02d 100644
--- a/mineru/model/flash/pdf/visual_annotations.py
+++ b/mineru/model/flash/pdf/visual_annotations.py
@@ -16,6 +16,7 @@ from .._shared.xycut import sort_entries
from ....types import BBox
from .geometry import (
+ _bbox_axis_overlap_ratio,
_bbox_center_x,
_bbox_center_y,
_bbox_union_many,
@@ -134,6 +135,21 @@ def _is_strong_caption_text(text: str) -> bool:
return match is not None and not _caption_tail_is_reference(match.group("tail"))
+def _caption_identifier(text: str) -> str | None:
+ """返回中英文强图表题共用的规范化编号。"""
+
+ normalized = _normalize_annotation_text(text)
+ match = _ENGLISH_CAPTION_RE.match(normalized) or _CHINESE_CAPTION_RE.match(normalized)
+ return (
+ unicodedata.normalize(
+ "NFKC",
+ match.group("identifier"),
+ ).casefold()
+ if match is not None
+ else None
+ )
+
+
def _is_strong_footnote_text(text: str) -> bool:
"""判断文本是否以带冒号的来源或注释强标记开头。"""
@@ -170,9 +186,7 @@ def _block_median_line_height(
"""优先使用原生行高,缺失时按局部块高和行框数量保守估计。"""
heights = [
- float(height)
- for height in block.get("_line_heights", [])
- if isinstance(height, (int, float)) and float(height) > 0
+ float(height) for height in block.get("_line_heights", []) if isinstance(height, (int, float)) and float(height) > 0
]
if heights:
return statistics.median(heights)
@@ -494,17 +508,15 @@ def _axis_overlap_metrics(
expanded_parent_end = parent_end + float_margin
overlap = max(
0.0,
- min(annotation_end, expanded_parent_end)
- - max(annotation_start, expanded_parent_start),
+ min(annotation_end, expanded_parent_end) - max(annotation_start, expanded_parent_start),
)
annotation_length = max(0.1, annotation_end - annotation_start)
parent_length = max(0.1, expanded_parent_end - expanded_parent_start)
projection_overlap = overlap / min(annotation_length, parent_length)
annotation_coverage = overlap / annotation_length
- center_offset = abs(
- (annotation_start + annotation_end) / 2.0
- - (parent_start + parent_end) / 2.0
- ) / max(annotation_length, parent_end - parent_start, 0.1)
+ center_offset = abs((annotation_start + annotation_end) / 2.0 - (parent_start + parent_end) / 2.0) / max(
+ annotation_length, parent_end - parent_start, 0.1
+ )
return projection_overlap, annotation_coverage, center_offset
@@ -548,10 +560,7 @@ def _direction_relation(
axis=projection_axis,
float_margin=line_height,
)
- if (
- projection_overlap < _MIN_PROJECTION_OVERLAP
- or annotation_coverage < _MIN_ANNOTATION_COVERAGE
- ):
+ if projection_overlap < _MIN_PROJECTION_OVERLAP or annotation_coverage < _MIN_ANNOTATION_COVERAGE:
return None
return _AnnotationRelation(
parent=parent,
@@ -618,9 +627,7 @@ def _image_blocks_form_component(
y_overlap = max(0.0, min(first_bbox[3], second_bbox[3]) - max(first_bbox[1], second_bbox[1]))
min_width = max(0.1, min(first_bbox[2] - first_bbox[0], second_bbox[2] - second_bbox[0]))
min_height = max(0.1, min(first_bbox[3] - first_bbox[1], second_bbox[3] - second_bbox[1]))
- return (
- horizontal_gap <= 2.0 * line_height and y_overlap / min_height >= 0.5
- ) or (
+ return (horizontal_gap <= 2.0 * line_height and y_overlap / min_height >= 0.5) or (
vertical_gap <= 2.0 * line_height and x_overlap / min_width >= 0.5
)
@@ -722,10 +729,7 @@ def _relation_has_intervening_block(
bbox = _block_local_bbox(block, page_size, relation.parent.angle)
if bbox is None:
continue
- if (
- min(bbox[2], corridor[2]) > max(bbox[0], corridor[0])
- and min(bbox[3], corridor[3]) > max(bbox[1], corridor[1])
- ):
+ if min(bbox[2], corridor[2]) > max(bbox[0], corridor[0]) and min(bbox[3], corridor[3]) > max(bbox[1], corridor[1]):
return True
return False
@@ -742,8 +746,7 @@ def _component_relation_is_materially_better(
comparable = [
single
for single in single_relations
- if single.direction == relation.direction
- and single.parent.member_indices[0] in member_indices
+ if single.direction == relation.direction and single.parent.member_indices[0] in member_indices
]
if not comparable:
return True
@@ -781,9 +784,7 @@ def _choose_annotation_relation(
)
is not None
]
- single_relations = [
- relation for relation in relations if len(relation.parent.member_indices) == 1
- ]
+ single_relations = [relation for relation in relations if len(relation.parent.member_indices) == 1]
relations = [
relation
for relation in relations
@@ -819,19 +820,13 @@ def _caption_blocks_use_distinct_regular_lanes(
) -> bool:
"""确认两个标题块分别属于互不重叠的普通栏带。"""
- if (
- anchor.get("_lane_is_span") is not False
- or candidate.get("_lane_is_span") is not False
- ):
+ if anchor.get("_lane_is_span") is not False or candidate.get("_lane_is_span") is not False:
return False
anchor_interval = _coerce_lane_interval(anchor.get("_lane_interval"))
candidate_interval = _coerce_lane_interval(candidate.get("_lane_interval"))
if anchor_interval is None or candidate_interval is None:
return False
- return (
- anchor_interval[1] <= candidate_interval[0]
- or candidate_interval[1] <= anchor_interval[0]
- )
+ return anchor_interval[1] <= candidate_interval[0] or candidate_interval[1] <= anchor_interval[0]
def _caption_blocks_have_compatible_typography(
@@ -846,11 +841,7 @@ def _caption_blocks_have_compatible_typography(
if anchor_height <= 0 or candidate_height <= 0:
return False
height_ratio = candidate_height / anchor_height
- if not (
- _CROSS_LANE_CAPTION_MIN_LINE_HEIGHT_RATIO
- <= height_ratio
- <= _CROSS_LANE_CAPTION_MAX_LINE_HEIGHT_RATIO
- ):
+ if not (_CROSS_LANE_CAPTION_MIN_LINE_HEIGHT_RATIO <= height_ratio <= _CROSS_LANE_CAPTION_MAX_LINE_HEIGHT_RATIO):
return False
anchor_fonts = anchor.get("_font_signatures")
@@ -880,10 +871,7 @@ def _cross_lane_caption_companion_relation(
return None
anchor = blocks[anchor_index]
candidate = blocks[candidate_index]
- if (
- candidate.get("type") != "text"
- or _block_angle(candidate) != anchor_relation.parent.angle
- ):
+ if candidate.get("type") != "text" or _block_angle(candidate) != anchor_relation.parent.angle:
return None
if not _caption_blocks_use_distinct_regular_lanes(anchor, candidate):
return None
@@ -909,10 +897,7 @@ def _cross_lane_caption_companion_relation(
_block_median_line_height(candidate, page_size),
)
)
- if (
- abs(anchor_first_row[1] - candidate_first_row[1])
- > _CROSS_LANE_CAPTION_ROW_TOP_TOLERANCE * pair_height
- ):
+ if abs(anchor_first_row[1] - candidate_first_row[1]) > _CROSS_LANE_CAPTION_ROW_TOP_TOLERANCE * pair_height:
return None
relation = _choose_annotation_relation(
@@ -923,11 +908,7 @@ def _cross_lane_caption_companion_relation(
parents,
annotation_indices | {candidate_index},
)
- if (
- relation is None
- or relation.parent != anchor_relation.parent
- or relation.direction != anchor_relation.direction
- ):
+ if relation is None or relation.parent != anchor_relation.parent or relation.direction != anchor_relation.direction:
return None
return relation
@@ -984,11 +965,7 @@ def _merge_parent_assignment_groups(
groups: list[tuple[set[int], dict[int, _AnnotationRelation]]] = []
for annotation_index, relation in assignments.items():
parent_indices = set(relation.parent.member_indices)
- overlapping = [
- index
- for index, (members, _relations) in enumerate(groups)
- if members & parent_indices
- ]
+ overlapping = [index for index, (members, _relations) in enumerate(groups) if members & parent_indices]
merged_members = set(parent_indices)
merged_relations = {annotation_index: relation}
for group_index in reversed(overlapping):
@@ -1067,9 +1044,7 @@ def _sort_annotation_indices_by_visual_rows(
item_relation is not None
and item_relation.direction in {"above", "below"}
and all(
- (
- member_relation := relations.get(member[0])
- ) is not None
+ (member_relation := relations.get(member[0])) is not None
and member_relation.direction == item_relation.direction
and _caption_blocks_use_distinct_regular_lanes(
blocks[member[0]],
@@ -1078,20 +1053,10 @@ def _sort_annotation_indices_by_visual_rows(
for member in current_row
)
)
- reference_top = statistics.median(
- member[1][1]
- for member in current_row
- )
- reference_height = statistics.median(
- member[2]
- for member in current_row
- )
+ reference_top = statistics.median(member[1][1] for member in current_row)
+ reference_height = statistics.median(member[2] for member in current_row)
pair_height = statistics.median((reference_height, item[2]))
- if (
- shares_cross_lane_row
- and abs(item[1][1] - reference_top)
- <= _CROSS_LANE_CAPTION_ROW_TOP_TOLERANCE * pair_height
- ):
+ if shares_cross_lane_row and abs(item[1][1] - reference_top) <= _CROSS_LANE_CAPTION_ROW_TOP_TOLERANCE * pair_height:
current_row.append(item)
continue
rows.append([item])
@@ -1125,20 +1090,14 @@ def _build_visual_annotation_regions(
leading = [
index
for index, relation in relations.items()
- if blocks[index].get("type") == "caption"
- and relation.direction in {"above", "left"}
+ if blocks[index].get("type") == "caption" and relation.direction in {"above", "left"}
]
trailing = [
index
for index, relation in relations.items()
- if blocks[index].get("type") == "caption"
- and relation.direction in {"below", "right"}
- ]
- footnotes = [
- index
- for index in relations
- if blocks[index].get("type") == "footnote"
+ if blocks[index].get("type") == "caption" and relation.direction in {"below", "right"}
]
+ footnotes = [index for index in relations if blocks[index].get("type") == "footnote"]
regions.append(
[
*(
@@ -1187,10 +1146,7 @@ def _classify_and_bind_visual_annotations(
candidates = _collect_annotation_candidates(blocks)
if not candidates:
return []
- line_heights = [
- _block_median_line_height(blocks[index], page_size)
- for index in candidates
- ]
+ line_heights = [_block_median_line_height(blocks[index], page_size) for index in candidates]
component_line_height = statistics.median(line_heights) if line_heights else 8.0
parents = _build_visual_parents(blocks, page_size, component_line_height)
if not parents:
@@ -1211,6 +1167,14 @@ def _classify_and_bind_visual_annotations(
)
is not None
}
+ assignments.update(
+ _expand_stacked_bilingual_caption_assignments(
+ blocks,
+ page_size,
+ candidates,
+ assignments,
+ )
+ )
cross_lane_assignments = _expand_cross_lane_caption_assignments(
blocks,
page_size,
@@ -1232,9 +1196,69 @@ def _classify_and_bind_visual_annotations(
blocks[index]["_visual_annotation_direction"] = relation.direction
regions = _build_visual_annotation_regions(assignments, blocks, page_size)
if consumed_indices:
- blocks[:] = [
- block
- for index, block in enumerate(blocks)
- if index not in consumed_indices
- ]
+ blocks[:] = [block for index, block in enumerate(blocks) if index not in consumed_indices]
return regions
+
+
+def _expand_stacked_bilingual_caption_assignments(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+ candidates: dict[int, _AnnotationKind],
+ assignments: dict[int, _AnnotationRelation],
+) -> dict[int, _AnnotationRelation]:
+ """把紧邻且编号相同的中英文双语图题绑定到同一视觉主体。"""
+
+ output: dict[int, _AnnotationRelation] = {}
+ assigned_captions = [index for index in assignments if candidates.get(index) == "caption"]
+ for candidate_index, kind in candidates.items():
+ if kind != "caption" or candidate_index in assignments:
+ continue
+ candidate_identifier = _caption_identifier(
+ str(blocks[candidate_index].get("content") or ""),
+ )
+ candidate_bbox = _block_local_bbox(
+ blocks[candidate_index],
+ page_size,
+ )
+ if candidate_identifier is None or candidate_bbox is None:
+ continue
+ candidate_height = _block_median_line_height(
+ blocks[candidate_index],
+ page_size,
+ )
+ matches: list[tuple[float, int]] = []
+ for anchor_index in assigned_captions:
+ if _caption_identifier(
+ str(blocks[anchor_index].get("content") or ""),
+ ) != candidate_identifier or _block_angle(blocks[anchor_index]) != _block_angle(blocks[candidate_index]):
+ continue
+ anchor_bbox = _block_local_bbox(
+ blocks[anchor_index],
+ page_size,
+ )
+ if anchor_bbox is None:
+ continue
+ anchor_height = _block_median_line_height(
+ blocks[anchor_index],
+ page_size,
+ )
+ gap = max(
+ candidate_bbox[1] - anchor_bbox[3],
+ anchor_bbox[1] - candidate_bbox[3],
+ 0.0,
+ )
+ if (
+ gap <= 1.5 * max(candidate_height, anchor_height)
+ and _bbox_axis_overlap_ratio(
+ candidate_bbox,
+ anchor_bbox,
+ axis="x",
+ )
+ >= 0.35
+ ):
+ matches.append((gap, anchor_index))
+ if not matches:
+ continue
+ _gap, anchor_index = min(matches)
+ output[candidate_index] = assignments[anchor_index]
+ return output
diff --git a/tests/fixtures/flash_layout_block_expectations.json b/tests/fixtures/flash_layout_block_expectations.json
index 62cf43c4..197ca359 100644
--- a/tests/fixtures/flash_layout_block_expectations.json
+++ b/tests/fixtures/flash_layout_block_expectations.json
@@ -225,6 +225,104 @@
{"page_index": 2, "type": "table", "fragment": "续表"},
{"page_index": 7, "type": "text", "fragment": "acc(Bm)="}
]
+ },
+ {
+ "path": "demo/pdfs/中文论文3.pdf",
+ "sha256": "a9edebcdff03ea03d80f61cfe0b5a875ea2f7122beacaf8177d59327eeab8154",
+ "type_counts": {
+ "caption": 6,
+ "doc_title": 1,
+ "header": 12,
+ "image": 3,
+ "page_footnote": 4,
+ "page_number": 3,
+ "paragraph_title": 6,
+ "text": 59
+ },
+ "exact_typed_text": [
+ {"page_index": 0, "type": "header", "text": "DOI:10.16270/j.cnki.slgc.2013.03.029"},
+ {"page_index": 0, "type": "header", "text": "FORESTENGINEERING"},
+ {"page_index": 0, "type": "paragraph_title", "text": "1APS与ERP简介"},
+ {"page_index": 0, "type": "paragraph_title", "text": "1.1ERP系统的弱点"},
+ {"page_index": 2, "type": "caption", "text": "图1高级计划与排程系统业务流程"},
+ {"page_index": 2, "type": "caption", "text": "Fig.1BusinessprocessofAPS"},
+ {"page_index": 2, "type": "caption", "text": "图2APS结构模块示意图"},
+ {"page_index": 2, "type": "caption", "text": "Fig.2SchematicdiagramofstructuremoduleinAPS"},
+ {"page_index": 3, "type": "caption", "text": "图3APS与ERP系统集成计划管理流程"},
+ {"page_index": 3, "type": "caption", "text": "Fig.3ManagementprocessofintegratedProjectbetweenAPSandERP"},
+ {"page_index": 3, "type": "paragraph_title", "text": "【参考文献】"}
+ ],
+ "different_block_groups": [
+ {
+ "page_index": 0,
+ "fragments": ["关键词:高级计划与排程", "中图分类号:F406.2", "文献标识码:A", "文章编号:1001"]
+ },
+ {
+ "page_index": 0,
+ "fragments": ["1APS与ERP简介", "1.1ERP系统的弱点"]
+ }
+ ]
+ },
+ {
+ "path": "demo/pdfs/中文论文4.pdf",
+ "sha256": "697f37feb86cb49c905ceac0074e2569969e25043c15768cf6c0a86973fdc899",
+ "normalize_nfkc": true,
+ "type_counts": {
+ "caption": 10,
+ "doc_title": 2,
+ "header": 19,
+ "image": 5,
+ "page_footnote": 1,
+ "paragraph_title": 13,
+ "table": 5,
+ "text": 46
+ },
+ "exact_typed_text": [
+ {"page_index": 0, "type": "paragraph_title", "text": "引言"},
+ {"page_index": 0, "type": "paragraph_title", "text": "1资料与分析方法"},
+ {"page_index": 0, "type": "text", "text": "http://www.qxkj.net.cn气象科技"},
+ {"page_index": 1, "type": "caption", "text": "表1逆温强度分级"},
+ {"page_index": 1, "type": "caption", "text": "图12005—2009年逆温发生频率年变化"},
+ {"page_index": 1, "type": "paragraph_title", "text": "2重庆市区低空逆温时空分布特征"},
+ {"page_index": 1, "type": "paragraph_title", "text": "2.1低空逆温出现频率"},
+ {"page_index": 1, "type": "paragraph_title", "text": "2.2逆温厚度分布特征"},
+ {"page_index": 1, "type": "paragraph_title", "text": "2.2.1接地逆温厚度分布特征"},
+ {"page_index": 2, "type": "paragraph_title", "text": "2.2.2悬浮逆温厚度分布特征"},
+ {"page_index": 2, "type": "caption", "text": "图22005—2009年逆温厚度年变化"},
+ {"page_index": 2, "type": "caption", "text": "表22005—2009年悬浮逆温分布特征"},
+ {"page_index": 2, "type": "caption", "text": "图32005—2009年悬浮逆温层底高和顶高的年变化"},
+ {"page_index": 2, "type": "caption", "text": "图42005—2009年悬浮逆温高度分布"},
+ {"page_index": 3, "type": "caption", "text": "表3逆温强度的次数和频率"},
+ {"page_index": 3, "type": "caption", "text": "图52005—2009年逆温强度年变化"},
+ {"page_index": 3, "type": "caption", "text": "表407:00多层逆温次数分布"},
+ {"page_index": 3, "type": "paragraph_title", "text": "2.5逆温垂直结构特征分析"},
+ {"page_index": 3, "type": "paragraph_title", "text": "3结论与讨论"},
+ {"page_index": 4, "type": "caption", "text": "表519:00多层逆温次数分布"},
+ {"page_index": 4, "type": "doc_title", "text": "CharacteristicAnalysisofTemperatureInversioninLower-LevelAtmosphereoverChongqingBasedonL-BandRadarData"}
+ ],
+ "same_block_groups": [
+ {"page_index": 0, "type": "text", "fragments": ["(1南京信息工程大学", "重庆401147)"]},
+ {"page_index": 1, "type": "text", "fragments": ["差:ΔT=T2-T1", "逆温强度定义为", "I=ΔT×100%", "100%。逆温日数统计算法"]},
+ {"page_index": 1, "type": "text", "fragments": ["07:00悬浮逆温频次", "19:00悬浮逆温年平均值"]},
+ {"page_index": 1, "type": "text", "fragments": ["逆温层厚度反映", "也只有134m。"]},
+ {"page_index": 2, "type": "text", "fragments": ["悬浮逆温是悬浮在离地面", "的厚度即为顶高减底高的差值"]},
+ {"page_index": 4, "type": "text", "fragments": ["(3)重庆市区低空逆温强度不大", "没有大的季节变化。"]},
+ {"page_index": 4, "type": "text", "fragments": ["(4)重庆市区低空逆温厚度薄且层次多", "待今后开展更深入的分析。"]},
+ {"page_index": 4, "type": "text", "fragments": ["[2]姜大膀", "200l,37(4):133-139."]},
+ {"page_index": 4, "type": "text", "fragments": ["[3]刘焕彬", "象,2005,25(1):27-28."]},
+ {"page_index": 4, "type": "text", "fragments": ["[4]刘增强", "分析[J].干旱区地理"]},
+ {"page_index": 4, "type": "text", "fragments": ["[5]戴安国", "14(3):58-62."]},
+ {"page_index": 4, "type": "text", "fragments": ["[6]马力", "105-107."]},
+ {"page_index": 4, "type": "text", "fragments": ["[7]胡春梅", "665-669."]},
+ {"page_index": 4, "type": "text", "fragments": ["[8]王荣基", "106-109."]},
+ {"page_index": 4, "type": "doc_title", "fragments": ["CharacteristicAnalysisofTemperatureInversioninLower-Level", "AtmosphereoverChongqingBasedonL-BandRadarData"]}
+ ],
+ "forbidden_type_fragments": [
+ {"page_index": 1, "type": "equation", "fragment": "I=ΔT"},
+ {"page_index": 1, "type": "paragraph_title", "fragment": "也只有134m。"},
+ {"page_index": 2, "type": "table", "fragment": "2.2.2悬浮逆温厚度"},
+ {"page_index": 4, "type": "paragraph_title", "fragment": "2ChongqingMeteorologicalService"}
+ ]
}
]
}
diff --git a/tests/fixtures/flash_layout_geometry_manifest.json b/tests/fixtures/flash_layout_geometry_manifest.json
index 5a19fc90..60a81fbc 100644
--- a/tests/fixtures/flash_layout_geometry_manifest.json
+++ b/tests/fixtures/flash_layout_geometry_manifest.json
@@ -15309,6 +15309,1083 @@
"strong_x_runs": 0,
"sibling_x_runs": 0
}
+ },
+ {
+ "path": "demo/pdfs/中文论文3.pdf",
+ "sha256": "a9edebcdff03ea03d80f61cfe0b5a875ea2f7122beacaf8177d59327eeab8154",
+ "role": "normal",
+ "approved": true,
+ "pages": [
+ {
+ "page_index": 0,
+ "fingerprint": "10c7003ad02f6b2a0b0ec73d8fb9842e3856f7f1077e6a672c1218453e9c6716",
+ "bbox_fingerprint": "9825313d730f19b1f29a7ad60c4f194d03a905c01cb5e79234bbd338cd97ddad",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "7fb345c1083a3c519dc2",
+ "type": "header",
+ "text_sha256": "eb2fae4578eb93febae2694242a0fd0f9d37974843e05e3d65a023bd60bfdc44"
+ },
+ {
+ "id": "bed408899f1eeaf32b46",
+ "type": "header",
+ "text_sha256": "1aba362f8772107db0c65f261f31f6e3b9e3317d9280991e4e5b609c31b89c8b"
+ },
+ {
+ "id": "0005faeca69c4a05d8f9",
+ "type": "header",
+ "text_sha256": "4679457d7cb2c66f28121952e95253273a66a01e8230801538578badcdfa7e58"
+ },
+ {
+ "id": "b8ccb4a6daaface1fb43",
+ "type": "header",
+ "text_sha256": "89584b32dcdb35b3c5861b923f00fc7bbf4130a728de0142fbf8cb42b674cb03"
+ },
+ {
+ "id": "9062e398e7be354e570c",
+ "type": "header",
+ "text_sha256": "53e809bba5c69c7631cf5303c93812792f14aabfb4ebfac2994ef5b4d8011a84"
+ },
+ {
+ "id": "486620c29d9646db2d3a",
+ "type": "header",
+ "text_sha256": "0ac6dca741f91e0c34480a5c7074a4c21a67db5e3fdbab95850ad7130d0eb946"
+ },
+ {
+ "id": "f922b9b7a9537294b7e8",
+ "type": "doc_title",
+ "text_sha256": "b771e739b5b37395fbe6ef977e324318adc20947859f41300f2fa665de617e76"
+ },
+ {
+ "id": "4563c93f475a6944f053",
+ "type": "text",
+ "text_sha256": "e729d68d22049d5b17220b4c949a39af4631278efd7656f931ea5c0ababfbff8"
+ },
+ {
+ "id": "3c877549c87de094b93b",
+ "type": "text",
+ "text_sha256": "3e9cc3f788b6b8e09b480064854c7b1044ab3b060726b0088d362091f6181166"
+ },
+ {
+ "id": "7ada23e3d5be06501795",
+ "type": "text",
+ "text_sha256": "e2f5124042277e441a328c00e2b6b130a2a8d0da4116da60e5bcff3cd923ece5"
+ },
+ {
+ "id": "8b00a2f3696eea09b9a1",
+ "type": "text",
+ "text_sha256": "acc911d769cbe5d03342d274e05dda4639f9c9369e9f3406a815f238ed608542"
+ },
+ {
+ "id": "b58c8178a09c642a23d2",
+ "type": "text",
+ "text_sha256": "d9016c4d558f9d997d4de1b59c0e20bce1fd91ac148ac2d3e5d49f7b18f015fc"
+ },
+ {
+ "id": "cfd1663d34e210541348",
+ "type": "text",
+ "text_sha256": "a9064d2d4f3e61ad9eced5da52f1da2f386d81b72d05cd6add21f538ed0c33a4"
+ },
+ {
+ "id": "d6f8944d5f8a037a7c79",
+ "type": "text",
+ "text_sha256": "a63a42a182a0d0ff0a93e3a8ed75ca5a704d50f57ec0ae8b2296fd2727c3cb1d"
+ },
+ {
+ "id": "150b29864d2440ff768c",
+ "type": "text",
+ "text_sha256": "9ee31544df0ba6657b8d549fb2c0f337af2b589a23407e93504c3ebd4ce0d4a8"
+ },
+ {
+ "id": "1dd3a813fdd13c260dfe",
+ "type": "text",
+ "text_sha256": "743d6037ab455eb7cacdb702b4be4186c922920aaaa41b0ac48fdfa9e7b8e3c4"
+ },
+ {
+ "id": "9ac364ce552260252491",
+ "type": "text",
+ "text_sha256": "ce93751a458c21be8d8216511c0429f8af22ba37ce0fa9ba142084a9d769b159"
+ },
+ {
+ "id": "3fb6a95e84aebba221f0",
+ "type": "text",
+ "text_sha256": "6135cb595b6a44ac0b1f83e777b9c1368e19ae7e7cc0bc2516383fcab98d79c9"
+ },
+ {
+ "id": "f73bf87339147e1ef87c",
+ "type": "text",
+ "text_sha256": "d35691561d144fe1bc705dbac69076558ce6534cfb2d0c20ee87d218df25e6ff"
+ },
+ {
+ "id": "15887426ff716593f86b",
+ "type": "text",
+ "text_sha256": "f2a30116729cecbbcbb2abf85a89913cc831b94a313b9d98ac619511e7e2e169"
+ },
+ {
+ "id": "7e2e522eee79bd24dc32",
+ "type": "text",
+ "text_sha256": "c404a4505d40de06f329a449caca810b7a0270028b8dcfe55f84ecfa50110618"
+ },
+ {
+ "id": "e3609c52c44e8881f4fb",
+ "type": "text",
+ "text_sha256": "57062170fafa9aab8a02b74224e8d7bc3916cd3095dd9322441fc464d8c05a84"
+ },
+ {
+ "id": "effc3a46f93f3f6ffd51",
+ "type": "text",
+ "text_sha256": "dd579f9dca995144e66410bbfac2372f24ef8841e91da1403edf0d2b68d90c54"
+ },
+ {
+ "id": "f7e7603dab3beef3d8f0",
+ "type": "text",
+ "text_sha256": "0bd40e5187027c20e261b0ba8265f0cda183f52e682ef8325bfcdec5c5667ff4"
+ },
+ {
+ "id": "9cfa8afb25140150657d",
+ "type": "text",
+ "text_sha256": "b26cfda16bb1ca373cf38e89540cc173b1d27dc5ce947a35cf508e35355dfc70"
+ },
+ {
+ "id": "517097a84ba8c2ffff5d",
+ "type": "paragraph_title",
+ "text_sha256": "43a5aff3a2b04e2ecf77e8b43f58ce277864cafdec454c19c6871e2042753c86"
+ },
+ {
+ "id": "f331f94651da579cd233",
+ "type": "paragraph_title",
+ "text_sha256": "9b01688e04e6c70a9aefae712c86c27355533e7d386e3d56af317a24275e3cf2"
+ },
+ {
+ "id": "ecf882ab2edd975315c3",
+ "type": "text",
+ "text_sha256": "0a42360909fdaad4c7c1813fc48a69a1f56af9041b6535fcbcdfef8c7b9f1396"
+ },
+ {
+ "id": "fac81474a35e1a75e35c",
+ "type": "text",
+ "text_sha256": "bfe8c8675d7dc0a8092ef36834a2af3f02badf8d2a94be38aa7750eab2e8b841"
+ },
+ {
+ "id": "49342749d23c81795626",
+ "type": "page_footnote",
+ "text_sha256": "636a4aa82543baa6ee109629389cf59fef90e87dd73479ae5b967e565663447c"
+ },
+ {
+ "id": "64f577c813b5bdd15cb5",
+ "type": "page_footnote",
+ "text_sha256": "7c2894bb02606f5a375cd9d5743772ce00e971169d8250ec6a6feb16dd9c89cd"
+ },
+ {
+ "id": "2088afa4f1a8f18edf80",
+ "type": "page_footnote",
+ "text_sha256": "fe406fb44b94810275c0c16ad5e27d0e123e1bc7a0db5dcb172b868969169c35"
+ },
+ {
+ "id": "933af638553ce75d4637",
+ "type": "page_footnote",
+ "text_sha256": "33da632aca31786f893397be4ba3bccb87571d9ed026c0f9c8af85800819e404"
+ }
+ ]
+ },
+ {
+ "page_index": 1,
+ "fingerprint": "106d8aaa73e90ca5e76abd1f2c248efbd8fb0675db994e2191650cd3a3331655",
+ "bbox_fingerprint": "6cdb3c5e384d8ae3834aa01056bbfd1e4a7d0f9bf34b8116c44cdf667b038085",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "0634da0a3ae32ad75aee",
+ "type": "header",
+ "text_sha256": "d9ac187eada03a93b3637bf05af2479f1bf73406f2fc48a00836b335dff61002"
+ },
+ {
+ "id": "5bb79ae9c7dd1d172f4a",
+ "type": "header",
+ "text_sha256": "879e96e7476dc7c1a1074b8f56fb417801b61b23650442c5448ab825d2bf3e5f"
+ },
+ {
+ "id": "007e2cb51b9d41e0c02d",
+ "type": "page_number",
+ "text_sha256": "1d28c120568c10e19b9d8abe8b66d0983fa3d2e11ee7751aca50f83c6f4a43aa"
+ },
+ {
+ "id": "92c1c61c9ea892fbba38",
+ "type": "text",
+ "text_sha256": "4f280a47a779686abea3d6f91d55dc0c9fb7f5a7ced4f62c0eda5946fb26eb74"
+ },
+ {
+ "id": "664b0fbc5769c48f4c25",
+ "type": "text",
+ "text_sha256": "57cccb96503155028e9c5ff1bc4926cc3a2fead8137811bda69cbca84a8523be"
+ },
+ {
+ "id": "ec5a984a2fd51c16eebf",
+ "type": "text",
+ "text_sha256": "d6f7aa91bd844c05a89b7b9f40b8d8cc4f3ec143d487174c9ef49eb2d9f168ed"
+ },
+ {
+ "id": "96bed3831565b2d8da5d",
+ "type": "text",
+ "text_sha256": "4d469174d87cff1bd64ab8f0d6d6da7a234231a1adf3d3e25d2e9568158b39fd"
+ },
+ {
+ "id": "44e9cb399523849316ef",
+ "type": "paragraph_title",
+ "text_sha256": "5c353fb67168ac52d1a837d7c79672eb7e8fff61036ab3383330feb5e451dadb"
+ },
+ {
+ "id": "e3bf737a0d862118dd29",
+ "type": "text",
+ "text_sha256": "cec9441bb9b84485ab1cc5832935a52da73f81353d6597f91acac75abb680bb9"
+ },
+ {
+ "id": "4036037d9b410abae874",
+ "type": "text",
+ "text_sha256": "fa01e7aea969b01bfa1deeed5a95324100b907ef1681bbc5a75f5e83a3466439"
+ },
+ {
+ "id": "2686d36d0f17928918f8",
+ "type": "text",
+ "text_sha256": "c33451ba67f02109bf39631b557a02f3350816d54b9582c23b9e4e6ef4917a9b"
+ },
+ {
+ "id": "aa037f45ef4645565f3e",
+ "type": "text",
+ "text_sha256": "2af332e8bfe50bd53e2ec64dc9ef0fbca2c5c77ace7e55b05a6e55e9a50719b0"
+ },
+ {
+ "id": "2dee5314286d88b78027",
+ "type": "text",
+ "text_sha256": "2c61efc8d52247f52cdc2b56a908172f60895bb8d54178096552607dd3c39e38"
+ },
+ {
+ "id": "f64b8e919801d23858aa",
+ "type": "text",
+ "text_sha256": "b4ca3a3f4340c56f927cc189ddbfa37bc21b99c66f6fb4e3b8678fda4e6b5917"
+ },
+ {
+ "id": "39a3394c048eeec6b6bf",
+ "type": "paragraph_title",
+ "text_sha256": "fe5de176db52e752efb45e31923944cf19657973bde0d62291552ec4afa34e2a"
+ },
+ {
+ "id": "f82f9d6076142e457bba",
+ "type": "text",
+ "text_sha256": "7e0b6d1d019f133830d739cd5f78220e6ad28cee18537ea9b81908cddb302f16"
+ },
+ {
+ "id": "83a121ee20572e923163",
+ "type": "text",
+ "text_sha256": "b9d3da010c5c22a1dd24e4aca901b538bc9e85342438d42694adb4d2bb7f9380"
+ }
+ ]
+ },
+ {
+ "page_index": 2,
+ "fingerprint": "b4931ae0f69ebd7ea7c620072c86dc4ec8a0fb3a6b22ca4509da185d4dea5163",
+ "bbox_fingerprint": "6b0a1c153305becbad13c477715b41fbe2a06fd2da8f3108f455a58f9f7df767",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "b273ea89ffd29720ab8f",
+ "type": "page_number",
+ "text_sha256": "ec2e990b934dde55cb87300629cedfc21b15cd28bbcf77d8bbdc55359d7689da"
+ },
+ {
+ "id": "b5ff8827ba4167fa6ec4",
+ "type": "header",
+ "text_sha256": "4679457d7cb2c66f28121952e95253273a66a01e8230801538578badcdfa7e58"
+ },
+ {
+ "id": "271d66aa1f8ea5c5e085",
+ "type": "header",
+ "text_sha256": "1355135766c5081db4700ff646a48c9cf4f76466d244958ba5eaeec139f3b54a"
+ },
+ {
+ "id": "b34c6913365a42611106",
+ "type": "text",
+ "text_sha256": "296e386d708638a86601ded08f6ea4365bd92c93fc0c4ade01688121702f44dd"
+ },
+ {
+ "id": "eaa53518e748cb6a9b2f",
+ "type": "text",
+ "text_sha256": "d915aeebd739bdeacdb643a9d0064b72841dce60906b6e966d7c205e77c3d211"
+ },
+ {
+ "id": "f87218959ab9a648ce8e",
+ "type": "text",
+ "text_sha256": "7f89c4d3e8e3d5dfbf00acb1b88ea1f75e0c99b5799f8e8b73ddd179d931b02e"
+ },
+ {
+ "id": "d1c273a5e1cebb8a338a",
+ "type": "image",
+ "text_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ {
+ "id": "3c9bc9aeab5cd30d03dd",
+ "type": "caption",
+ "text_sha256": "cf17f2bd5b621faa6894c06933abef13bd4d02917126530383d37300dc1514f9"
+ },
+ {
+ "id": "d22333aa8de94260f49c",
+ "type": "caption",
+ "text_sha256": "59484f8f06f56d9d3e9197c5f7b21382a06c4038690501fe15e7fddbe9fa2348"
+ },
+ {
+ "id": "7d851210862bb0c04f0d",
+ "type": "text",
+ "text_sha256": "2fdbe257b935317a37e4f8976bb30825ea13dcf848f54362ce9ac9db2f96da93"
+ },
+ {
+ "id": "88e166941b6192fd0de2",
+ "type": "text",
+ "text_sha256": "21143bae0d19ecbc64e1b8de645e643f3cd81f476076a0185fc392594a5c0ae4"
+ },
+ {
+ "id": "1dfa3ddc632eda60347f",
+ "type": "text",
+ "text_sha256": "9fb7836102f11682e013eea7d8ec16eef652781030ae9f11819d4ddb3f4738a5"
+ },
+ {
+ "id": "9fd81a126949cbb1e228",
+ "type": "image",
+ "text_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ {
+ "id": "abb77497b7062a9f1c92",
+ "type": "caption",
+ "text_sha256": "2f6d297290a24e32571c97cb16d8008f723204257b933a291c3cb43edc443e69"
+ },
+ {
+ "id": "55f7beab7c9290202a9f",
+ "type": "caption",
+ "text_sha256": "b4d9e09983f5ba63f6f635b74e5b28df4be56ed88d7f4b6489cf417a30ac9fdb"
+ },
+ {
+ "id": "b8851d7fdbfca87592f7",
+ "type": "text",
+ "text_sha256": "8ba0717c70baa3c7da1060186632ef39e5df391dd73d3876da28a61b1a212ec8"
+ },
+ {
+ "id": "e459ade1bb8bf9195efd",
+ "type": "text",
+ "text_sha256": "d413d1bbd364d65e57557246db08787cdff22db8dc0db17478c124c9fce1a9a0"
+ },
+ {
+ "id": "0067ede6c5cd39b08370",
+ "type": "text",
+ "text_sha256": "283d25a958838a01131e1ac7fa75b76e189f4ac8fff53dd1a527f62fb00c91c6"
+ },
+ {
+ "id": "5a25d54c78732185a180",
+ "type": "text",
+ "text_sha256": "c99ddf496418ea704066b8460e985bba786e077eb9cb64e65bbf7eb9280699d7"
+ }
+ ]
+ },
+ {
+ "page_index": 3,
+ "fingerprint": "719d8bd9873356c256d5b7a64d348fe8f93390f474c84b6cc09a36660ea7ea6f",
+ "bbox_fingerprint": "24ee1c39c47bd8a2f08bf616cb8b5859e29e3be22cc19d1c0c0c51867339f46d",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "4a98e13b978ed067ef04",
+ "type": "header",
+ "text_sha256": "d9ac187eada03a93b3637bf05af2479f1bf73406f2fc48a00836b335dff61002"
+ },
+ {
+ "id": "ba9e73d2089c876e803a",
+ "type": "header",
+ "text_sha256": "879e96e7476dc7c1a1074b8f56fb417801b61b23650442c5448ab825d2bf3e5f"
+ },
+ {
+ "id": "85ee5c78bbeb91f21bbf",
+ "type": "page_number",
+ "text_sha256": "05ada863a4cf9660fd8c68e2295f1d35b2264815f5b605003d6625bd9e0492cf"
+ },
+ {
+ "id": "e3fd2bf2afad9f347f08",
+ "type": "text",
+ "text_sha256": "d2e283ded490e6206072fc98eb87ae5f69e920e5ff4dba9970c7116e6e988f57"
+ },
+ {
+ "id": "a06067d61fa08f8cf2b5",
+ "type": "text",
+ "text_sha256": "ec7b88a4fe7db5b65b348811eb356f651bd256808239cdcefca354e50e531842"
+ },
+ {
+ "id": "e37ada12d033a65b19d0",
+ "type": "text",
+ "text_sha256": "7e43cc941faa8154018dc6ed4d4aca0d28908bf236171683a5134a35a567b992"
+ },
+ {
+ "id": "049890c60930e668e64f",
+ "type": "image",
+ "text_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ {
+ "id": "a261df437220580bf6df",
+ "type": "caption",
+ "text_sha256": "5477c23b8786702e54fae23542d7a4217bb755defd2569f117b68e07522452d1"
+ },
+ {
+ "id": "059f94f92b8fe71cddb9",
+ "type": "caption",
+ "text_sha256": "b01ee45339b26d1289f6ef1fddca6ebfb6186ddb4acc8b43029759f9c9faaa58"
+ },
+ {
+ "id": "a71e37f3d4eacc90148c",
+ "type": "paragraph_title",
+ "text_sha256": "4b7bd4499b1084c1cf8b30f2129008d83dd2cd3711a2d06c61200e0635d8fca3"
+ },
+ {
+ "id": "8fbf90c96a9e375f46d5",
+ "type": "text",
+ "text_sha256": "7ea49b5aa711f4d60a54550ee959fb374f884d977921cc6d1dad785411746f43"
+ },
+ {
+ "id": "2cbb38346dd6e11df0ea",
+ "type": "text",
+ "text_sha256": "f16789a20cf5bea3a65066b32de4a6fb4227db52b9ecc6d7dc3d9904e1a135ca"
+ },
+ {
+ "id": "e81d5567354d15521687",
+ "type": "paragraph_title",
+ "text_sha256": "b0c7816d029b1fb96a66ae1f3ef03ce32518c2a7c7d9de9a64f2ea2ca20893be"
+ },
+ {
+ "id": "57f08a00aa06b0c4ef5a",
+ "type": "text",
+ "text_sha256": "a77004cd16a7563adb11902da523ed386957b10c03f5c766938970b8d97b102f"
+ },
+ {
+ "id": "33ce3703812140e7a181",
+ "type": "text",
+ "text_sha256": "951ef8998ef7ab7f39117ade1287ab0c26f678f2d16b72665901df7381ae93f8"
+ },
+ {
+ "id": "02c44635156835329805",
+ "type": "text",
+ "text_sha256": "05933cb417dfc87fcb861f930b88d4eeb28188ce1ad664f7f93b180f3874a38c"
+ },
+ {
+ "id": "4b69fd6749ab0e51d95d",
+ "type": "text",
+ "text_sha256": "a3b7f159cdf2b703a248f45ee1cb7db1bc4c39861fb50ac2e6c7365563f1a8fb"
+ },
+ {
+ "id": "f70849a24fedf7f46f86",
+ "type": "text",
+ "text_sha256": "eb1498e6a047f0d7d17c609b6e2bfc7f85583446e0ea12f2f78533cfcde0cb20"
+ },
+ {
+ "id": "748d7976a6e9b16417a5",
+ "type": "text",
+ "text_sha256": "9ce5ab22c73835926c6a1bb2d2988dbe04e2d311324d6d71479db3f4b5ec8dbb"
+ },
+ {
+ "id": "e251c72f5b8277d67e5c",
+ "type": "text",
+ "text_sha256": "9e4309fed83a37ebfd223dc9ae778c009c9128546eefec58862c990890d95a71"
+ },
+ {
+ "id": "b3a6456e5ae2367fe834",
+ "type": "text",
+ "text_sha256": "c8c53060994643e7f10315bc4773f050ab82aea7f70b223b80a3d0ac7b8e2c05"
+ },
+ {
+ "id": "3d3e27a0f84020b9d7c1",
+ "type": "text",
+ "text_sha256": "ba13d02d1735549f9dd5b94215c3cf87df170019b1eecd42cb2492d6e9625e04"
+ },
+ {
+ "id": "647111d08e3f3e051858",
+ "type": "text",
+ "text_sha256": "7dd3206da9ccc781fb4783e96a62c690a31b72d02b3bf9ef909ad1bedc7396f5"
+ },
+ {
+ "id": "00f9b01519da4a8c146f",
+ "type": "text",
+ "text_sha256": "948247fb8100bce15098c452916d01532ede1c17106588bf67b195deb7f42536"
+ },
+ {
+ "id": "8a64d78b6882f926935e",
+ "type": "text",
+ "text_sha256": "aeee481295770c54b10552384526165bb642a5a76480a301422de3ee38033d51"
+ }
+ ]
+ }
+ ],
+ "expected_geometry_summary": {
+ "repaired_chars": 0,
+ "repaired_lines": 0,
+ "split_y_candidates": 0,
+ "strong_x_runs": 0,
+ "sibling_x_runs": 0
+ }
+ },
+ {
+ "path": "demo/pdfs/中文论文4.pdf",
+ "sha256": "697f37feb86cb49c905ceac0074e2569969e25043c15768cf6c0a86973fdc899",
+ "role": "normal",
+ "approved": true,
+ "pages": [
+ {
+ "page_index": 0,
+ "fingerprint": "a67cf4d6ec9d6616f4159f1c9654a8a62cebe0614b000b9749665cb0db6a795c",
+ "bbox_fingerprint": "e592d5319f0d6dbea1dd41bd0dc9c6c235c42f30d68dc0562e3cfc96094e7c3e",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "74dc92cf63f85fbc26fb",
+ "type": "header",
+ "text_sha256": "a784211568ec9ed0882608f9a54092d62222c8ea0a66285febf756ee4dd701a1"
+ },
+ {
+ "id": "e1e9ad6dd78069791e09",
+ "type": "header",
+ "text_sha256": "3747dd5cd4741ad9a969105bc7b51bc376933a3646694d8839e6046d0d3786a5"
+ },
+ {
+ "id": "24cb638553d2591eef35",
+ "type": "header",
+ "text_sha256": "6a6d54095cca00bcdf6b890d198ba1679711082a81cefd814a3e5c9b15ad9990"
+ },
+ {
+ "id": "e57450b1e283b6b356e4",
+ "type": "header",
+ "text_sha256": "dc8b6dc755fca983cc4a1daade54480cdf710b7820e63a1b8a5a6f958bedcff0"
+ },
+ {
+ "id": "0aa592ae3b6a4ed14c2e",
+ "type": "header",
+ "text_sha256": "9db4a8ccde37759a7e9d3ddf6c4a9895cd0e0deedca40a716a8d27785e13c83c"
+ },
+ {
+ "id": "4b343d1a00043f9c82c9",
+ "type": "doc_title",
+ "text_sha256": "c29adbea6293fed1182206ee9891e147cb40c1240f8702ddac995be610efd96b"
+ },
+ {
+ "id": "4555e0819b935c844a0b",
+ "type": "text",
+ "text_sha256": "00e815211282359111a592215185b85e1814cbec56ee955c1d733a14edb32d11"
+ },
+ {
+ "id": "b311176271f238fd4aac",
+ "type": "text",
+ "text_sha256": "9f5c4d62fc610d7423c132fa1448e9b110aa449b9a3c7025c44552032642a07d"
+ },
+ {
+ "id": "0fe8152f564f1ca31671",
+ "type": "text",
+ "text_sha256": "d15c1717086a633ff13a041e3c3fa9a17e033b57b2e0a4892aba846318c6d1f4"
+ },
+ {
+ "id": "49c2ac8add97ca37373a",
+ "type": "paragraph_title",
+ "text_sha256": "ef6fba91718f20ee18db5a1fea02f670e9781fb4534bf9f2b2409266e0316dfd"
+ },
+ {
+ "id": "c915496d8fc038ce31bf",
+ "type": "text",
+ "text_sha256": "7139688f09200f3b4702e0e94445ccfab3488117fdb2aeae174ebc64a6a37b17"
+ },
+ {
+ "id": "a497fdce2aaf04998fc9",
+ "type": "text",
+ "text_sha256": "c09e99bf162037aaaf18c322e129c43096f9d07f24511912196bda25ae63b930"
+ },
+ {
+ "id": "191dd811d765a3043e17",
+ "type": "paragraph_title",
+ "text_sha256": "f9220db8def2d12c85b55718a4b7a803c42d24e83db24b4f1571452b9bac4a8c"
+ },
+ {
+ "id": "bafc4a6d0c34b7f9b51d",
+ "type": "text",
+ "text_sha256": "bbd8692d512b57fd7968cb26e1f782763c0ee0c71b5e8a24170c264a69c3ed32"
+ },
+ {
+ "id": "d554c70083fddd5ab5a7",
+ "type": "text",
+ "text_sha256": "05a1c75303a45a0e4920d6f0b595cb2ba8446c924bd5d9e230090dda45e9c393"
+ },
+ {
+ "id": "31ec28e0e13b715a9f2d",
+ "type": "text",
+ "text_sha256": "215a5050a861ffcfcb05d45e36ebd98846c8f95c68bf2b41c89ca49acd767713"
+ },
+ {
+ "id": "8af93339e9cc8a777b1d",
+ "type": "page_footnote",
+ "text_sha256": "f57d2292614be010025573b4e60b69c52c1becb56d786d5d72c002c271291416"
+ }
+ ]
+ },
+ {
+ "page_index": 1,
+ "fingerprint": "01bc5f14e82c4abb578d94285b31cc4d48d1ca5cdacfe2746f54e00c4fb1229f",
+ "bbox_fingerprint": "6279d78ef340f5a11ef2521f1886129af6fd74d89e0fe4c5fb039258325c7c02",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "be008b712ef5e631f3bd",
+ "type": "header",
+ "text_sha256": "ffa4dbf201bd4fdd590dda166a68d3ac92c4acee0ae89acad22c516f0b605f93"
+ },
+ {
+ "id": "ba460ff01d05e9444bc0",
+ "type": "header",
+ "text_sha256": "9eac93b2a1ca498a79fa04ac29398be1abc0001c1e0510697e641e1ea9b73170"
+ },
+ {
+ "id": "26e938f71d8bf28c0ce1",
+ "type": "header",
+ "text_sha256": "d6a81c0580eb8bfd82c91fb2fda8f67cd82adf4b90c1faa18f53f104f7065273"
+ },
+ {
+ "id": "46aae5ba746b23830445",
+ "type": "header",
+ "text_sha256": "bad947d1bca452b5d50c5b3a5de5713cd3121e4c6a79b24c27a3d113189554a1"
+ },
+ {
+ "id": "18eba335a8090f52b913",
+ "type": "text",
+ "text_sha256": "6a5cb6a06c80ebe74a4ba8f99fa621831381ecff8d59a2474f99cdadb68127dd"
+ },
+ {
+ "id": "f5cbb0c5fb110f511ac2",
+ "type": "text",
+ "text_sha256": "64aeba9413d96219b2ea1fa0d262e923a47776d6a88ba4354bd95369607e4446"
+ },
+ {
+ "id": "7a0474dc15fc630af8cf",
+ "type": "caption",
+ "text_sha256": "8a0a5f41ec38826d18fccc0dbb79d34bf6daddb99b14d6f64b7ddba0a656d475"
+ },
+ {
+ "id": "a13a9acb3e21fe01f5a9",
+ "type": "table",
+ "text_sha256": "811b67c642bac02f202cccb71d9fad8eddbbf39687504b64888229875337cb37"
+ },
+ {
+ "id": "594fb84ab4ae71b3d075",
+ "type": "paragraph_title",
+ "text_sha256": "8c8400fbe044b30870b4bb7e070febe63bdaade95b0d36949404c51d83952ed7"
+ },
+ {
+ "id": "2aa584867f9086e6ebe1",
+ "type": "paragraph_title",
+ "text_sha256": "d53a02148b277ba7a0246a3a6b2be13e4eaba6f3fc7ee99a11b5ae0698ab36b9"
+ },
+ {
+ "id": "5378660cfc8ad7a41130",
+ "type": "text",
+ "text_sha256": "aa6cc5d4c6d127c7a037875c6379a98a08b7cf51a24139f2e7259c604c94b341"
+ },
+ {
+ "id": "f3ad4a61324f825e0507",
+ "type": "text",
+ "text_sha256": "bf02fc808baa7d4fc27800d7490763e6a9a21d2168689872b95a7c0f46298968"
+ },
+ {
+ "id": "68b52768b562863d16db",
+ "type": "text",
+ "text_sha256": "4d9c4721ff436f75b88b54f9ecee509c25d08b255a5c84b9b2caa5fb3dcbafa2"
+ },
+ {
+ "id": "d2bb237653f613f74aab",
+ "type": "paragraph_title",
+ "text_sha256": "5390e6a8f5f1f41584f0fcc06935dfe81011c5815516e7c303b08e46f7ca7d9f"
+ },
+ {
+ "id": "56dbc5bdb09fc4601171",
+ "type": "paragraph_title",
+ "text_sha256": "dff4af1cda26e6ff1387a30f6abaae30b5d806eb015e52c4a48f3fca6a5d68ef"
+ },
+ {
+ "id": "48a374a04c196bd3f1e5",
+ "type": "text",
+ "text_sha256": "27495909b755e42ca4783db6055389f900a94414ce5c1c149650e538ff9f4e5a"
+ },
+ {
+ "id": "ac93c5e28d83f5d6a89b",
+ "type": "text",
+ "text_sha256": "52a4368fbfe268a735a639d8d8706f3384d5daa5e1bbfb4cb2f5b34cd6c17004"
+ },
+ {
+ "id": "418a782650af641c5a88",
+ "type": "image",
+ "text_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ {
+ "id": "673f695ac1aee7d21262",
+ "type": "caption",
+ "text_sha256": "f1bd7feb4d525f92c7820952a5a3e06a715ce1eb774e65c821bfd5abd6790f7c"
+ },
+ {
+ "id": "2a13066fe9f7811a2bcd",
+ "type": "text",
+ "text_sha256": "650ac044ae222500a6fc7122222b846eefa309436a291fbda7f5d6f96963d841"
+ }
+ ]
+ },
+ {
+ "page_index": 2,
+ "fingerprint": "ceb9ca3a2a1222c2d22552dcd3a508e24e79a23b9f8c284b96a8b95c2096bc28",
+ "bbox_fingerprint": "6bb84a2d7818d14dd66e0f40febd4611b2282e1000608b2cbb4ce51a36a5dbe0",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "00692dfa84692ecf2759",
+ "type": "header",
+ "text_sha256": "5b5dcd50d76dfa6a53548f3050165109f9e49ff4aeb026f7d2ed25bf30fd5e1b"
+ },
+ {
+ "id": "8d97b3344f0789b01bc4",
+ "type": "header",
+ "text_sha256": "3373926558277d74507e3b1e630222f5064edfe51fecdb656e89fd046f5ab927"
+ },
+ {
+ "id": "ab22dc36117ef571e3ed",
+ "type": "header",
+ "text_sha256": "67c2eeed87479eb8a11903d4c5ef7aa4a321024f071db10b3b93e4eabcb96610"
+ },
+ {
+ "id": "f87fc27575a200f962f4",
+ "type": "paragraph_title",
+ "text_sha256": "0eea86524a4daf827b0de2d1b3944394decc0e3366c9fa7ea32ac3dcb92f4e37"
+ },
+ {
+ "id": "62ebdef1052f47abb32e",
+ "type": "text",
+ "text_sha256": "d647f81c2a1d77457c8f74f6915dfd78d4929bd97cbc86f47ca1590cfaf9dbf0"
+ },
+ {
+ "id": "039a76cf1502bb6d4f8d",
+ "type": "image",
+ "text_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ {
+ "id": "9a28694b7770b6cdd045",
+ "type": "caption",
+ "text_sha256": "c9f3146eb23efa6585c8e51b272ea6c10227c4eb67360690f08830d264a682f2"
+ },
+ {
+ "id": "5ee40087735bcbb15568",
+ "type": "text",
+ "text_sha256": "cf9ef8e83c56ad61d305cf5030adc9d97ba0f6ea9cf421bab3dcb5049273a6db"
+ },
+ {
+ "id": "4d6a588013a5989c78db",
+ "type": "paragraph_title",
+ "text_sha256": "41ba637bc52014501e4559684064799eafa33c5ebd0f0eff01f7a60e46f35fda"
+ },
+ {
+ "id": "1aa27c1f0d2cb0b7ccca",
+ "type": "paragraph_title",
+ "text_sha256": "6c4492658ce5f58147134cedb13f58532fed84a28f6f4595ddf3495ab1689c38"
+ },
+ {
+ "id": "6def976f141ea6f8619d",
+ "type": "text",
+ "text_sha256": "89fccf8c0f1e786f6bb6bb85537937b1a4d9bdae375e356cb6097628e42e6a83"
+ },
+ {
+ "id": "7c0d07d44ee317691ff4",
+ "type": "text",
+ "text_sha256": "f11a8c9ba98b6aaa42081e57089d1bdb64567710399cbff861050ff6cf518f65"
+ },
+ {
+ "id": "e7c96b83091ac323f755",
+ "type": "caption",
+ "text_sha256": "b2769274192c26b691d58829ff45cdf0313c3f73e6c916383ffd2dbc4a03cbf9"
+ },
+ {
+ "id": "9ecb1836f6f3e6aadd7d",
+ "type": "table",
+ "text_sha256": "241c013f0def79ebd6407f00d1d634238b400821d5f0f6b5b7c869b31b54e9d1"
+ },
+ {
+ "id": "89ceca4b3e0f85396d5c",
+ "type": "text",
+ "text_sha256": "c8590417968d7ab116bda9a89cf77ac11f0248d48c9d371d66ba8a1c4f68c661"
+ },
+ {
+ "id": "a94c58aa242bdbb92afb",
+ "type": "image",
+ "text_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ {
+ "id": "d2848b7560b189ebe6be",
+ "type": "caption",
+ "text_sha256": "251c42522b252081a8f3f55dc718c229d64e02cbf3c0f82560183342645061d4"
+ },
+ {
+ "id": "7dc93d7ca713c97da441",
+ "type": "paragraph_title",
+ "text_sha256": "aaca6b5919c0d12c2206bdd66b106f8cbe046ba31585568bf73315f8a1ae08cb"
+ },
+ {
+ "id": "7bb3bc7eb0b937a566e6",
+ "type": "text",
+ "text_sha256": "626744e698851cb823b6053482637df79f458ba063455407675df07ba6f25c11"
+ },
+ {
+ "id": "18386575c3bf4dfd571a",
+ "type": "text",
+ "text_sha256": "7d92a3df60321b92241034ccd30af300a7854d717163e9faab7bab2de9cf4f3c"
+ },
+ {
+ "id": "8373eb7a5aa63c127748",
+ "type": "image",
+ "text_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ {
+ "id": "7af40f011215e80fd63a",
+ "type": "caption",
+ "text_sha256": "b95c8c8dc2a31d6054e4ed3788633dd75775c33cb4ebcf34e8efe4f87ca2938d"
+ },
+ {
+ "id": "04e0d514b8ae1afcd779",
+ "type": "paragraph_title",
+ "text_sha256": "31a2f5efafc2d950ec326dc6a34595050ecd55e8a615a56fec3271915f27e327"
+ },
+ {
+ "id": "d841230a03724a1692b1",
+ "type": "text",
+ "text_sha256": "bed858da7418749d9c7503cabac052856bc1159a17d62ae926debd9a4fc5d8b5"
+ }
+ ]
+ },
+ {
+ "page_index": 3,
+ "fingerprint": "7591b916ab2d6c0bc3bec2b9545d0ea5a8da4bdda70c3099514a85dd5b8db4e1",
+ "bbox_fingerprint": "c13f2e1f2991e8a99230442011496f383ba922d09a8d0a5ae6a7f4d639e931bb",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "24fd4825de558fb8eb8f",
+ "type": "header",
+ "text_sha256": "15894ec0082b423a3637ee354407479b5b1beb78c71e3c57a85a45b55abfe0dc"
+ },
+ {
+ "id": "7a89e6d34f68bfe8b4a2",
+ "type": "header",
+ "text_sha256": "9eac93b2a1ca498a79fa04ac29398be1abc0001c1e0510697e641e1ea9b73170"
+ },
+ {
+ "id": "42d41f51bd836a19b79b",
+ "type": "header",
+ "text_sha256": "d6a81c0580eb8bfd82c91fb2fda8f67cd82adf4b90c1faa18f53f104f7065273"
+ },
+ {
+ "id": "aaa8226b01789b05235b",
+ "type": "header",
+ "text_sha256": "bad947d1bca452b5d50c5b3a5de5713cd3121e4c6a79b24c27a3d113189554a1"
+ },
+ {
+ "id": "8d0d48b18a6bbf3ae845",
+ "type": "text",
+ "text_sha256": "19d1523813f7b6333d2fa66b28f5061e39ca18a28b9594aa084a4414ee25beb0"
+ },
+ {
+ "id": "03c47058b443ff294d1c",
+ "type": "caption",
+ "text_sha256": "2581636012347c39c0b3eee96f329bf382ae9200b4619e3eaaf09d4e4715a241"
+ },
+ {
+ "id": "ee885f1e5d647871289d",
+ "type": "table",
+ "text_sha256": "f7907bdebd7b2698809cdbb82f4f8c6b57f17b2a39f6fe12b91ccc883df6744e"
+ },
+ {
+ "id": "01575bf6015656b2f023",
+ "type": "text",
+ "text_sha256": "b88573e9385f73b2e1ecda8b31adef383841b69d1bbeb686415dab5e63938ae6"
+ },
+ {
+ "id": "6445faaf0599afaa795f",
+ "type": "text",
+ "text_sha256": "bd5374c37010d6e7b0d30da812d29bf55bcd21e5ff15f9ba2c271c3c467b301e"
+ },
+ {
+ "id": "b5b16f2fc4c425c24946",
+ "type": "paragraph_title",
+ "text_sha256": "21197db0761ae8ec3cc7b1eb6566634f274695ff99f3e2bca71bdb74fb9e667f"
+ },
+ {
+ "id": "d08014f11bf3400abd14",
+ "type": "text",
+ "text_sha256": "38e4ec3baf1df498eb9b165256d50bc4b93dcef44e3b33c243053c5fdb29a291"
+ },
+ {
+ "id": "f1ee9e5b693f88df6234",
+ "type": "paragraph_title",
+ "text_sha256": "4d009e71a53c7b5c4fc6c63b6f0920dd5e347d0d24621a05975a971d795e0179"
+ },
+ {
+ "id": "894ae3910b70ba4174c3",
+ "type": "text",
+ "text_sha256": "5f11ec4dc865465252c9b9d205a8694febbaa0ead0e80e7263ce151dfebc26c8"
+ },
+ {
+ "id": "a312521ea5739ad86849",
+ "type": "text",
+ "text_sha256": "d55f8206337b705e1165fdc0e3341c154cfb900788e89bf7f6c3d4bd0f8f6860"
+ },
+ {
+ "id": "36976871022f91d37f30",
+ "type": "image",
+ "text_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ {
+ "id": "1ad4332851d55e43b57e",
+ "type": "caption",
+ "text_sha256": "1f7c96110f4fc7eeb2c70dc893727ec2b0440422bda4b6d788cb52c926d6c31e"
+ },
+ {
+ "id": "c1a0c74975f2b013562e",
+ "type": "caption",
+ "text_sha256": "318e10bc351a757ffa84f9f76dce3df31f7d3aef48e4efe37de846ad4bf8e741"
+ },
+ {
+ "id": "8d948776befccb4c208f",
+ "type": "table",
+ "text_sha256": "c01ff5d32e3fbb946e292bb2794b25ee0679caa4bd3f291bab2d54d5bedf62f9"
+ }
+ ]
+ },
+ {
+ "page_index": 4,
+ "fingerprint": "aeb346a70ea9baa5ad76b4f2fa59328bbcb96fd736b74486e4c13dbbed52c98a",
+ "bbox_fingerprint": "f5fa295f6ee60b3547b745da86f88defaf867d675f37ae46ebde68b4cf42a935",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "3c0406052a3e975abb3f",
+ "type": "header",
+ "text_sha256": "5b5dcd50d76dfa6a53548f3050165109f9e49ff4aeb026f7d2ed25bf30fd5e1b"
+ },
+ {
+ "id": "4a3d8b45c418e861da39",
+ "type": "header",
+ "text_sha256": "3373926558277d74507e3b1e630222f5064edfe51fecdb656e89fd046f5ab927"
+ },
+ {
+ "id": "fa9d903141802b5ec0d6",
+ "type": "header",
+ "text_sha256": "e5120fef6a1340d1594bde9336e7f297ed604b6eaf3efe23526e72c13caebfec"
+ },
+ {
+ "id": "c72d77fdba46a4e228cf",
+ "type": "caption",
+ "text_sha256": "e5b91dc4a8111d4072e517ca216013bbdae610ebb8ed8f65336f6d7ef6a044a8"
+ },
+ {
+ "id": "cf514996e0d8c0cee3a5",
+ "type": "table",
+ "text_sha256": "9d965f6ba5295ebfd0ab6f34fe13ca7f5ccf05e47ad3f6383f3a998de773042d"
+ },
+ {
+ "id": "f9b293f31833d2a4e0db",
+ "type": "text",
+ "text_sha256": "273099b7089986a1ea39bbc348cf5b6b012e7b9d6fdff6ede7238a349b11262b"
+ },
+ {
+ "id": "2a043f2ba23f35d15907",
+ "type": "text",
+ "text_sha256": "0dace48adaa71a64bf461e33010ac3ed3dfd48e3fe828cb938e93b770032eb9c"
+ },
+ {
+ "id": "2ba7503665159c06b7ab",
+ "type": "text",
+ "text_sha256": "edc3efb149a25b9613ce36ac49d50fa08fbda9e7b7120a27b83d2c9a69b24a3f"
+ },
+ {
+ "id": "727bf774bea1b487d581",
+ "type": "text",
+ "text_sha256": "55807e4ca80022f3a1ed571705dc557b977dd121cf4b5c8174bf2b3fe40d0e22"
+ },
+ {
+ "id": "dd92b417988ed180183c",
+ "type": "text",
+ "text_sha256": "24afd6e60e71dbec0a66baabf29f977fda250a5500cafad2f6a6e25932aa417b"
+ },
+ {
+ "id": "ef48c0fa7ff6fb88d266",
+ "type": "text",
+ "text_sha256": "7f2c57269060a37ad03a16f303a1d13b1832a725a2955c5c234edaef1411e7d8"
+ },
+ {
+ "id": "ccddbe650c72f1e9fc3f",
+ "type": "text",
+ "text_sha256": "70321e31b49db9f2742e4ce16d36b0c22f5ff405938df9ac009a3cc43c7421e7"
+ },
+ {
+ "id": "0567d0dcfcdd8143a821",
+ "type": "text",
+ "text_sha256": "3dc260da8e4faa47e1429912fc9da95098ad1ca76c5c772273993659fea9ed7f"
+ },
+ {
+ "id": "ad5a5b9e9a6a144e8ac4",
+ "type": "text",
+ "text_sha256": "814c3581713351c08c856a7dbe9a55a481b0c8c0cc76146d18630f0aca75d0b6"
+ },
+ {
+ "id": "8920052ee2588ddc45d1",
+ "type": "text",
+ "text_sha256": "ed622913e08f6be60ccd165c1714c1a890fb2e522399ee22d8258c3ffc7911bd"
+ },
+ {
+ "id": "e1ae7f6c33a865e06fcf",
+ "type": "text",
+ "text_sha256": "2a86caf69553ee6d1a7b2603ab9d30fbbfd59da80e17bc567c9e31299dae7601"
+ },
+ {
+ "id": "94e81009734e2690d107",
+ "type": "text",
+ "text_sha256": "007055dc0dbd606f65908a231b074537cfdf7931f51b19326d18496a8aaad2f8"
+ },
+ {
+ "id": "49a76d2f631fd8a150f3",
+ "type": "doc_title",
+ "text_sha256": "00ecd72f24e6e049d208f5ccab530de36605f1deec79ef96affd1a3a00894cf4"
+ },
+ {
+ "id": "25be6728bdce601f7f66",
+ "type": "text",
+ "text_sha256": "4bfc3fd89a858b770292678b4eeb7b1345261d63423740be1c49122d4e5a347e"
+ },
+ {
+ "id": "86ada0413ab6122b57ef",
+ "type": "text",
+ "text_sha256": "014cc1629d2740f4200adf81c87a3e19ada82638237b27759a844e460f393ebf"
+ },
+ {
+ "id": "33e9fee0e0e8ea35fa16",
+ "type": "text",
+ "text_sha256": "b85992874a6e4f4429b3c07d1eeb365596d579423e4e95ac48f0635843cd4fbf"
+ },
+ {
+ "id": "7d9310595ba15cf97997",
+ "type": "text",
+ "text_sha256": "ca7518cdd3da3b61db3fe318af60bb6e959158efe0571309825a612bece1427f"
+ }
+ ]
+ }
+ ],
+ "expected_geometry_summary": {
+ "repaired_chars": 2359,
+ "repaired_lines": 389,
+ "split_y_candidates": 2,
+ "strong_x_runs": 3,
+ "sibling_x_runs": 1
+ }
}
],
"performance_validation": {
diff --git a/tests/unittest/test_flash_pdf_char_geometry.py b/tests/unittest/test_flash_pdf_char_geometry.py
index 19db7a11..24849def 100644
--- a/tests/unittest/test_flash_pdf_char_geometry.py
+++ b/tests/unittest/test_flash_pdf_char_geometry.py
@@ -447,8 +447,8 @@ def test_flash_layout_manifest_uses_portable_repository_paths() -> None:
project_root = Path(__file__).parents[2]
payload = json.loads((project_root / "tests" / "fixtures" / "flash_layout_geometry_manifest.json").read_text())
assert payload["schema_version"] == 1
- assert len(payload["documents"]) == 17
- assert sum(len(document["pages"]) for document in payload["documents"]) == 159
+ assert len(payload["documents"]) == 19
+ assert sum(len(document["pages"]) for document in payload["documents"]) == 168
for document in payload["documents"]:
path = Path(document["path"])
assert not path.is_absolute()
diff --git a/tests/unittest/test_flash_pdf_formulas.py b/tests/unittest/test_flash_pdf_formulas.py
index 07d3d70a..1b7ec21d 100644
--- a/tests/unittest/test_flash_pdf_formulas.py
+++ b/tests/unittest/test_flash_pdf_formulas.py
@@ -38,6 +38,55 @@ def _formula_member(
)
+def test_formula_component_rejects_left_aligned_prose_lead() -> None:
+ """验证同栏左缘带正文引导语的复杂行内分式不升级为行间公式。"""
+
+ prose = _text_line(
+ "(℃/hm),用 I 表示:I=ΔT",
+ (0.0, 20.0, 55.0, 30.0),
+ 0,
+ effective_height=10.0,
+ )
+ numerator = _text_line(
+ "×100%",
+ (56.0, 20.0, 78.0, 30.0),
+ 1,
+ effective_height=10.0,
+ )
+ denominator = _text_line(
+ "ΔH",
+ (45.0, 30.0, 55.0, 38.0),
+ 2,
+ effective_height=8.0,
+ )
+ lane = models._TextLane(
+ left=0.0,
+ right=100.0,
+ lines=[
+ (prose, prose.bbox),
+ (numerator, numerator.bbox),
+ (denominator, denominator.bbox),
+ ],
+ )
+
+ assert formulas._formula_component_has_left_prose(
+ lane.lines,
+ lane,
+ 10.0,
+ )
+
+ formula = replace(
+ prose,
+ text="I=ΔT",
+ bbox=(20.0, 20.0, 55.0, 30.0),
+ )
+ assert not formulas._formula_component_has_left_prose(
+ [(formula, formula.bbox), (denominator, denominator.bbox)],
+ lane,
+ 10.0,
+ )
+
+
def _vector_path(
bbox: tuple[float, float, float, float],
source_index: int,
@@ -209,10 +258,7 @@ def test_vector_formula_paths_and_detached_path_number_form_one_empty_equation()
"""验证矢量主体与远距栏右缘路径编号形成一个空内容公式。"""
body_paths = _vector_formula_body_paths()
- number_paths = [
- _vector_path((91.0 + index * 3.0, 51.0, 93.0 + index * 3.0, 60.0), 10 + index)
- for index in range(3)
- ]
+ number_paths = [_vector_path((91.0 + index * 3.0, 51.0, 93.0 + index * 3.0, 60.0), 10 + index) for index in range(3)]
blocks, claimed = formulas._build_vector_formula_blocks(
_vector_formula_source(*body_paths, *number_paths),
[],
@@ -249,13 +295,9 @@ def test_vector_formula_claims_text_number_but_keeps_content_empty() -> None:
def test_vector_formula_rejects_unmatched_number_rules_strokes_forms_and_inline_paths() -> None:
"""验证无主体编号、细规则、描边、Form 图标和正文同行路径均不会误报。"""
- unmatched_number = [
- _vector_path((91.0 + index * 3.0, 51.0, 93.0 + index * 3.0, 60.0), index)
- for index in range(3)
- ]
+ unmatched_number = [_vector_path((91.0 + index * 3.0, 51.0, 93.0 + index * 3.0, 60.0), index) for index in range(3)]
rules = [
- _vector_path((10.0 + index * 12.0, 70.0, 20.0 + index * 12.0, 70.5), 10 + index, segment_count=5)
- for index in range(6)
+ _vector_path((10.0 + index * 12.0, 70.0, 20.0 + index * 12.0, 70.5), 10 + index, segment_count=5) for index in range(6)
]
excluded = [
_vector_path((20.0, 50.0, 24.0, 62.0), 30, stroke_visible=True),
diff --git a/tests/unittest/test_flash_pdf_graphics.py b/tests/unittest/test_flash_pdf_graphics.py
index 430827ff..83cddf36 100644
--- a/tests/unittest/test_flash_pdf_graphics.py
+++ b/tests/unittest/test_flash_pdf_graphics.py
@@ -52,6 +52,31 @@ def _path_info(
)
+def test_vertical_raster_tiles_merge_before_area_filter() -> None:
+ """验证同宽纵向切片先合并成完整图片,再应用单图面积门槛。"""
+
+ tiles = [(20.0, float(top), 180.0, float(top + 4)) for top in range(20, 60, 4)]
+
+ assert graphics._merge_vertical_raster_tiles(
+ tiles,
+ (200.0, 200.0),
+ ) == [(20.0, 20.0, 180.0, 60.0)]
+
+
+def test_full_page_raster_tiles_stay_separate() -> None:
+ """验证整页扫描图切片不合成单个容器,保留既有逐片输出。"""
+
+ tiles = [(0.0, float(top), 200.0, float(top + 10)) for top in range(0, 200, 10)]
+
+ assert (
+ graphics._merge_vertical_raster_tiles(
+ tiles,
+ (200.0, 200.0),
+ )
+ == tiles
+ )
+
+
def _parallel_rule_split_fixture(
*,
cross_gutter: bool = False,
@@ -151,9 +176,7 @@ def test_parallel_graphic_rule_rows_require_all_spatial_evidence(
) -> None:
"""验证横线、图形、栏沟或表格排除任一不成立时都不拆分。"""
- line, rules, images = _parallel_rule_split_fixture(
- cross_gutter=missing_evidence == "clear_gutter"
- )
+ line, rules, images = _parallel_rule_split_fixture(cross_gutter=missing_evidence == "clear_gutter")
table_bboxes: list[tuple[float, float, float, float]] = []
if missing_evidence == "right_rule":
rules = rules[:1]
@@ -323,16 +346,22 @@ def test_strong_graphic_core_binds_only_to_unique_containing_lane() -> None:
models._TextLane(left=305.0, right=545.0),
]
- assert graphics._strong_graphic_lane_index(
- (73.0, 516.0, 281.0, 655.0),
- lanes,
- 10.0,
- ) == 0
- assert graphics._strong_graphic_lane_index(
- (73.0, 516.0, 520.0, 655.0),
- lanes,
- 10.0,
- ) == -1
+ assert (
+ graphics._strong_graphic_lane_index(
+ (73.0, 516.0, 281.0, 655.0),
+ lanes,
+ 10.0,
+ )
+ == 0
+ )
+ assert (
+ graphics._strong_graphic_lane_index(
+ (73.0, 516.0, 520.0, 655.0),
+ lanes,
+ 10.0,
+ )
+ == -1
+ )
def test_axis_pair_requires_internal_two_dimensional_complex_path() -> None:
@@ -353,9 +382,7 @@ def test_axis_pair_requires_internal_two_dimensional_complex_path() -> None:
],
)
- assert graphics._detect_strong_graphic_bboxes(source) == [
- (20.0, 20.0, 80.0, 70.0)
- ]
+ assert graphics._detect_strong_graphic_bboxes(source) == [(20.0, 20.0, 80.0, 70.0)]
source.path_infos[2] = _path_info(
(25.0, 30.0, 75.0, 31.0),
@@ -434,9 +461,7 @@ def test_form_image_bbox_tightens_to_supported_internal_evidence() -> None:
],
)
- assert graphics._select_form_image_bboxes(source) == [
- (20.0, 25.0, 85.0, 81.0)
- ]
+ assert graphics._select_form_image_bboxes(source) == [(20.0, 25.0, 85.0, 81.0)]
def test_graphic_label_absorbs_short_axis_title_but_rejects_long_caption() -> None:
diff --git a/tests/unittest/test_flash_pdf_native_text.py b/tests/unittest/test_flash_pdf_native_text.py
index f30e6719..01a95be4 100644
--- a/tests/unittest/test_flash_pdf_native_text.py
+++ b/tests/unittest/test_flash_pdf_native_text.py
@@ -5,7 +5,7 @@ from typing import Any
import pytest
-from mineru.model.flash.pdf import native_text
+from mineru.model.flash.pdf import models, native_text
def _span(
@@ -48,6 +48,31 @@ def _line(
}
+def test_private_use_decorative_rule_becomes_axis_line() -> None:
+ """验证页首宽幅私用区重复字形不再进入文本输出。"""
+
+ decorative = models._LineItem(
+ text="\ue123" * 24,
+ bbox=(10.0, 12.0, 190.0, 16.0),
+ angle=0,
+ source_index=0,
+ )
+ body = models._LineItem(
+ text="body",
+ bbox=(10.0, 40.0, 80.0, 50.0),
+ angle=0,
+ source_index=1,
+ )
+
+ retained, rules = native_text._extract_decorative_text_rules(
+ [decorative, body],
+ (200.0, 200.0),
+ )
+
+ assert retained == [body]
+ assert [(rule.orientation, rule.bbox) for rule in rules] == [("horizontal", decorative.bbox)]
+
+
def test_mixed_footer_and_315_degree_watermark_are_split_before_filtering() -> None:
"""验证接近 315 度的 span 不会继续借用父行 0 度方向与巨型 bbox。"""
diff --git a/tests/unittest/test_flash_pdf_pipeline.py b/tests/unittest/test_flash_pdf_pipeline.py
index fad2a34c..003a829f 100644
--- a/tests/unittest/test_flash_pdf_pipeline.py
+++ b/tests/unittest/test_flash_pdf_pipeline.py
@@ -133,6 +133,39 @@ def test_prepare_page_uses_only_table_body_bbox_and_keeps_annotations_fixed(
]
+def test_table_detection_excludes_confirmed_masthead_separator() -> None:
+ """验证页首通栏分隔线不与下方真表格边界组成巨型候选。"""
+
+ source = models._PageSource(
+ page_size=(200.0, 300.0),
+ lines=[
+ _text_line("left masthead", (10.0, 10.0, 60.0, 20.0), 0),
+ _text_line("center masthead", (70.0, 10.0, 130.0, 20.0), 1),
+ _text_line("body", (10.0, 50.0, 190.0, 60.0), 2),
+ ],
+ chars=[],
+ drawing_lines=[
+ models._AxisLine(
+ bbox=(10.0, 30.0, 190.0, 31.0),
+ width=1.0,
+ orientation="horizontal",
+ ),
+ models._AxisLine(
+ bbox=(10.0, 100.0, 190.0, 101.0),
+ width=1.0,
+ orientation="horizontal",
+ ),
+ ],
+ )
+
+ retained = pipeline._table_detection_drawing_lines(
+ source,
+ {(10.0, 30.0, 190.0, 31.0)},
+ )
+
+ assert [line.bbox for line in retained] == [(10.0, 100.0, 190.0, 101.0)]
+
+
def test_repeated_large_image_requires_three_distinct_pages() -> None:
"""验证同页重复只计一次,面积恰好 8% 且跨三页时才命中水印。"""
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index 786fb294..55095b49 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -458,6 +458,36 @@ def test_explicit_pdf_fixtures_keep_expected_txt_block_inventory() -> None:
}
),
),
+ "中文论文3.pdf": (
+ 4,
+ Counter(
+ {
+ "caption": 6,
+ "doc_title": 1,
+ "header": 12,
+ "image": 3,
+ "page_footnote": 4,
+ "page_number": 3,
+ "paragraph_title": 6,
+ "text": 59,
+ }
+ ),
+ ),
+ "中文论文4.pdf": (
+ 5,
+ Counter(
+ {
+ "caption": 10,
+ "doc_title": 2,
+ "header": 19,
+ "image": 5,
+ "page_footnote": 1,
+ "paragraph_title": 13,
+ "table": 5,
+ "text": 46,
+ }
+ ),
+ ),
_FLASH_SYNTHETIC_PDF_NAME: (
8,
Counter(
diff --git a/tests/unittest/test_flash_pdf_semantics.py b/tests/unittest/test_flash_pdf_semantics.py
index 12f25ed1..e5a7d0b9 100644
--- a/tests/unittest/test_flash_pdf_semantics.py
+++ b/tests/unittest/test_flash_pdf_semantics.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import hashlib
import json
import re
+import unicodedata
from collections import Counter
from functools import lru_cache
from pathlib import Path
@@ -17,24 +18,9 @@ from scripts.review_flash_layout_geometry import (
_PROJECT_ROOT = Path(__file__).parents[2]
-_EXPECTATION_PATH = (
- _PROJECT_ROOT
- / "tests"
- / "fixtures"
- / "flash_layout_semantic_expectations.json"
-)
-_GEOMETRY_MANIFEST_PATH = (
- _PROJECT_ROOT
- / "tests"
- / "fixtures"
- / "flash_layout_geometry_manifest.json"
-)
-_BLOCK_EXPECTATION_PATH = (
- _PROJECT_ROOT
- / "tests"
- / "fixtures"
- / "flash_layout_block_expectations.json"
-)
+_EXPECTATION_PATH = _PROJECT_ROOT / "tests" / "fixtures" / "flash_layout_semantic_expectations.json"
+_GEOMETRY_MANIFEST_PATH = _PROJECT_ROOT / "tests" / "fixtures" / "flash_layout_geometry_manifest.json"
+_BLOCK_EXPECTATION_PATH = _PROJECT_ROOT / "tests" / "fixtures" / "flash_layout_block_expectations.json"
_FROZEN_SOIL_PATH = _PROJECT_ROOT / "demo" / "pdfs" / "中文论文.pdf"
_NATURAL_TEXT_TYPES = {"text", "doc_title", "paragraph_title"}
@@ -57,10 +43,15 @@ def _visible_text(value: Any) -> str:
return ""
-def _normalized_text(value: Any) -> str:
+def _normalized_text(
+ value: Any,
+ *,
+ nfkc: bool = False,
+) -> str:
"""移除排版空白,保留语义字符供版本化期望比较。"""
- return re.sub(r"\s+", "", _visible_text(value))
+ normalized = re.sub(r"\s+", "", _visible_text(value))
+ return unicodedata.normalize("NFKC", normalized) if nfkc else normalized
@lru_cache(maxsize=1)
@@ -93,9 +84,21 @@ def _frozen_soil_pages() -> tuple[tuple[dict[str, Any], ...], ...]:
return tuple(tuple(page) for page in pages)
+@lru_cache(maxsize=None)
+def _additional_chinese_paper_pages(
+ relative_path: str,
+) -> tuple[tuple[dict[str, Any], ...], ...]:
+ """按版本化相对路径缓存新增中文论文 Flash 页面。"""
+
+ source = _PROJECT_ROOT / relative_path
+ with PDFDocument(str(source)) as document:
+ pages = _analyze_native_document(document)
+ return tuple(tuple(page) for page in pages)
+
+
@lru_cache(maxsize=1)
def _block_expectations() -> tuple[dict[str, Any], ...]:
- """读取两篇中文论文的版本化 block 分组与类型库存期望。"""
+ """读取四篇中文论文的版本化 block 分组与类型库存期望。"""
payload = json.loads(
_BLOCK_EXPECTATION_PATH.read_text(encoding="utf-8"),
@@ -114,8 +117,11 @@ def _pages_for_expectation(
if expectation["path"] == "demo/pdfs/中文论文.pdf":
return _frozen_soil_pages()
- assert expectation["path"] == "demo/pdfs/中文论文2.pdf"
- return _pages()
+ if expectation["path"] == "demo/pdfs/中文论文2.pdf":
+ return _pages()
+ return _additional_chinese_paper_pages(
+ str(expectation["path"]),
+ )
def _block_containing_fragment(
@@ -123,20 +129,38 @@ def _block_containing_fragment(
fragment: str,
*,
block_type: str | None = None,
+ nfkc: bool = False,
) -> tuple[int, dict[str, Any]]:
"""返回唯一包含规范化片段的顶层 block 及其页内索引。"""
- normalized_fragment = _normalized_text(fragment)
+ normalized_fragment = _normalized_text(
+ fragment,
+ nfkc=nfkc,
+ )
matches = [
(index, block)
for index, block in enumerate(page)
if (block_type is None or block.get("type") == block_type)
- and normalized_fragment in _normalized_text(block.get("content"))
+ and normalized_fragment
+ in _normalized_text(
+ block.get("content"),
+ nfkc=nfkc,
+ )
]
assert len(matches) == 1, (
fragment,
block_type,
- [(index, block.get("type"), _normalized_text(block.get("content"))) for index, block in matches],
+ [
+ (
+ index,
+ block.get("type"),
+ _normalized_text(
+ block.get("content"),
+ nfkc=nfkc,
+ ),
+ )
+ for index, block in matches
+ ],
)
return matches[0]
@@ -147,21 +171,11 @@ def test_frozen_soil_paper_keeps_tracked_semantic_and_bbox_gold() -> None:
manifest = json.loads(
_GEOMETRY_MANIFEST_PATH.read_text(encoding="utf-8"),
)
- expected = next(
- document
- for document in manifest["documents"]
- if document["path"] == "demo/pdfs/中文论文.pdf"
- )
+ expected = next(document for document in manifest["documents"] if document["path"] == "demo/pdfs/中文论文.pdf")
assert hashlib.sha256(_FROZEN_SOIL_PATH.read_bytes()).hexdigest() == expected["sha256"]
pages = _frozen_soil_pages()
- assert [
- _page_fingerprint(list(page))
- for page in pages
- ] == [page["fingerprint"] for page in expected["pages"]]
- assert [
- _page_bbox_fingerprint(list(page))
- for page in pages
- ] == [page["bbox_fingerprint"] for page in expected["pages"]]
+ assert [_page_fingerprint(list(page)) for page in pages] == [page["fingerprint"] for page in expected["pages"]]
+ assert [_page_bbox_fingerprint(list(page)) for page in pages] == [page["bbox_fingerprint"] for page in expected["pages"]]
def _typed_texts(block_type: str) -> Counter[tuple[int, str]]:
@@ -179,37 +193,20 @@ def test_chinese_paper_matches_versioned_title_semantics() -> None:
"""验证双语文档标题和四十个章节标题与人工视觉金标完全一致。"""
expectation = _expectation()
- expected_doc_titles = Counter(
- (item["page_index"], item["text"])
- for item in expectation["doc_titles"]
- )
- expected_paragraph_titles = Counter(
- (item["page_index"], item["text"])
- for item in expectation["paragraph_titles"]
- )
+ expected_doc_titles = Counter((item["page_index"], item["text"]) for item in expectation["doc_titles"])
+ expected_paragraph_titles = Counter((item["page_index"], item["text"]) for item in expectation["paragraph_titles"])
assert _typed_texts("doc_title") == expected_doc_titles
assert _typed_texts("paragraph_title") == expected_paragraph_titles
- title_text = "\n".join(
- text
- for _page_index, text in _typed_texts("paragraph_title")
- )
- assert all(
- fragment not in title_text
- for fragment in expectation["forbidden_title_fragments"]
- )
+ title_text = "\n".join(text for _page_index, text in _typed_texts("paragraph_title"))
+ assert all(fragment not in title_text for fragment in expectation["forbidden_title_fragments"])
def test_chinese_paper_recovers_all_numbered_formula_blocks() -> None:
"""验证式一至式十四唯一成块,且公式内容不吸收相邻说明句。"""
expectation = _expectation()
- equations = [
- block
- for page in _pages()
- for block in page
- if block.get("type") == "equation"
- ]
+ equations = [block for page in _pages() for block in page if block.get("type") == "equation"]
tag_counts: Counter[str] = Counter()
contents = []
for block in equations:
@@ -220,33 +217,21 @@ def test_chinese_paper_recovers_all_numbered_formula_blocks() -> None:
tag_counts[match.group(1)] += 1
assert tag_counts == Counter(expectation["equation_tags"])
- assert all(
- fragment not in content
- for content in contents
- for fragment in expectation["forbidden_equation_fragments"]
- )
+ assert all(fragment not in content for content in contents for fragment in expectation["forbidden_equation_fragments"])
def test_chinese_paper_preserves_visual_controls_and_unique_blocks() -> None:
"""验证表图页码数量、双栏归属和顶层自然文本无近乎完全重叠。"""
expectation = _expectation()
- counts = Counter(
- str(block.get("type"))
- for page in _pages()
- for block in page
- )
- assert all(
- counts[block_type] == expected_count
- for block_type, expected_count in expectation["control_counts"].items()
- )
+ counts = Counter(str(block.get("type")) for page in _pages() for block in page)
+ assert all(counts[block_type] == expected_count for block_type, expected_count in expectation["control_counts"].items())
first_page = _pages()[0]
introduction = next(
block
for block in first_page
- if block.get("type") == "paragraph_title"
- and _normalized_text(block.get("content")) == "0引言"
+ if block.get("type") == "paragraph_title" and _normalized_text(block.get("content")) == "0引言"
)
introduction_bottom = float(introduction["bbox"][3])
assert not any(
@@ -260,12 +245,7 @@ def test_chinese_paper_preserves_visual_controls_and_unique_blocks() -> None:
overlaps = []
for page_index, page in enumerate(_pages()):
- blocks = [
- block
- for block in page
- if block.get("type") in _NATURAL_TEXT_TYPES
- and isinstance(block.get("bbox"), list)
- ]
+ blocks = [block for block in page if block.get("type") in _NATURAL_TEXT_TYPES and isinstance(block.get("bbox"), list)]
for first_index, first in enumerate(blocks):
first_bbox = [float(value) for value in first["bbox"]]
first_area = max(0.0, first_bbox[2] - first_bbox[0]) * max(
@@ -280,12 +260,10 @@ def test_chinese_paper_preserves_visual_controls_and_unique_blocks() -> None:
)
intersection = max(
0.0,
- min(first_bbox[2], second_bbox[2])
- - max(first_bbox[0], second_bbox[0]),
+ min(first_bbox[2], second_bbox[2]) - max(first_bbox[0], second_bbox[0]),
) * max(
0.0,
- min(first_bbox[3], second_bbox[3])
- - max(first_bbox[1], second_bbox[1]),
+ min(first_bbox[3], second_bbox[3]) - max(first_bbox[1], second_bbox[1]),
)
overlap = intersection / max(
1e-9,
@@ -303,10 +281,11 @@ def test_chinese_paper_preserves_visual_controls_and_unique_blocks() -> None:
def test_chinese_papers_match_versioned_block_group_expectations() -> None:
- """验证两篇真实论文的类型库存、指定合并和指定拆分与人工审阅期望一致。"""
+ """验证四篇真实论文的类型库存、指定合并和指定拆分与人工审阅期望一致。"""
for expectation in _block_expectations():
pages = _pages_for_expectation(expectation)
+ normalize_nfkc = expectation.get("normalize_nfkc") is True
counts = Counter(str(block.get("type")) for page in pages for block in page)
assert counts == Counter(expectation["type_counts"])
@@ -315,7 +294,15 @@ def test_chinese_papers_match_versioned_block_group_expectations() -> None:
matches = [
block
for block in page
- if block.get("type") == item["type"] and _normalized_text(block.get("content")) == item["text"]
+ if block.get("type") == item["type"]
+ and _normalized_text(
+ block.get("content"),
+ nfkc=normalize_nfkc,
+ )
+ == _normalized_text(
+ item["text"],
+ nfkc=normalize_nfkc,
+ )
]
assert len(matches) == 1, item
@@ -326,6 +313,7 @@ def test_chinese_papers_match_versioned_block_group_expectations() -> None:
page,
fragment,
block_type=group["type"],
+ nfkc=normalize_nfkc,
)[0]
for fragment in group["fragments"]
}
@@ -337,6 +325,7 @@ def test_chinese_papers_match_versioned_block_group_expectations() -> None:
_block_containing_fragment(
page,
fragment,
+ nfkc=normalize_nfkc,
)[0]
for fragment in group["fragments"]
}
@@ -344,13 +333,46 @@ def test_chinese_papers_match_versioned_block_group_expectations() -> None:
for item in expectation.get("forbidden_type_fragments", []):
page = pages[item["page_index"]]
- normalized_fragment = _normalized_text(item["fragment"])
+ normalized_fragment = _normalized_text(
+ item["fragment"],
+ nfkc=normalize_nfkc,
+ )
assert not any(
- block.get("type") == item["type"] and normalized_fragment in _normalized_text(block.get("content"))
+ block.get("type") == item["type"]
+ and normalized_fragment
+ in _normalized_text(
+ block.get("content"),
+ nfkc=normalize_nfkc,
+ )
for block in page
), item
+def test_chinese_paper_four_third_page_upper_band_inventory() -> None:
+ """验证中文论文4第三页原假大表区域恢复为指定的文本、图表和标题库存。"""
+
+ pages = _additional_chinese_paper_pages(
+ "demo/pdfs/中文论文4.pdf",
+ )
+ upper_band = [
+ block
+ for block in pages[2]
+ if block.get("type") != "header"
+ and isinstance(block.get("bbox"), list)
+ and float(block["bbox"][3]) <= 0.56
+ ]
+
+ assert Counter(str(block.get("type")) for block in upper_band) == Counter(
+ {
+ "paragraph_title": 3,
+ "text": 4,
+ "image": 1,
+ "caption": 2,
+ "table": 1,
+ }
+ )
+
+
def test_chinese_paper_continuation_caption_precedes_tight_table_body() -> None:
"""验证第3页续表 caption 不进入 HTML,且其边界位于收紧后的表体上方。"""
diff --git a/tests/unittest/test_flash_pdf_tables.py b/tests/unittest/test_flash_pdf_tables.py
index 151e32a0..ace6c41f 100644
--- a/tests/unittest/test_flash_pdf_tables.py
+++ b/tests/unittest/test_flash_pdf_tables.py
@@ -130,14 +130,10 @@ def _filled_grid_path_fixture(
(300.0 + cell_gap, top, right_edge, bottom),
]
for cell in cells:
- output.append(
- _path_info(cell, source_index, form_depth=form_depth)
- )
+ output.append(_path_info(cell, source_index, form_depth=form_depth))
source_index += 1
if row_index == 0:
- output.append(
- _path_info(cells[0], source_index, form_depth=form_depth)
- )
+ output.append(_path_info(cells[0], source_index, form_depth=form_depth))
source_index += 1
if row_index % 2 == 1:
middle = 0.5 * (top + bottom)
@@ -184,9 +180,7 @@ def test_filled_grid_geometry_detects_exact_outer_bbox_without_text() -> None:
drawing_lines=[],
path_infos=path_infos,
)
- assert [
- candidate.bbox for candidate in tables._detect_table_candidates(source)
- ] == [(100.0, 100.0, 500.0, 400.0)]
+ assert [candidate.bbox for candidate in tables._detect_table_candidates(source)] == [(100.0, 100.0, 500.0, 400.0)]
source.lines = [
models._LineItem(
@@ -197,36 +191,49 @@ def test_filled_grid_geometry_detects_exact_outer_bbox_without_text() -> None:
effective_height=20.0,
)
]
- assert [
- candidate.bbox for candidate in tables._detect_table_candidates(source)
- ] == [(100.0, 100.0, 500.0, 400.0)]
+ assert [candidate.bbox for candidate in tables._detect_table_candidates(source)] == [(100.0, 100.0, 500.0, 400.0)]
def test_filled_grid_geometry_rejects_incomplete_or_interfering_paths() -> None:
"""验证行带不足、横向破损、非根层和强图形重叠均不能生成外框。"""
page_size = (1000.0, 1000.0)
- assert tables._detect_filled_grid_table_candidates(
- _filled_grid_path_fixture(band_count=3),
- page_size,
- ) == []
- assert tables._detect_filled_grid_table_candidates(
- _filled_grid_path_fixture(right_edge=450.0),
- page_size,
- ) == []
- assert tables._detect_filled_grid_table_candidates(
- _filled_grid_path_fixture(cell_gap=10.0),
- page_size,
- ) == []
- assert tables._detect_filled_grid_table_candidates(
- _filled_grid_path_fixture(form_depth=1),
- page_size,
- ) == []
- assert tables._detect_filled_grid_table_candidates(
- _filled_grid_path_fixture(),
- page_size,
- [(120.0, 120.0, 480.0, 380.0)],
- ) == []
+ assert (
+ tables._detect_filled_grid_table_candidates(
+ _filled_grid_path_fixture(band_count=3),
+ page_size,
+ )
+ == []
+ )
+ assert (
+ tables._detect_filled_grid_table_candidates(
+ _filled_grid_path_fixture(right_edge=450.0),
+ page_size,
+ )
+ == []
+ )
+ assert (
+ tables._detect_filled_grid_table_candidates(
+ _filled_grid_path_fixture(cell_gap=10.0),
+ page_size,
+ )
+ == []
+ )
+ assert (
+ tables._detect_filled_grid_table_candidates(
+ _filled_grid_path_fixture(form_depth=1),
+ page_size,
+ )
+ == []
+ )
+ assert (
+ tables._detect_filled_grid_table_candidates(
+ _filled_grid_path_fixture(),
+ page_size,
+ [(120.0, 120.0, 480.0, 380.0)],
+ )
+ == []
+ )
def test_filled_grid_candidate_prevents_rule_bbox_expansion() -> None:
@@ -268,9 +275,7 @@ def test_filled_grid_candidate_prevents_rule_bbox_expansion() -> None:
candidates = tables._detect_table_candidates(source)
- assert [candidate.bbox for candidate in candidates] == [
- (100.0, 100.0, 500.0, 400.0)
- ]
+ assert [candidate.bbox for candidate in candidates] == [(100.0, 100.0, 500.0, 400.0)]
def test_filled_grid_materialization_uses_existing_spatial_projection(
@@ -550,14 +555,8 @@ def test_connected_rule_grid_expands_core_and_reclaims_sparse_bottom_row() -> No
line_indices=set(range(9)),
)
axis_lines = [
- *[
- _axis_line("horizontal", (0.0, top, 110.0, top + 0.1))
- for top in (8.0, 58.0, 80.0)
- ],
- *[
- _axis_line("vertical", (left, 8.0, left + 0.1, 80.1))
- for left in (0.0, 55.0, 109.9)
- ],
+ *[_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in (8.0, 58.0, 80.0)],
+ *[_axis_line("vertical", (left, 8.0, left + 0.1, 80.1)) for left in (0.0, 55.0, 109.9)],
]
expanded = tables._expand_candidates_to_connected_rule_grids(
@@ -579,18 +578,9 @@ def test_disconnected_stacked_rule_grids_remain_separate() -> None:
"""验证竖轨未跨越空白间距时,同跨度上下网格仍保持为两张表。"""
axis_lines = [
- *[
- _axis_line("horizontal", (0.0, top, 110.0, top + 0.1))
- for top in (8.0, 58.0, 90.0, 140.0)
- ],
- *[
- _axis_line("vertical", (left, 8.0, left + 0.1, 58.1))
- for left in (0.0, 55.0, 109.9)
- ],
- *[
- _axis_line("vertical", (left, 90.0, left + 0.1, 140.1))
- for left in (0.0, 55.0, 109.9)
- ],
+ *[_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in (8.0, 58.0, 90.0, 140.0)],
+ *[_axis_line("vertical", (left, 8.0, left + 0.1, 58.1)) for left in (0.0, 55.0, 109.9)],
+ *[_axis_line("vertical", (left, 90.0, left + 0.1, 140.1)) for left in (0.0, 55.0, 109.9)],
]
grid_bboxes = tables._connected_rule_grid_bboxes(axis_lines, 5.0)
@@ -646,20 +636,10 @@ def _closed_sparse_grid_fixture(
)
for fragment in fragments
]
- horizontal_tops = (
- (0.0, 20.0, 40.0)
- if horizontal_count == 3
- else (0.0, 40.0)
- )
+ horizontal_tops = (0.0, 20.0, 40.0) if horizontal_count == 3 else (0.0, 40.0)
axis_lines = [
- *[
- _axis_line("horizontal", (0.0, top, 110.0, top + 0.1))
- for top in horizontal_tops
- ],
- *[
- _axis_line("vertical", (left, 0.0, left + 0.1, 40.1))
- for left in (0.0, 55.0, 109.9)
- ],
+ *[_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in horizontal_tops],
+ *[_axis_line("vertical", (left, 0.0, left + 0.1, 40.1)) for left in (0.0, 55.0, 109.9)],
]
return rows, lines, axis_lines
@@ -683,9 +663,7 @@ def test_closed_grid_accepts_sparse_single_column_form_with_empty_row() -> None:
)
assert len(candidates) == 1
- assert candidates[0].core_bbox == pytest.approx(
- (0.0, 0.0, 110.0, 40.1)
- )
+ assert candidates[0].core_bbox == pytest.approx((0.0, 0.0, 110.0, 40.1))
assert candidates[0].line_indices == {0}
@@ -734,35 +712,30 @@ def test_closed_sparse_grid_rejects_incomplete_or_excluded_geometry(
lines = []
elif failure_mode == "short_outer_tracks":
axis_lines = [
- _axis_line("vertical", (line.bbox[0], 5.0, line.bbox[2], 35.0))
- if line.orientation == "vertical"
- else line
+ _axis_line("vertical", (line.bbox[0], 5.0, line.bbox[2], 35.0)) if line.orientation == "vertical" else line
for line in axis_lines
]
elif failure_mode == "only_two_vertical_tracks":
- axis_lines = [
- line
- for line in axis_lines
- if line.orientation != "vertical" or line.bbox[0] != 55.0
- ]
+ axis_lines = [line for line in axis_lines if line.orientation != "vertical" or line.bbox[0] != 55.0]
elif failure_mode == "one_occupied_column":
rows[0].fragments[1].bbox = (32.0, 10.0, 48.0, 15.0)
rows[0].fragments[1].local_bbox = rows[0].fragments[1].bbox
- rows[0].bbox = geometry._bbox_union_many(
- [fragment.bbox for fragment in rows[0].fragments]
- )
+ rows[0].bbox = geometry._bbox_union_many([fragment.bbox for fragment in rows[0].fragments])
else:
excluded_bboxes = [(0.0, 0.0, 110.0, 40.1)]
- assert tables._build_closed_rule_grid_candidates(
- rows,
- lines,
- (150.0, 100.0),
- 0,
- 5.0,
- axis_lines,
- excluded_bboxes,
- ) == []
+ assert (
+ tables._build_closed_rule_grid_candidates(
+ rows,
+ lines,
+ (150.0, 100.0),
+ 0,
+ 5.0,
+ axis_lines,
+ excluded_bboxes,
+ )
+ == []
+ )
def test_closed_grid_inside_form_bbox_is_not_a_table_candidate() -> None:
@@ -843,10 +816,7 @@ def _rule_table_fixture(
)
)
rule_tops = (8.0, 58.0) if rule_count == 2 else (8.0, 33.0, 58.0)
- axis_lines = [
- _axis_line("horizontal", (0.0, top, 110.0, top + 0.1))
- for top in rule_tops
- ]
+ axis_lines = [_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in rule_tops]
return rows, lines, axis_lines
@@ -895,22 +865,14 @@ def _compact_fully_ruled_table_fixture() -> tuple[
models._VisualRow(
fragments=fragments,
center_y=top + 2.5,
- bbox=geometry._bbox_union_many(
- [fragment.bbox for fragment in fragments]
- ),
+ 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 (8.0, 20.0, 32.0)
- ],
- *[
- _axis_line("vertical", (left, 8.1, left + 0.1, 32.0))
- for left in (0.0, 27.5, 55.0, 82.5, 109.9)
- ],
+ *[_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in (8.0, 20.0, 32.0)],
+ *[_axis_line("vertical", (left, 8.1, left + 0.1, 32.0)) for left in (0.0, 27.5, 55.0, 82.5, 109.9)],
]
return rows, lines, axis_lines
@@ -971,14 +933,57 @@ def test_compact_fully_ruled_two_row_table_is_accepted() -> None:
assert candidates[0].score == 8.0
+def test_caption_anchored_two_row_three_line_table_is_accepted() -> None:
+ """验证强表题可与三横线、两行稳定多列共同确认无竖线表格。"""
+
+ rows, lines, axis_lines = _compact_fully_ruled_table_fixture()
+ axis_lines = [line for line in axis_lines if line.orientation == "horizontal"]
+ lines.append(
+ models._LineItem(
+ text="Table 1 Results",
+ bbox=(20.0, 0.0, 90.0, 6.0),
+ angle=0,
+ source_index=100,
+ effective_height=5.0,
+ )
+ )
+ rows.append(
+ models._VisualRow(
+ fragments=[
+ models._Fragment(
+ text="Table 1 Results",
+ bbox=(20.0, 0.0, 90.0, 6.0),
+ local_bbox=(20.0, 0.0, 90.0, 6.0),
+ line_index=100,
+ visual_row_id=100,
+ )
+ ],
+ center_y=3.0,
+ bbox=(20.0, 0.0, 90.0, 6.0),
+ visual_row_id=100,
+ )
+ )
+ rows.sort(key=lambda row: row.center_y)
+
+ candidates = tables._build_rule_table_candidates(
+ rows,
+ lines,
+ (150.0, 200.0),
+ 0,
+ 5.0,
+ axis_lines,
+ )
+
+ assert len(candidates) == 1
+ assert candidates[0].line_indices == set(range(8))
+ assert [annotation.kind for annotation in candidates[0].annotations] == ["caption"]
+
+
def test_compact_grid_deduplicates_repeated_vertical_paths() -> None:
"""验证同位置重复竖线路径不会扩大紧凑表格的物理列数和评分。"""
rows, lines, axis_lines = _compact_fully_ruled_table_fixture()
- axis_lines.extend(
- _axis_line("vertical", (left + 0.3, 8.1, left + 0.4, 32.0))
- for left in (0.0, 27.5, 55.0, 82.5, 109.9)
- )
+ axis_lines.extend(_axis_line("vertical", (left + 0.3, 8.1, left + 0.4, 32.0)) for left in (0.0, 27.5, 55.0, 82.5, 109.9))
candidates = tables._build_rule_table_candidates(
rows,
@@ -1013,17 +1018,11 @@ def test_compact_two_row_layout_requires_complete_grid(
axis_lines = [line for line in axis_lines if line.orientation == "horizontal"]
elif failure_mode == "short_verticals":
axis_lines = [
- _axis_line("vertical", (line.bbox[0], 13.0, line.bbox[2], 27.0))
- if line.orientation == "vertical"
- else line
+ _axis_line("vertical", (line.bbox[0], 13.0, line.bbox[2], 27.0)) if line.orientation == "vertical" else line
for line in axis_lines
]
elif failure_mode == "missing_outer":
- axis_lines = [
- line
- for line in axis_lines
- if line.orientation != "vertical" or line.bbox[0] > 1.0
- ]
+ axis_lines = [line for line in axis_lines if line.orientation != "vertical" or line.bbox[0] > 1.0]
elif failure_mode == "same_cell":
rows[0].fragments[1].bbox = (8.0, 10.0, 18.0, 15.0)
rows[0].fragments[1].local_bbox = rows[0].fragments[1].bbox
@@ -1049,12 +1048,8 @@ def test_compact_admission_does_not_accept_two_row_column_prose() -> None:
rows, lines, axis_lines = _compact_fully_ruled_table_fixture()
for row in rows:
row.fragments = [row.fragments[0], row.fragments[-1]]
- row.bbox = geometry._bbox_union_many(
- [fragment.bbox for fragment in row.fragments]
- )
- retained_indices = {
- fragment.line_index for row in rows for fragment in row.fragments
- }
+ row.bbox = geometry._bbox_union_many([fragment.bbox for fragment in row.fragments])
+ retained_indices = {fragment.line_index for row in rows for fragment in row.fragments}
lines = [line for line in lines if line.source_index in retained_indices]
axis_lines = [line for line in axis_lines if line.orientation == "horizontal"]
@@ -1230,10 +1225,7 @@ def test_long_sparse_rule_interval_cannot_bridge_two_low_column_tables() -> None
visual_row_id=row_index,
)
)
- rules = [
- _axis_line("horizontal", (0.0, top, 110.0, top + 0.1))
- for top in (0.0, 40.0, 120.0, 150.0)
- ]
+ rules = [_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in (0.0, 40.0, 120.0, 150.0)]
assert not tables._rule_intervals_are_column_compatible(rows, rules, 5.0)
@@ -1564,9 +1556,7 @@ def test_auxiliary_table_note_requires_neutral_core_reference(
0,
)
- assert [tables._visual_row_text(row) for row in selected] == [
- f"{marker} neutral explanation"
- ]
+ assert [tables._visual_row_text(row) for row in selected] == [f"{marker} neutral explanation"]
def test_auxiliary_table_note_rejects_marker_without_core_reference() -> None:
@@ -1577,15 +1567,18 @@ def test_auxiliary_table_note_rejects_marker_without_core_reference() -> None:
"none",
)
- assert tables._collect_footnote_rows(
- rows,
- lines,
- rule_bbox,
- 8.0,
- core_indices,
- page_size,
- 0,
- ) == []
+ assert (
+ tables._collect_footnote_rows(
+ rows,
+ lines,
+ rule_bbox,
+ 8.0,
+ core_indices,
+ page_size,
+ 0,
+ )
+ == []
+ )
def test_superscript_reference_requires_smaller_raised_glyph() -> None:
@@ -1615,15 +1608,18 @@ def test_auxiliary_table_note_rejects_body_or_title_sized_first_row(
note_height=note_height,
)
- assert tables._collect_footnote_rows(
- rows,
- lines,
- rule_bbox,
- 8.0,
- core_indices,
- page_size,
- 0,
- ) == []
+ assert (
+ tables._collect_footnote_rows(
+ rows,
+ lines,
+ rule_bbox,
+ 8.0,
+ core_indices,
+ page_size,
+ 0,
+ )
+ == []
+ )
def test_auxiliary_table_note_rejects_loose_first_gap() -> None:
@@ -1642,15 +1638,18 @@ def test_auxiliary_table_note_rejects_loose_first_gap() -> None:
visual_row_id=1,
)
- assert tables._collect_footnote_rows(
- rows,
- lines,
- rule_bbox,
- 8.0,
- core_indices,
- page_size,
- 0,
- ) == []
+ assert (
+ tables._collect_footnote_rows(
+ rows,
+ lines,
+ rule_bbox,
+ 8.0,
+ core_indices,
+ page_size,
+ 0,
+ )
+ == []
+ )
def test_auxiliary_table_note_requires_smaller_than_body_reference() -> None:
@@ -1663,15 +1662,18 @@ def test_auxiliary_table_note_requires_smaller_than_body_reference() -> None:
for line in lines[2:]:
line.effective_height = 8.5
- assert tables._collect_footnote_rows(
- rows,
- lines,
- rule_bbox,
- 8.0,
- core_indices,
- page_size,
- 0,
- ) == []
+ assert (
+ tables._collect_footnote_rows(
+ rows,
+ lines,
+ rule_bbox,
+ 8.0,
+ core_indices,
+ page_size,
+ 0,
+ )
+ == []
+ )
def test_auxiliary_table_note_uses_clipped_corridor_projection() -> None:
@@ -1704,15 +1706,18 @@ def test_auxiliary_table_note_uses_clipped_corridor_projection() -> None:
)
)
- assert tables._collect_footnote_rows(
- rows,
- lines,
- rule_bbox,
- 8.0,
- core_indices,
- page_size,
- 0,
- ) == []
+ assert (
+ tables._collect_footnote_rows(
+ rows,
+ lines,
+ rule_bbox,
+ 8.0,
+ core_indices,
+ page_size,
+ 0,
+ )
+ == []
+ )
def test_rotated_auxiliary_table_note_uses_local_superscript_geometry() -> None:
@@ -1734,9 +1739,7 @@ def test_rotated_auxiliary_table_note_uses_local_superscript_geometry() -> None:
90,
)
- assert [tables._visual_row_text(row) for row in selected] == [
- "7 neutral explanation"
- ]
+ assert [tables._visual_row_text(row) for row in selected] == ["7 neutral explanation"]
def test_table_note_chain_cannot_expand_beyond_ten_line_heights() -> None:
@@ -1745,10 +1748,7 @@ def test_table_note_chain_cannot_expand_beyond_ten_line_heights() -> None:
lines: list[models._LineItem] = []
rows: list[models._VisualRow] = []
specs = [("Note: neutral", (0.0, 51.0, 80.0, 59.0))]
- specs.extend(
- (f"continuation-{index}", (0.0, 59.5 + 8.5 * index, 80.0, 67.5 + 8.5 * index))
- for index in range(12)
- )
+ specs.extend((f"continuation-{index}", (0.0, 59.5 + 8.5 * index, 80.0, 67.5 + 8.5 * index)) for index in range(12))
for source_index, (text, bbox) in enumerate(specs):
lines.append(
models._LineItem(
@@ -1860,15 +1860,18 @@ def test_numeric_body_row_cannot_start_table_note_chain() -> None:
visual_row_id=0,
)
- assert tables._collect_footnote_rows(
- [row],
- [line],
- (0.0, 0.0, 100.0, 50.0),
- 10.0,
- set(),
- (100.0, 100.0),
- 0,
- ) == []
+ assert (
+ tables._collect_footnote_rows(
+ [row],
+ [line],
+ (0.0, 0.0, 100.0, 50.0),
+ 10.0,
+ set(),
+ (100.0, 100.0),
+ 0,
+ )
+ == []
+ )
@pytest.mark.parametrize("projection_mode", ["empty", "error"])
diff --git a/tests/unittest/test_flash_pdf_text_blocks.py b/tests/unittest/test_flash_pdf_text_blocks.py
index e0e81980..e300e92a 100644
--- a/tests/unittest/test_flash_pdf_text_blocks.py
+++ b/tests/unittest/test_flash_pdf_text_blocks.py
@@ -64,6 +64,97 @@ def test_hanging_indent_groups_neutral_entries_and_ignores_centered_heading() ->
]
+def test_nested_columns_ignore_intervening_full_width_metadata_band() -> None:
+ """验证左右栏行交错时,中间全宽元数据簇不阻断局部双栏推断。"""
+
+ lines = [
+ _text_line("full width", (0.0, 0.0, 100.0, 10.0), 0),
+ *[
+ _text_line(
+ f"left {index}",
+ (0.0, 30.0 + 12.0 * index, 45.0, 40.0 + 12.0 * index),
+ 1 + 2 * index,
+ )
+ for index in range(4)
+ ],
+ *[
+ _text_line(
+ f"right {index}",
+ (55.0, 30.0 + 12.0 * index, 100.0, 40.0 + 12.0 * index),
+ 2 + 2 * index,
+ )
+ for index in range(4)
+ ],
+ _text_line("author one", (20.0, 100.0, 80.0, 110.0), 20),
+ _text_line("author two", (20.0, 112.0, 80.0, 122.0), 21),
+ _text_line("author three", (20.0, 124.0, 80.0, 134.0), 22),
+ ]
+
+ lanes = line_layout._infer_text_lanes(
+ [(line, line.bbox) for line in lines],
+ 100.0,
+ 10.0,
+ )
+ regular = sorted(
+ (
+ lane
+ for lane in lanes
+ if not lane.is_span and len(lane.lines) >= 4 and min(item[1][1] for item in lane.lines) >= 30.0
+ ),
+ key=lambda lane: lane.left,
+ )
+
+ assert [(lane.left, lane.right) for lane in regular[:2]] == [
+ (0.0, 45.0),
+ (55.0, 100.0),
+ ]
+
+
+def test_paragraph_formula_context_merges_dense_same_lane_text() -> None:
+ """验证复杂行内分式及其同栏前后正文恢复为一个文本块。"""
+
+ def block(
+ content: str,
+ bbox: tuple[float, float, float, float],
+ ) -> dict[str, object]:
+ """构造含栏带和行框的最小文本块。"""
+
+ return {
+ "type": "text",
+ "bbox": bbox,
+ "angle": 0,
+ "content": content,
+ "_local_line_bboxes": [bbox],
+ "_line_heights": [10.0],
+ "_font_signatures": {("Body", 0)},
+ "_lane_interval": (0.0, 100.0),
+ "_lane_is_span": False,
+ "_hard_break_before": False,
+ "_leading_emphasis_start": False,
+ }
+
+ blocks = [
+ block("prefix", (0.0, 0.0, 30.0, 10.0)),
+ block("body:", (0.0, 10.0, 100.0, 20.0)),
+ block("I=ΔT/ΔH", (0.0, 21.0, 100.0, 31.0)),
+ block("tail", (0.0, 32.0, 100.0, 42.0)),
+ {
+ **block("other lane", (120.0, 0.0, 220.0, 10.0)),
+ "_lane_interval": (120.0, 220.0),
+ },
+ ]
+ blocks[2]["_paragraph_formula_context"] = True
+
+ merged = text_blocks._merge_paragraph_formula_context_blocks(
+ blocks,
+ )
+
+ assert [item["content"] for item in merged] == [
+ "prefix body: I=ΔT/ΔH tail",
+ "other lane",
+ ]
+
+
def test_hanging_indent_accepts_reference_spacing_and_italic_tail() -> None:
"""验证 1.25 倍行高的参考文献间距不会拆掉前一条斜体尾行。"""
@@ -1356,9 +1447,7 @@ def test_nested_lane_accepts_wider_one_sided_rows_and_expands_interval() -> None
(10.0, top, 190.0, top + 8.0),
30 + row_index,
)
- for row_index, top in enumerate(
- (90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0)
- )
+ for row_index, top in enumerate((90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0))
)
lanes = line_layout._infer_text_lanes(
@@ -1367,18 +1456,13 @@ def test_nested_lane_accepts_wider_one_sided_rows_and_expands_interval() -> None
8.0,
)
- left_lane = next(
- lane
- for lane in lanes
- if any(line.text == "wide-left-one" for line, _bbox in lane.lines)
- )
+ left_lane = next(lane for lane in lanes if any(line.text == "wide-left-one" for line, _bbox in lane.lines))
assert not left_lane.is_span
assert left_lane.right == pytest.approx(105.0)
- assert {
- line.text
- for line, _bbox in left_lane.lines
- if line.text.startswith("wide-left")
- } == {"wide-left-one", "wide-left-two"}
+ assert {line.text for line, _bbox in left_lane.lines if line.text.startswith("wide-left")} == {
+ "wide-left-one",
+ "wide-left-two",
+ }
def test_regular_lanes_accept_wider_one_sided_rows_but_keep_gutter_crossing_span() -> None:
@@ -1414,16 +1498,8 @@ def test_regular_lanes_accept_wider_one_sided_rows_but_keep_gutter_crossing_span
8.0,
)
- left_lane = next(
- lane
- for lane in lanes
- if any(line.text == "wide-left-one" for line, _bbox in lane.lines)
- )
- span_lane = next(
- lane
- for lane in lanes
- if any(line.text == "crosses-gutter" for line, _bbox in lane.lines)
- )
+ left_lane = next(lane for lane in lanes if any(line.text == "wide-left-one" for line, _bbox in lane.lines))
+ span_lane = next(lane for lane in lanes if any(line.text == "crosses-gutter" for line, _bbox in lane.lines))
assert not left_lane.is_span
assert left_lane.right == pytest.approx(105.0)
assert span_lane.is_span
@@ -2296,10 +2372,7 @@ def test_canonical_visual_resplit_separates_cross_column_coarse_row() -> None:
zip("ABCDEFGH", positions, strict=True),
)
]
- visual_bboxes = {
- index: (position, 10.0, position + 5.0, 20.0)
- for index, position in enumerate(positions)
- }
+ visual_bboxes = {index: (position, 10.0, position + 5.0, 20.0) for index, position in enumerate(positions)}
line = models._LineItem(
text="ABCDEFGH",
bbox=(0.0, 10.0, 100.0, 20.0),
@@ -2453,13 +2526,10 @@ def test_local_aligned_column_replaces_polluted_full_width_lane() -> None:
]
blocks = text_blocks._build_text_blocks(lines, [], (200.0, 120.0))
- introduction_body = next(
- block for block in blocks if "local first sentence" in block["content"]
- )
+ introduction_body = next(block for block in blocks if "local first sentence" in block["content"])
assert introduction_body["content"] == (
- "local first sentence. local second sentence local third sentence "
- "local final sentence."
+ "local first sentence. local second sentence local third sentence local final sentence."
)
assert introduction_body["_lane_interval"] == (110.0, 200.0)
@@ -2761,10 +2831,7 @@ def test_inline_math_fragments_merge_into_wide_split_text_row() -> None:
assert len(merged) == 1
assert merged[0]["bbox"] == (10.0, 34.0, 90.0, 56.0)
- assert all(
- token in merged[0]["content"]
- for token in ("body host", "numerator", "denominator", "power")
- )
+ assert all(token in merged[0]["content"] for token in ("body host", "numerator", "denominator", "power"))
assert merged[0][text_blocks._INLINE_MATH_RECOVERY_MARKER] is True
@@ -2873,10 +2940,7 @@ def test_inline_math_paragraph_continuations_merge_five_wide_blocks() -> None:
assert len(merged) == 1
assert merged[0]["bbox"] == (20.0, 40.0, 172.0, 175.0)
- assert all(
- f"paragraph part {index}" in str(merged[0]["content"])
- for index in range(5)
- )
+ assert all(f"paragraph part {index}" in str(merged[0]["content"]) for index in range(5))
assert merged[0][text_blocks._INLINE_MATH_RECOVERY_MARKER] is True
@@ -3109,7 +3173,4 @@ def test_front_matter_grid_merges_each_author_column_independently() -> None:
assert len(merged_authors) == 4
for column_index, block in enumerate(merged_authors):
- assert all(
- f"author-{column_index}-row-{row_index}" in block["content"]
- for row_index in range(3)
- )
+ assert all(f"author-{column_index}-row-{row_index}" in block["content"] for row_index in range(3))
diff --git a/tests/unittest/test_flash_pdf_titles.py b/tests/unittest/test_flash_pdf_titles.py
index f71b0619..d0b386e1 100644
--- a/tests/unittest/test_flash_pdf_titles.py
+++ b/tests/unittest/test_flash_pdf_titles.py
@@ -59,6 +59,37 @@ def test_heading_like_content_with_body_layout_remains_text() -> None:
assert lines[2].semantic_type is None
+def test_explicit_section_number_rejects_century_and_decimal_sentence() -> None:
+ """验证通用章节编号补标标题,同时排除世纪年代和小数正文。"""
+
+ body_font = ("Body", 0)
+ lines = [
+ _text_line("20 century body", (0.0, 10.0, 80.0, 20.0), 0, font_signature=body_font),
+ _text_line("ordinary body one", (0.0, 22.0, 100.0, 32.0), 1, font_signature=body_font),
+ _text_line("2 Section heading", (0.0, 45.0, 55.0, 55.0), 2, font_signature=body_font),
+ _text_line("ordinary body two", (0.0, 62.0, 100.0, 72.0), 3, font_signature=body_font),
+ _text_line("ordinary body three", (0.0, 74.0, 100.0, 84.0), 4, font_signature=body_font),
+ _text_line("0.26 value, continues", (0.0, 96.0, 100.0, 106.0), 5, font_signature=body_font),
+ _text_line("ordinary body four", (0.0, 108.0, 100.0, 118.0), 6, font_signature=body_font),
+ ]
+ profile = titles._DocumentBodyProfile(
+ body_height=10.0,
+ body_weight=400.0,
+ regular_fonts=frozenset({body_font}),
+ )
+
+ titles._classify_explicit_section_titles(
+ lines,
+ (120.0, 150.0),
+ container_bboxes=[],
+ document_body_profile=profile,
+ )
+
+ assert lines[0].semantic_type is None
+ assert lines[2].semantic_type == "paragraph_title"
+ assert lines[5].semantic_type is None
+
+
def test_document_regular_fonts_only_use_body_height_band() -> None:
"""验证跨页重复的大字号标题字体不会进入全文常规正文字体集合。"""
@@ -256,11 +287,7 @@ def test_body_height_section_titles_mark_only_repeated_short_anchors() -> None:
"paragraph_title",
"paragraph_title",
]
- assert all(
- line.semantic_type is None
- for index, line in enumerate(lines)
- if index not in {0, 4}
- )
+ assert all(line.semantic_type is None for index, line in enumerate(lines) if index not in {0, 4})
def test_physical_title_gap_ignores_disjoint_column_and_keeps_overlapping_row() -> None:
@@ -324,9 +351,7 @@ def test_grid_title_suppression_requires_two_distinct_parallel_bands() -> None:
source_index,
)
source_index += 1
- lane.lines.extend(
- [(second_opener, second_opener.bbox), (second_body, second_body.bbox)]
- )
+ lane.lines.extend([(second_opener, second_opener.bbox), (second_body, second_body.bbox)])
suppressions = titles._find_repeated_grid_title_suppressions(lanes, 10.0)
diff --git a/tests/unittest/test_flash_pdf_visual_annotations.py b/tests/unittest/test_flash_pdf_visual_annotations.py
index fecaf7e8..d64a59be 100644
--- a/tests/unittest/test_flash_pdf_visual_annotations.py
+++ b/tests/unittest/test_flash_pdf_visual_annotations.py
@@ -113,6 +113,28 @@ def test_strong_caption_markers_reject_body_references(content: str) -> None:
assert not visual_annotations._is_strong_caption_text(content)
+def test_stacked_bilingual_captions_share_visual_parent() -> None:
+ """验证编号相同、上下紧邻的中英文图题共同绑定一个图片。"""
+
+ image = _visual_block((20.0, 20.0, 180.0, 120.0))
+ chinese = _text_block(
+ "图 1 系统结构",
+ (55.0, 125.0, 145.0, 135.0),
+ )
+ english = _text_block(
+ "Fig. 1 System architecture",
+ (50.0, 138.0, 150.0, 145.0),
+ line_height=7.0,
+ font_signature=("EnglishCaption", 400),
+ )
+ blocks = [image, chinese, english]
+
+ regions = _classify_with_text_block_merge(blocks)
+
+ assert chinese["type"] == english["type"] == "caption"
+ assert regions == [[image, chinese, english]]
+
+
@pytest.mark.parametrize(
"content",
[
@@ -715,28 +737,14 @@ def test_cross_lane_caption_companion_rejects_unsafe_geometry(case: str) -> None
(20.0, 90.5, 90.0, 110.5),
lane_interval=(20.0, 90.0),
)
- companion_bbox = (
- (110.0, 94.0, 180.0, 114.0)
- if case == "misaligned"
- else (110.0, 90.0, 180.0, 110.0)
- )
+ companion_bbox = (110.0, 94.0, 180.0, 114.0) if case == "misaligned" else (110.0, 90.0, 180.0, 110.0)
companion = _text_block(
"plain continuation",
companion_bbox,
line_height=12.0 if case == "line_height" else 10.0,
- lane_interval=(
- (20.0, 90.0)
- if case == "same_lane"
- else (110.0, 180.0)
- ),
+ lane_interval=((20.0, 90.0) if case == "same_lane" else (110.0, 180.0)),
lane_is_span=case == "span_lane",
- font_signature=(
- None
- if case == "missing_font"
- else ("OtherFont", 400)
- if case == "font"
- else ("TestFont", 400)
- ),
+ font_signature=(None if case == "missing_font" else ("OtherFont", 400) if case == "font" else ("TestFont", 400)),
)
extra_blocks: list[dict[str, object]] = []
if case == "narrow_parent":
@@ -750,9 +758,7 @@ def test_cross_lane_caption_companion_rejects_unsafe_geometry(case: str) -> None
)
)
elif case == "competing_parent":
- extra_blocks.append(
- _visual_block((110.0, 82.0, 180.0, 86.0))
- )
+ extra_blocks.append(_visual_block((110.0, 82.0, 180.0, 86.0)))
blocks = [parent, anchor, *extra_blocks, companion]
_classify_with_text_block_merge(blocks)