Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
fix: refactor style anomaly handling to use style_scale_repaired flag and improve tier offset calculations
myhloliba37c36ae5f2
diff --git a/mineru/model/flash/pdf/char_geometry.py b/mineru/model/flash/pdf/char_geometry.pyindex 7cfd87fe..e780f929 100644--- a/mineru/model/flash/pdf/char_geometry.py+++ b/mineru/model/flash/pdf/char_geometry.py@@ -52,12 +52,14 @@ STYLE_INFLATION_MIN_LINE_COUNT = 3STYLE_INFLATION_MIN_LINE_SHARE = 0.50STYLE_INFLATION_MIN_PAGE_COUNT = 2STYLE_INFLATION_MIN_SCALE = 4.0-STYLE_INFLATION_DOCUMENT_MIN_LINE_COUNT = 20-STYLE_INFLATION_DOCUMENT_MIN_PAGE_COUNT = 15+STYLE_TIER_MIN_MEMBER_COUNT = 2+STYLE_TIER_MIN_MEMBER_SHARE = 0.15+STYLE_TIER_GAP_RATIO = 1.35RunKey: TypeAlias = tuple[str, float, int, int, int, str]LineKey: TypeAlias = tuple[int, int]CharKey: TypeAlias = tuple[int, int]+LooseTierSample: TypeAlias = tuple[float, float, float, float]@dataclass(slots=True)@@ -101,6 +103,7 @@ class DocumentGeometryPlan:char_repairs: dict[CharKey, CharLayoutGeometry] = field(default_factory=dict)line_repairs: dict[LineKey, LineGeometryRepair] = field(default_factory=dict)line_style_scales: dict[LineKey, float] = field(default_factory=dict)+ style_inflated_runs: set[RunKey] = field(default_factory=set)run_diagnostics: list[dict[str, Any]] = field(default_factory=list)document_style_anomaly: bool = False@@ -223,6 +226,78 @@ def _quantile(values: list[float], fraction: float) -> float:return ordered[lower] * (1.0 - weight) + ordered[upper] * weight+def _line_loose_tier_offsets(+ samples: list[LooseTierSample],+ em_height: float,+) -> tuple[float, float] | None:+ """把归一化 loose 高度分档,并返回最大异常档回缩到次档后的 ascent/descent。"""++ if len(samples) < 2 * STYLE_TIER_MIN_MEMBER_COUNT or em_height <= 0:+ return None+ normalized = sorted(+ (+ (ascent + descent) / max(font_size, tight_height, 0.1),+ ascent,+ descent,+ tight_height,+ font_size,+ )+ for ascent, descent, tight_height, font_size in samples+ )+ tiers: list[list[tuple[float, float, float, float, float]]] = []+ for item in normalized:+ if (+ not tiers+ or item[0]+ > STYLE_TIER_GAP_RATIO+ * statistics.median(member[0] for member in tiers[-1])+ ):+ tiers.append([item])+ else:+ tiers[-1].append(item)+ if len(tiers) < 2:+ return None+ upper_tier = tiers[-1]+ reference_tier = tiers[-2]+ minimum_members = max(+ STYLE_TIER_MIN_MEMBER_COUNT,+ math.ceil(STYLE_TIER_MIN_MEMBER_SHARE * len(samples)),+ )+ if (+ len(upper_tier) < minimum_members+ or len(reference_tier) < STYLE_TIER_MIN_MEMBER_COUNT+ ):+ return None+ upper_loose_heights = [member[1] + member[2] for member in upper_tier]+ upper_font_sizes = [member[4] for member in upper_tier if member[4] > 0]+ upper_tight_heights = [member[3] for member in upper_tier]+ if (+ statistics.median(upper_loose_heights)+ <= STYLE_INFLATION_LOOSE_FONT_RATIO+ * (+ statistics.median(upper_font_sizes)+ if upper_font_sizes+ else 0.0+ )+ or statistics.median(upper_loose_heights)+ <= STYLE_INFLATION_LOOSE_TIGHT_RATIO+ * max(0.1, _quantile(upper_tight_heights, 0.75))+ ):+ return None+ reference_ascent_ratios = [+ member[1] / max(member[4], member[3], 0.1)+ for member in reference_tier+ ]+ reference_descent_ratios = [+ member[2] / max(member[4], member[3], 0.1)+ for member in reference_tier+ ]+ return (+ statistics.median(reference_ascent_ratios) * em_height,+ statistics.median(reference_descent_ratios) * em_height,+ )++def _coerce_origin(value: Any) -> tuple[float, float] | None:"""把 side map 中的 origin 收敛为有限二维坐标。"""@@ -636,55 +711,11 @@ def _mark_style_inflated_runs(def _document_uses_global_style_calibration(- lines_by_page: list[list[_LineItem]],- by_line: dict[LineKey, list[_CharSample]],style_inflated_runs: set[RunKey],) -> bool:- """判断异常 run 是否以跨页稀疏模式反复污染全文排版尺度。"""+ """只要存在已通过跨页重复证据的异常 run,就启用全文统一字体尺度。"""- if not style_inflated_runs:- return False- affected_lines: set[LineKey] = set()- for line_key, line_samples in by_line.items():- relevant = [- sample- for sample in line_samples- if sample.is_anchor- and sample.run_key in style_inflated_runs- ]- if not relevant:- continue- font_sizes = [- sample.font_size- for sample in relevant- if sample.font_size > 0- ]- tight_heights = [- sample.local_tight_bbox[3]- - sample.local_tight_bbox[1]- for sample in relevant- ]- style_scale = max(- statistics.median(font_sizes)- if font_sizes- else 0.0,- _quantile(tight_heights, 0.75),- )- if (- style_scale >= STYLE_INFLATION_MIN_SCALE- and relevant[0].line.effective_height- > STYLE_INFLATION_LOOSE_FONT_RATIO * style_scale- and relevant[0].line.effective_height- > STYLE_INFLATION_LOOSE_TIGHT_RATIO- * max(0.1, _quantile(tight_heights, 0.75))- ):- affected_lines.add(line_key)- return (- len(affected_lines)- >= STYLE_INFLATION_DOCUMENT_MIN_LINE_COUNT- and len({page_index for page_index, _source_index in affected_lines})- >= STYLE_INFLATION_DOCUMENT_MIN_PAGE_COUNT- )+ return bool(style_inflated_runs)def _apply_style_scale_repairs(@@ -735,6 +766,26 @@ def _apply_style_scale_repairs(plan.line_style_scales[line_key] = style_scale+def _line_uses_repaired_style_scale(+ line: _LineItem,+ style_inflated_runs: set[RunKey],+) -> bool:+ """按字体族、字号、flags 和方向把异常 run 证据投影到当前视觉行。"""++ if line.font_signature is None or line.em_height <= 0:+ return False+ family = _normalized_font_family(line.font_signature[0])+ style_size = round(line.em_height * 4.0) / 4.0+ flags = line.font_signature[1]+ return any(+ family == run_key[0]+ and abs(style_size - run_key[1]) <= 0.25+ and flags == run_key[2]+ and line.angle == run_key[4]+ for run_key in style_inflated_runs+ )++def _restore_stable_legacy_source_bboxes(by_line: dict[LineKey, list[_CharSample]],page_sizes: list[tuple[float, float]],@@ -1095,7 +1146,31 @@ def _repair_y_lines(if healthy_ascents and healthy_descentselse math.inf)- if len(healthy_ascents) >= Y_HEALTHY_LOOSE_SAMPLE_MIN and healthy_loose_height <= 1.5 * em_height:+ tier_offsets = _line_loose_tier_offsets(+ [+ (+ max(+ 0.0,+ sample.local_origin[1]+ - sample.local_source_bbox[1],+ ),+ max(+ 0.0,+ sample.local_source_bbox[3]+ - sample.local_origin[1],+ ),+ sample.local_tight_bbox[3]+ - sample.local_tight_bbox[1],+ sample.font_size,+ )+ for sample in analysis.dominant+ if sample.run_key == analysis.run_key+ ],+ em_height,+ )+ if tier_offsets is not None:+ ascent, descent = tier_offsets+ elif len(healthy_ascents) >= Y_HEALTHY_LOOSE_SAMPLE_MIN and healthy_loose_height <= 1.5 * em_height:ascent = statistics.median(healthy_ascents)descent = statistics.median(healthy_descents)else:@@ -1251,9 +1326,8 @@ def build_document_geometry_plan(samples, by_line = _collect_samples(lines_by_page, geometries, page_sizes)runs = _build_run_stats(samples, by_line)style_inflated_runs = _mark_style_inflated_runs(runs)+ plan.style_inflated_runs = style_inflated_runsplan.document_style_anomaly = _document_uses_global_style_calibration(- lines_by_page,- by_line,style_inflated_runs,)_apply_style_scale_repairs(@@ -1291,12 +1365,15 @@ def apply_line_geometry_repairs("""把文档计划应用到当前仍可参与 Flash 布局的行。"""for line in lines:- line.document_style_anomaly = plan.document_style_anomalystyle_scale = plan.line_style_scales.get((page_index, line.source_index),)if style_scale is not None:line.em_height = style_scale+ line.style_scale_repaired = _line_uses_repaired_style_scale(+ line,+ plan.style_inflated_runs,+ )repair = plan.line_repairs.get((page_index, line.source_index))if repair is None:continuediff --git a/mineru/model/flash/pdf/formulas.py b/mineru/model/flash/pdf/formulas.pyindex 3e56c034..32d679bd 100644--- a/mineru/model/flash/pdf/formulas.py+++ b/mineru/model/flash/pdf/formulas.py@@ -703,7 +703,7 @@ def _is_wide_tagged_formula_member(member_width = member_bbox[2] - member_bbox[0]marker = _standalone_formula_number_marker(anchor_line.text)return (- anchor_line.document_style_anomaly+ anchor_line.style_scale_repairedand marker is not Noneand _FORMULA_NUMBER_MARKER_RE.fullmatch(marker)and 0.75 * lane_width < member_width <= 0.95 * lane_width@@ -719,7 +719,7 @@ def _is_single_line_numbered_formula("""识别公式主体与右侧编号已落在同一原生文本行的情形。"""line, bbox = candidate- if not line.document_style_anomaly:+ if not line.style_scale_repaired:return Falseparts = _split_trailing_formula_number(line.text)if parts is None:@@ -1450,7 +1450,7 @@ def _is_formula_body_barrier("""识别具有稳定正文排版的行,阻止公式分量吸收正文尾行。"""line, bbox = candidate- if not line.document_style_anomaly:+ if not line.style_scale_repaired:if dominant_body_font is None:return Falseline_height = _line_effective_height(line, bbox)@@ -1547,8 +1547,8 @@ def _is_formula_body_prefix(if abs(bbox[0] - lane.left) > max(3.0, 0.75 * median_height):return Falseif (- not line.document_style_anomaly- and not anchor_line.document_style_anomaly+ not line.style_scale_repaired+ and not anchor_line.style_scale_repaired):return (dominant_body_font is not Nonediff --git a/mineru/model/flash/pdf/line_layout.py b/mineru/model/flash/pdf/line_layout.pyindex 19716a3d..a9e5852a 100644--- a/mineru/model/flash/pdf/line_layout.py+++ b/mineru/model/flash/pdf/line_layout.py@@ -146,13 +146,25 @@ def _line_style_scale(line: _LineItem, local_bbox: BBox) -> float:return max(0.1,line.em_height- if line.document_style_anomaly+ if line.style_scale_repairedand line.em_height > 0else line.effective_heightor (local_bbox[3] - local_bbox[1]),)+def _line_canonical_style_scale(line: _LineItem, local_bbox: BBox) -> float:+ """忽略语义选择标记,直接返回 tight/origin 校准后的字体尺度。"""++ return max(+ 0.1,+ line.em_height+ if line.em_height > 0+ else line.effective_height+ or (local_bbox[3] - local_bbox[1]),+ )++def _line_effective_height(line: _LineItem, local_bbox: BBox) -> float:"""兼容既有布局调用,并统一转发到 canonical 字体尺度。"""diff --git a/mineru/model/flash/pdf/line_merging.py b/mineru/model/flash/pdf/line_merging.pyindex 18d02ea6..3da89883 100644--- a/mineru/model/flash/pdf/line_merging.py+++ b/mineru/model/flash/pdf/line_merging.py@@ -231,8 +231,8 @@ def _overlapping_inline_cluster_pair_is_connected(if (local_page_width is not Noneand (- first_line.document_style_anomaly- or second_line.document_style_anomaly+ first_line.style_scale_repaired+ or second_line.style_scale_repaired)and left_bbox[2] <= 0.5 * local_page_widthand right_bbox[0] >= 0.5 * local_page_width@@ -366,8 +366,8 @@ 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),- document_style_anomaly=any(- line.document_style_anomaly+ style_scale_repaired=any(+ line.style_scale_repairedfor line in ordered_members),inline_math_regions=[@@ -655,8 +655,8 @@ 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),- document_style_anomaly=any(- member.document_style_anomaly+ style_scale_repaired=any(+ member.style_scale_repairedfor member in members),inline_math_regions=[region for member in members for region in member.inline_math_regions],@@ -1004,8 +1004,8 @@ 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),- document_style_anomaly=any(- member.document_style_anomaly+ style_scale_repaired=any(+ member.style_scale_repairedfor member in ordered_members),inline_math_regions=[region for member in ordered_members for region in member.inline_math_regions],diff --git a/mineru/model/flash/pdf/models.py b/mineru/model/flash/pdf/models.pyindex cee5be83..d6baf20d 100644--- a/mineru/model/flash/pdf/models.py+++ b/mineru/model/flash/pdf/models.py@@ -47,7 +47,7 @@ class _LineItem:compact_formula_cluster: bool = Falseformula_candidate_only: bool = Falsestructural_title: bool = False- document_style_anomaly: bool = False+ style_scale_repaired: bool = Falseinline_math_regions: list[BBox] = field(default_factory=list)def __post_init__(self) -> None:@@ -183,6 +183,8 @@ class _PreparedPage:table_bboxes: list[BBox]drawing_lines: list[_AxisLine]fixed_blocks: list[dict[str, Any]]+ canonical_formula_geometry: bool = False+ canonical_formula_source_lines: list[_LineItem] = field(default_factory=list)page_footnote_groups: list[set[int]] = field(default_factory=list)script_lines: list[PDFTextScriptLine] = field(default_factory=list)formula_candidate_lines: list[_LineItem] = field(default_factory=list)@@ -218,7 +220,7 @@ class _DocumentBodyProfile:body_height: floatbody_weight: float | Noneregular_fonts: frozenset[tuple[str, int]]- has_loose_height_anomaly: bool = False+ has_style_scale_repairs: bool = False@dataclass(frozen=True, slots=True)diff --git a/mineru/model/flash/pdf/native_text.py b/mineru/model/flash/pdf/native_text.pyindex a11a72f6..006c3528 100644--- a/mineru/model/flash/pdf/native_text.py+++ b/mineru/model/flash/pdf/native_text.py@@ -535,7 +535,7 @@ def _resplit_native_visual_runs(member.preserve_split_boundary = line.preserve_split_boundarymember.semantic_type = line.semantic_typemember.formula_candidate_only = line.formula_candidate_only- member.document_style_anomaly = line.document_style_anomaly+ member.style_scale_repaired = line.style_scale_repairedoutput.append(member)output.sort(key=lambda item: (diff --git a/mineru/model/flash/pdf/pipeline.py b/mineru/model/flash/pdf/pipeline.pyindex c385520a..69f20720 100644--- a/mineru/model/flash/pdf/pipeline.py+++ b/mineru/model/flash/pdf/pipeline.py@@ -297,6 +297,10 @@ def _analyze_native_document(_classify_page_footnote_trailing_footers(prepared_pages)_classify_isolated_first_page_footer(prepared_pages)document_body_profile = _infer_document_body_profile(prepared_pages)+ canonical_body_profile = _infer_document_body_profile(+ prepared_pages,+ use_canonical_scale=True,+ )if document_body_profile is not None:_classify_deferred_image_footnotes(prepared_pages,@@ -308,7 +312,9 @@ def _analyze_native_document()_classify_document_structural_titles(prepared_pages,- document_body_profile,+ canonical_body_profile,+ legacy_body_profile=document_body_profile,+ document_title_profile=document_title_profile,)finalized_pages = [_finalize_prepared_page(@@ -451,6 +457,19 @@ def _prepare_page_source()+ 1,)+ canonical_formula_source_lines = (+ [+ replace(+ line,+ chars=list(line.chars),+ inline_math_regions=list(line.inline_math_regions),+ )+ for line in remaining_lines+ ]+ if geometry_plan is not None+ and geometry_plan.document_style_anomaly+ else []+ )remaining_lines = _merge_same_baseline_text_lines(remaining_lines,source.page_size,@@ -494,6 +513,7 @@ def _prepare_page_source(+ raster_image_blocks+ vector_formula_blocks),+ canonical_formula_source_lines=canonical_formula_source_lines,script_lines=script_lines,formula_candidate_lines=formula_candidate_lines,)@@ -513,6 +533,79 @@ def _compact_prepared_lines(line.chars.clear()+def _rebuild_canonical_formula_blocks(+ prepared: _PreparedPage,+ excluded_source_indices: set[int],+) -> list[dict[str, Any]]:+ """从容器认领后的未合并行重放 canonical 公式路径,避免 loose 行高改变公式成员顺序。"""++ replay_lines = [+ replace(+ line,+ chars=list(line.chars),+ style_scale_repaired=True,+ inline_math_regions=list(line.inline_math_regions),+ )+ for line in prepared.canonical_formula_source_lines+ if line.source_index not in excluded_source_indices+ ]+ replay_lines = _merge_same_baseline_text_lines(+ replay_lines,+ prepared.page_size,+ prepared.table_bboxes,+ )+ replay_lines = _merge_overlapping_inline_text_clusters(+ replay_lines,+ prepared.page_size,+ prepared.table_bboxes,+ )+ replay_lines = _merge_same_baseline_text_lines(+ replay_lines,+ 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_input = _restore_dense_split_visual_rows(+ replay_lines + formula_candidate_lines,+ prepared.page_size,+ prepared.table_bboxes,+ )+ formula_input = _merge_same_baseline_text_lines(+ formula_input,+ prepared.page_size,+ prepared.table_bboxes,+ )+ blocks, _remaining_lines = _build_formula_like_blocks(+ formula_input,+ prepared.table_bboxes,+ prepared.page_size,+ )+ return blocks+++def _formula_block_inventory(+ blocks: list[dict[str, Any]],+) -> list[tuple[float, float, float, float]]:+ """返回公式重放与正常路径可比较的稳定 bbox 库存。"""++ 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+ )++def _finalize_prepared_page(prepared: _PreparedPage,page_index: int,@@ -536,6 +629,13 @@ 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+ }+ if prepared.canonical_formula_geometry:+ for line in formula_input:+ line.style_scale_repaired = Trueformula_input = _restore_dense_split_visual_rows(formula_input,prepared.page_size,@@ -551,6 +651,28 @@ def _finalize_prepared_page(prepared.table_bboxes,prepared.page_size,)+ 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+ },+ )+ if _formula_block_inventory(+ canonical_formula_blocks,+ ) == _formula_block_inventory(formula_blocks):+ formula_blocks = canonical_formula_blocks+ prepared.canonical_formula_source_lines.clear()+ if prepared.canonical_formula_geometry:+ for line in remaining_lines:+ line.style_scale_repaired = original_style_scale_state.get(+ line.source_index,+ line.style_scale_repaired,+ )fallback_index_blocks, remaining_lines = _extract_index_blocks(remaining_lines,prepared.page_size,diff --git a/mineru/model/flash/pdf/text_blocks.py b/mineru/model/flash/pdf/text_blocks.pyindex 49e269ce..7c7989b6 100644--- a/mineru/model/flash/pdf/text_blocks.py+++ b/mineru/model/flash/pdf/text_blocks.py@@ -709,7 +709,7 @@ def _build_text_blocks(else lane)if (- current[0].document_style_anomaly+ current[0].style_scale_repairedand current[0].split_from_rowand current[0].visual_row_id is not Noneand split_row_counts.get(diff --git a/mineru/model/flash/pdf/titles.py b/mineru/model/flash/pdf/titles.pyindex 4cacd0b6..45b438be 100644--- a/mineru/model/flash/pdf/titles.py+++ b/mineru/model/flash/pdf/titles.py@@ -5,6 +5,7 @@from __future__ import annotationsimport statistics+from collections import Counterfrom dataclasses import replacefrom typing import Literal@@ -37,6 +38,7 @@ from .line_layout import (_font_signatures_share_family,_font_weights_conflict,_infer_text_lanes,+ _line_canonical_style_scale,_line_effective_height,_normalized_font_family,_should_connect_semantic_rows,@@ -164,7 +166,7 @@ def _classify_page_titles()if (document_body_profile is not None- and document_body_profile.has_loose_height_anomaly+ and document_body_profile.has_style_scale_repairs):_demote_non_structural_anomaly_titles(line_geometry)if page_index == 0:@@ -191,6 +193,8 @@ def _demote_non_structural_anomaly_titles(def _infer_document_body_profile(prepared_pages: list[_PreparedPage],+ *,+ use_canonical_scale: bool = False,) -> _DocumentBodyProfile | None:"""按跨页覆盖和累计行宽推断全文正文行高及常规字体集合。"""@@ -217,7 +221,11 @@ def _infer_document_body_profile(if line.angle in {90, 270}else prepared.page_size[0])- height = _line_effective_height(line, local_bbox)+ height = (+ _line_canonical_style_scale(line, local_bbox)+ if use_canonical_scale+ else _line_effective_height(line, local_bbox)+ )normalized_width = max(0.0, local_bbox[2] - local_bbox[0]) / max(0.1,local_page_width,@@ -305,8 +313,8 @@ def _infer_document_body_profile(body_height=max(0.1, body_height),body_weight=body_weight,regular_fonts=regular_fonts,- has_loose_height_anomaly=any(- line.document_style_anomaly+ has_style_scale_repairs=any(+ line.style_scale_repairedfor prepared in prepared_pagesfor line in prepared.remaining_lines),@@ -316,20 +324,133 @@ def _infer_document_body_profile(def _classify_document_structural_titles(prepared_pages: list[_PreparedPage],document_body_profile: _DocumentBodyProfile | None,+ *,+ legacy_body_profile: _DocumentBodyProfile | None,+ document_title_profile: _DocumentTitleProfile | None,) -> None:"""用跨页稳定栏带和段前后转折补齐正文同字号标题。"""if (document_body_profile is None- or not document_body_profile.has_loose_height_anomaly+ or not document_body_profile.has_style_scale_repairs):return+ probe_pages = [+ replace(+ prepared,+ remaining_lines=[+ replace(+ line,+ style_scale_repaired=True,+ structural_title=False,+ )+ for line in prepared.remaining_lines+ ],+ )+ for prepared in prepared_pages+ ]+ _classify_document_structural_title_candidates(+ probe_pages,+ document_body_profile,+ )+ canonical_candidate_sources = {+ (page_index, line.source_index)+ for page_index, prepared in enumerate(probe_pages)+ for line in prepared.remaining_lines+ if line.structural_title+ }+ legacy_title_sources = _collect_legacy_paragraph_title_sources(+ prepared_pages,+ legacy_body_profile,+ document_title_profile,+ )+ body_height = max(0.1, document_body_profile.body_height)+ canonical_style_candidate_pages: dict[+ tuple[str, int, float, int],+ list[int],+ ] = {}+ for page_index, prepared in enumerate(prepared_pages):+ for line in prepared.remaining_lines:+ line_key = (page_index, line.source_index)+ if line_key not in canonical_candidate_sources:+ continue+ local_bbox = _rotate_bbox_to_upright(+ line.source_bbox or line.bbox,+ prepared.page_size,+ line.angle,+ )+ layout_ratio = (+ local_bbox[3] - local_bbox[1]+ ) / body_height+ if (+ line_key in legacy_title_sources+ or layout_ratio >= 1.8+ or not _line_uses_document_regular_font(+ line,+ document_body_profile,+ )+ ):+ line.semantic_type = "paragraph_title"+ line.structural_title = True+ if (+ line_key not in legacy_title_sources+ and layout_ratio >= 1.8+ and (+ style_key := _canonical_title_style_key(+ line,+ )+ )+ is not None+ ):+ canonical_style_candidate_pages.setdefault(+ style_key,+ [],+ ).append(page_index)+ 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 canonical_style_prototypes:+ for prepared in prepared_pages:+ prepared.canonical_formula_geometry = True+ for line in prepared.remaining_lines:+ style_key = _canonical_title_style_key(line)+ if style_key in canonical_style_prototypes:+ line.style_scale_repaired = True+++def _canonical_title_style_key(+ line: _LineItem,+) -> tuple[str, int, float, int] | None:+ """返回 canonical-only 标题向同样式正文传播时使用的稳定键。"""++ if line.font_signature is None or line.em_height <= 0:+ return None+ font_family = _normalized_font_family(line.font_signature)+ if font_family is None:+ return None+ return (+ font_family,+ line.font_signature[1],+ round(line.em_height * 4.0) / 4.0,+ line.angle,+ )+++def _classify_document_structural_title_candidates(+ prepared_pages: list[_PreparedPage],+ document_body_profile: _DocumentBodyProfile,+) -> None:+ """在 canonical 行副本上收集所有满足结构转折的标题候选。"""+body_height = max(0.1, document_body_profile.body_height)strong_candidates: list[- tuple[int, _LineItem, tuple[str, int] | None]+ tuple[int, _LineItem, tuple[str, int] | None, float]] = []start_candidates: list[- tuple[int, _LineItem, tuple[str, int] | None]+ tuple[int, _LineItem, tuple[str, int] | None, float]] = []accepted_anchor_positions: list[tuple[int, int, float, float]@@ -380,7 +501,7 @@ def _classify_document_structural_titles(else prepared.page_size[1])median_height = statistics.median(- _line_effective_height(line, bbox)+ _line_canonical_style_scale(line, bbox)for line, bbox in geometry)lanes = _infer_text_lanes(@@ -425,7 +546,7 @@ def _classify_document_structural_titles(lane_width = max(0.1, lane.right - lane.left)width_ratio = (bbox[2] - bbox[0]) / lane_widthstyle_ratio = (- _line_effective_height(line, bbox)+ _line_canonical_style_scale(line, bbox)/ body_height)left_offset = (bbox[0] - lane.left) / body_height@@ -533,7 +654,12 @@ def _classify_document_structural_titles()):strong_candidates.append(- (page_index, line, family_key),+ (+ page_index,+ line,+ family_key,+ layout_ratio,+ ),)accepted_anchor_positions.append((@@ -557,18 +683,23 @@ def _classify_document_structural_titles()):start_candidates.append(- (page_index, line, family_key),+ (+ page_index,+ line,+ family_key,+ layout_ratio,+ ),)- for _page_index, line, _family_key in strong_candidates:+ for _page_index, line, _family_key, _layout_ratio in strong_candidates:line.semantic_type = "paragraph_title"line.structural_title = Truestrong_families_by_page = {(page_index, family_key)- for page_index, _line, family_key in strong_candidates+ for page_index, _line, family_key, _layout_ratio in strong_candidatesif family_key is not None}- for page_index, line, family_key in start_candidates:+ for page_index, line, family_key, _layout_ratio in start_candidates:if (not _line_uses_document_regular_font(line,@@ -584,6 +715,56 @@ def _classify_document_structural_titles(line.structural_title = True+def _collect_legacy_paragraph_title_sources(+ prepared_pages: list[_PreparedPage],+ document_body_profile: _DocumentBodyProfile | None,+ document_title_profile: _DocumentTitleProfile | None,+) -> set[tuple[int, int]]:+ """在行副本上使用 legacy 尺度收集原本成立的段落标题身份。"""++ if document_body_profile is None:+ return set()+ legacy_profile = replace(+ document_body_profile,+ has_style_scale_repairs=False,+ )+ output: set[tuple[int, int]] = set()+ for page_index, prepared in enumerate(prepared_pages):+ probe_lines = [+ replace(+ line,+ style_scale_repaired=False,+ structural_title=False,+ )+ 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"}+ ]+ _classify_page_titles(+ probe_lines,+ prepared.page_size,+ page_index=page_index,+ container_bboxes=container_bboxes,+ caption_container_bboxes=caption_container_bboxes,+ 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"+ )+ return output++def _classify_body_height_section_titles(lines: list[_LineItem],page_size: tuple[float, float],@@ -1237,7 +1418,7 @@ def _classify_document_title(top_preference_weight = (4.0if document_body_profile is not None- and document_body_profile.has_loose_height_anomaly+ and document_body_profile.has_style_scale_repairselse 1.0)score = (@@ -1381,7 +1562,7 @@ def _classify_additional_document_title_bands(if (document_title_bottom is Noneor document_body_profile is None- or not document_body_profile.has_loose_height_anomaly+ or not document_body_profile.has_style_scale_repairs):return document_title_bottombody_height = max(0.1, document_body_profile.body_height)@@ -1454,7 +1635,7 @@ def _demote_front_matter_non_document_titles(if (document_title_bottom is Noneor document_body_profile is None- or not document_body_profile.has_loose_height_anomaly+ or not document_body_profile.has_style_scale_repairs):returnboundary = max(diff --git a/tests/unittest/test_flash_pdf_char_geometry.py b/tests/unittest/test_flash_pdf_char_geometry.pyindex 8ef8504c..77f60960 100644--- a/tests/unittest/test_flash_pdf_char_geometry.py+++ b/tests/unittest/test_flash_pdf_char_geometry.py@@ -6,6 +6,7 @@ from pathlib import Pathfrom mineru.model.flash.pdf import pipelinefrom mineru.model.flash.pdf.char_geometry import (+ _line_loose_tier_offsets,apply_line_geometry_repairs,build_document_geometry_plan,)@@ -96,15 +97,15 @@ def _merge_geometries(*geometries: PDFPageTextGeometry) -> PDFPageTextGeometry:)-def test_repeated_loose_height_inflation_sets_canonical_em_scale() -> None:- """验证跨页重复的 loose 高度异常按字号与 tight 几何校准行尺度。"""+def test_two_page_repeated_loose_height_inflation_sets_canonical_em_scale() -> None:+ """验证两页内重复的 loose 高度异常即可按字号与 tight 几何校准全文。"""lines_by_page: list[list[_LineItem]] = []geometries: list[PDFPageTextGeometry] = []- for page_index in range(15):+ for page_index in range(2):page_lines = []page_geometries = []- for line_index in range(10):+ for line_index in range(3):baseline = 20.0 + 16.0 * line_indexanomalous = line_index < 2line, geometry = _line_fixture(@@ -140,7 +141,7 @@ def test_repeated_loose_height_inflation_sets_canonical_em_scale() -> None:plan = build_document_geometry_plan(lines_by_page,geometries,- [(300.0, 200.0)] * 15,+ [(300.0, 200.0)] * 2,)for page_index, lines in enumerate(lines_by_page):apply_line_geometry_repairs(@@ -155,6 +156,42 @@ def test_repeated_loose_height_inflation_sets_canonical_em_scale() -> None:assert any(run["style_y_bad"] for run in plan.run_diagnostics)+def test_line_loose_tier_shrinks_repeated_largest_tier_to_second_tier() -> None:+ """验证同行重复最大 loose 档按次档的归一化 ascent/descent 回缩。"""++ offsets = _line_loose_tier_offsets(+ [(8.0, 2.0, 7.0, 10.0)] * 6+ + [(20.0, 4.0, 7.0, 10.0)] * 4,+ 10.0,+ )++ assert offsets == (8.0, 2.0)+++def test_line_loose_tier_preserves_legitimate_mixed_font_sizes() -> None:+ """验证按各自 em 归一化后相同的真实混合字号不会形成异常高度档。"""++ offsets = _line_loose_tier_offsets(+ [(8.0, 2.0, 7.0, 10.0)] * 4+ + [(16.0, 4.0, 14.0, 20.0)] * 4,+ 10.0,+ )++ assert offsets is None+++def test_line_loose_tier_ignores_single_large_outlier() -> None:+ """验证单个 loose 高度离群字符不足以触发整行档位回缩。"""++ offsets = _line_loose_tier_offsets(+ [(8.0, 2.0, 7.0, 10.0)] * 7+ + [(20.0, 4.0, 7.0, 10.0)],+ 10.0,+ )++ assert offsets is None++def test_strong_x_run_repairs_advance_and_contains_tight_bbox() -> None:"""验证强 X 异常 run 按 origin advance 收缩且仍包含 tight。"""diff --git a/tests/unittest/test_flash_pdf_formulas.py b/tests/unittest/test_flash_pdf_formulas.pyindex 00f9a6a8..d171c4e1 100644--- a/tests/unittest/test_flash_pdf_formulas.py+++ b/tests/unittest/test_flash_pdf_formulas.py@@ -120,8 +120,8 @@ def test_single_line_formula_requires_numeric_trailing_marker() -> None:1,effective_height=10.0,)- numbered.document_style_anomaly = True- parenthesized_argument.document_style_anomaly = True+ numbered.style_scale_repaired = True+ parenthesized_argument.style_scale_repaired = Truelane = models._TextLane(left=0.0,right=100.0,diff --git a/tests/unittest/test_flash_pdf_semantics.py b/tests/unittest/test_flash_pdf_semantics.pyindex e96e7268..04545b2e 100644--- a/tests/unittest/test_flash_pdf_semantics.py+++ b/tests/unittest/test_flash_pdf_semantics.py@@ -10,6 +10,10 @@ from typing import Anyfrom mineru.model.flash.pdf.document import PDFDocumentfrom mineru.model.flash.pdf.pipeline import _analyze_native_document+from scripts.review_flash_layout_geometry import (+ _page_bbox_fingerprint,+ _page_fingerprint,+)_PROJECT_ROOT = Path(__file__).parents[2]@@ -19,6 +23,13 @@ _EXPECTATION_PATH = (/ "fixtures"/ "flash_layout_semantic_expectations.json")+_GEOMETRY_MANIFEST_PATH = (+ _PROJECT_ROOT+ / "tests"+ / "fixtures"+ / "flash_layout_geometry_manifest.json"+)+_FROZEN_SOIL_PATH = _PROJECT_ROOT / "demo" / "pdfs" / "中文论文.pdf"_NATURAL_TEXT_TYPES = {"text", "doc_title", "paragraph_title"}@@ -67,6 +78,38 @@ def _pages() -> tuple[tuple[dict[str, Any], ...], ...]:return tuple(tuple(page) for page in pages)+@lru_cache(maxsize=1)+def _frozen_soil_pages() -> tuple[tuple[dict[str, Any], ...], ...]:+ """只解析一次中文论文1,供 canonical 几何兼容性断言复用。"""++ with PDFDocument(str(_FROZEN_SOIL_PATH)) as document:+ pages = _analyze_native_document(document)+ return tuple(tuple(page) for page in pages)+++def test_frozen_soil_paper_keeps_tracked_semantic_and_bbox_gold() -> None:+ """验证无长文档门槛时中文论文1仍逐页保持已有语义与 bbox 指纹。"""++ 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"+ )+ 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"]]++def _typed_texts(block_type: str) -> Counter[tuple[int, str]]:"""按页号和规范文本统计指定类型,保留重复项检测能力。"""diff --git a/tests/unittest/test_flash_pdf_text_blocks.py b/tests/unittest/test_flash_pdf_text_blocks.pyindex ea99a1cf..617974ca 100644--- a/tests/unittest/test_flash_pdf_text_blocks.py+++ b/tests/unittest/test_flash_pdf_text_blocks.py@@ -1886,7 +1886,7 @@ def test_native_typography_separates_loose_height_from_canonical_em() -> None:source_index=0,chars=chars,em_height=10.0,- document_style_anomaly=True,+ style_scale_repaired=True,)native_text._fill_native_typography(line, (100.0, 100.0))