Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: enhance OCR detection by adding support for hybrid text blocks and automatic merging based on OCR line hints
myhloli4611b0b134d8
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.pyindex ae3aea67..aaa2f248 100644--- a/mineru/backend/hybrid/hybrid_analyze.py+++ b/mineru/backend/hybrid/hybrid_analyze.py@@ -53,6 +53,25 @@ OCR_DET_BASE_BATCH_SIZE = 8LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD = 0.8not_extract_list = [item.value for item in NotExtractType]+HYBRID_OCR_DET_TEXT_TYPES = set(not_extract_list) | {+ MineruBlockType.ABSTRACT,+ MineruBlockType.CAPTION,+ MineruBlockType.FOOTNOTE,+ MineruBlockType.DOC_TITLE,+ MineruBlockType.PARAGRAPH_TITLE,+ MineruBlockType.LIST,+ MineruBlockType.INDEX,+ MineruBlockType.ASIDE_TEXT,+ MineruBlockType.PHONETIC,+ MineruBlockType.CHART_CAPTION,+ MineruBlockType.CHART_FOOTNOTE,+ MineruBlockType.CODE_FOOTNOTE,+}+++def _is_hybrid_ocr_det_candidate(block):+ """判断 Hybrid 文本类块是否需要 OCR det 生成行级视觉信息。"""+ return (block.get("type") or block.get("label")) in HYBRID_OCR_DET_TEXT_TYPESdef ocr_classify(pdf_bytes, parse_method: str = 'auto',) -> bool:# 确定OCR设置@@ -71,6 +90,8 @@ def ocr_det(mfd_res,_ocr_enable,batch_ratio: int = 1,+ *,+ fill_text: bool = True,):def _set_temp_pixel_bbox(res, pixel_bbox):res["_normalized_bbox"] = list(res["bbox"])@@ -92,7 +113,7 @@ def ocr_det(ocr_res_list.append([])img_height, img_width = np_image.shape[:2]for res in page_results:- if res['type'] not in not_extract_list:+ if not _is_hybrid_ocr_det_candidate(res):continuex0 = max(0, int(res['bbox'][0] * img_width))y0 = max(0, int(res['bbox'][1] * img_height))@@ -116,7 +137,11 @@ def ocr_det()[0]if ocr_res:ocr_result_list = get_ocr_result_list(- ocr_res, useful_list, _ocr_enable, bgr_image, hybrid_pipeline_model.lang+ ocr_res,+ useful_list,+ _ocr_enable if fill_text else False,+ bgr_image,+ hybrid_pipeline_model.lang,)ocr_res_list[-1].extend(ocr_result_list)@@ -131,7 +156,7 @@ def ocr_det(ocr_res_list.append([])img_height, img_width = np_image.shape[:2]for res in page_results:- if res['type'] not in not_extract_list:+ if not _is_hybrid_ocr_det_candidate(res):continuex0 = max(0, int(res['bbox'][0] * img_width))y0 = max(0, int(res['bbox'][1] * img_height))@@ -200,7 +225,11 @@ def ocr_det(if dt_boxes_final:ocr_res = [box.tolist() if hasattr(box, 'tolist') else box for box in dt_boxes_final]ocr_result_list = get_ocr_result_list(- ocr_res, useful_list, _ocr_enable, bgr_image, hybrid_pipeline_model.lang+ ocr_res,+ useful_list,+ _ocr_enable if fill_text else False,+ bgr_image,+ hybrid_pipeline_model.lang,)ocr_page_res_list.extend(ocr_result_list)return ocr_res_list@@ -283,6 +312,21 @@ def _build_inline_formula_inputs(images_layout_res):return inline_formula_inputs+def _build_formula_mask_inputs(images_layout_res):+ """从 layout 检测结果提取公式框,供 OCR det 规避行内/行间公式区域。"""+ page_formula_masks = []+ for layout_res in images_layout_res:+ page_masks = []+ for res in layout_res:+ if res.get('label') not in ['inline_formula', 'display_formula']:+ continue+ bbox = _formula_item_to_pixel_bbox(res)+ if bbox is not None:+ page_masks.append({"bbox": bbox})+ page_formula_masks.append(page_masks)+ return page_formula_masks++def _normalize_page_size(page_image):"""从PIL或numpy图像中读取页面宽高,供归一化bbox还原为像素bbox。"""if hasattr(page_image, "size"):@@ -509,7 +553,7 @@ def _apply_layout_title_split_for_window(language,batch_ratio,):- """为VLM-OCR路径补跑layout小模型,并只用其doc_title结果拆分VLM标题。"""+ """为VLM-OCR路径补跑layout小模型,拆分标题并追加空文本OCR det sidecar。"""hybrid_model_singleton = HybridModelSingleton()hybrid_pipeline_model = hybrid_model_singleton.get_model(lang=language,@@ -525,6 +569,23 @@ def _apply_layout_title_split_for_window(images_layout_res,[_normalize_page_size(image) for image in images_pil_list],)+ np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]+ ocr_res_list = ocr_det(+ hybrid_pipeline_model,+ np_images,+ model_list,+ _build_formula_mask_inputs(images_layout_res),+ False,+ batch_ratio=batch_ratio,+ fill_text=False,+ )+ _normalize_bbox([[] for _ in images_pil_list], ocr_res_list, images_pil_list)+ model_list[:] = _merge_page_sidecar_items(+ model_list,+ [[] for _ in images_pil_list],+ ocr_res_list,+ keep_ocr_text=False,+ )return hybrid_pipeline_model@@ -556,11 +617,12 @@ def _build_inline_formula_model_item(formula):}-def _build_ocr_text_model_item(ocr_res):+def _build_ocr_text_model_item(ocr_res, keep_text=True):+ """构造 OCR det sidecar;VLM-OCR 路径可只保留空文本行提示。"""return {"type": "ocr_text","bbox": list(ocr_res["bbox"]),- "text": ocr_res.get("text", ""),+ "text": ocr_res.get("text", "") if keep_text else "","score": float(ocr_res.get("score", 0.0)),}@@ -569,6 +631,7 @@ def _merge_page_sidecar_items(model_list,inline_formula_list,ocr_res_list,+ keep_ocr_text=True,):merged_model_list = []for page_model_list, page_inline_formula_list, page_ocr_res_list in zip(@@ -581,7 +644,7 @@ def _merge_page_sidecar_items(if formula.get("bbox") is not None)merged_page_model_list.extend(- _build_ocr_text_model_item(ocr_res)+ _build_ocr_text_model_item(ocr_res, keep_text=keep_ocr_text)for ocr_res in page_ocr_res_listif ocr_res.get("bbox") is not None)diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.pyindex 57faec7b..21555ec2 100644--- a/mineru/backend/hybrid/hybrid_magic_model.py+++ b/mineru/backend/hybrid/hybrid_magic_model.py@@ -26,6 +26,17 @@ not_extract_list = [item.value for item in NotExtractType] + [BlockType.DOC_TITLE,BlockType.PARAGRAPH_TITLE,]+OCR_DET_LINES_KEY = "_ocr_det_lines"+OCR_DET_LINE_BLOCK_TYPES = set(not_extract_list) | {+ BlockType.LIST,+ BlockType.INDEX,+ BlockType.ABSTRACT,+ BlockType.ASIDE_TEXT,+ BlockType.PHONETIC,+ BlockType.CHART_CAPTION,+ BlockType.CHART_FOOTNOTE,+ BlockType.CODE_FOOTNOTE,+}def _copy_raw_text_block_metadata(raw_block_type, block_info, block):@@ -60,39 +71,38 @@ class MagicModel:self.all_spans = []page_text_inline_formula_spans = []- if not _vlm_ocr_enable:- for inline_formula in self.page_inline_formula:- inline_formula["bbox"] = self.cal_real_bbox(inline_formula["bbox"])- inline_formula_latex = inline_formula.pop("latex", "")- if inline_formula_latex:- page_text_inline_formula_spans.append(- {- "bbox": inline_formula["bbox"],- "type": ContentType.INLINE_EQUATION,- "content": inline_formula_latex,- "score": inline_formula["score"],- }- )- for ocr_res in self.page_ocr_res:- ocr_res["bbox"] = self.cal_real_bbox(ocr_res["bbox"])+ for inline_formula in self.page_inline_formula:+ inline_formula["bbox"] = list(self.cal_real_bbox(inline_formula["bbox"]))+ inline_formula_latex = inline_formula.pop("latex", "")+ if inline_formula_latex:page_text_inline_formula_spans.append({- "bbox": ocr_res["bbox"],- "type": ContentType.TEXT,- "content": ocr_res["text"],- "score": ocr_res["score"],+ "bbox": inline_formula["bbox"],+ "type": ContentType.INLINE_EQUATION,+ "content": inline_formula_latex,+ "score": inline_formula["score"],})- if not _ocr_enable:- virtual_block = [0, 0, width, height, None, None, None, "text"]- page_text_inline_formula_spans = txt_spans_extract(- page,- page_text_inline_formula_spans,- page_pil_img,- scale,- [virtual_block],- [],- )+ for ocr_res in self.page_ocr_res:+ ocr_res["bbox"] = list(self.cal_real_bbox(ocr_res["bbox"]))+ page_text_inline_formula_spans.append(+ {+ "bbox": ocr_res["bbox"],+ "type": ContentType.TEXT,+ "content": ocr_res.get("text", ""),+ "score": ocr_res["score"],+ }+ )+ if not _vlm_ocr_enable and not _ocr_enable:+ virtual_block = [0, 0, width, height, None, None, None, "text"]+ page_text_inline_formula_spans = txt_spans_extract(+ page,+ page_text_inline_formula_spans,+ page_pil_img,+ scale,+ [virtual_block],+ [],+ )span_matcher = SpanBlockMatcher(page_text_inline_formula_spans)# 解析每个块@@ -293,6 +303,12 @@ class MagicModel:block["sub_type"] = block_sub_typeif raw_block_type == "table" and "cell_merge" in block_info:block["cell_merge"] = block_info["cell_merge"]+ if _vlm_ocr_enable and self._supports_ocr_det_lines(block_type):+ ocr_det_lines = self._build_ocr_det_lines(+ span_matcher.collect_for_block(block_bbox)+ )+ if ocr_det_lines:+ block[OCR_DET_LINES_KEY] = ocr_det_lines_copy_raw_text_block_metadata(raw_block_type, block_info, block)else:block_spans = span_matcher.collect_for_block(block_bbox)@@ -398,6 +414,20 @@ class MagicModel:return page_blocks, page_inline_formula, page_ocr_res+ @staticmethod+ def _supports_ocr_det_lines(block_type):+ """判断当前块类型是否需要保留 OCR det 行提示供 Hybrid 段落合并使用。"""+ return block_type in OCR_DET_LINE_BLOCK_TYPES++ @staticmethod+ def _build_ocr_det_lines(block_spans):+ """将 OCR det span 聚合成 line,但不改变 VLM-OCR 的 canonical 文本内容。"""+ if not block_spans:+ return []++ hint_block = {"spans": copy.deepcopy(block_spans)}+ return fix_text_block(hint_block).get("lines", [])+def cal_real_bbox(self, bbox):x1, y1, x2, y2 = bboxx_1, y_1, x_2, y_2 = (diff --git a/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py b/mineru/backend/hybrid/hybrid_model_output_to_middle_json.pyindex 23c01b2d..3ed2498e 100644--- a/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py+++ b/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py@@ -13,10 +13,8 @@ from mineru.backend.utils.ocr_det_utils import (get_ch_lite_ocr_det_model,)from mineru.backend.utils.para_block_utils import (- annotate_hybrid_cross_page_merge_prev,build_para_blocks_from_preproc,cleanup_internal_para_block_metadata,- edge_text_line_hints_key,iter_block_spans,merge_para_text_blocks,)@@ -133,10 +131,6 @@ def blocks_to_page_info("page_size": [width, height],"page_idx": page_index,}- if _vlm_ocr_enable:- edge_text_line_hints = _detect_edge_text_line_hints(page_blocks, page_pil_img, scale)- if edge_text_line_hints:- page_info[edge_text_line_hints_key()] = edge_text_line_hintsreturn page_info@@ -256,11 +250,11 @@ def finalize_middle_json(pdf_info_list, hybrid_pipeline_model, _ocr_enable, _vlm_apply_post_ocr(pdf_info_list, hybrid_pipeline_model)build_para_blocks_from_preproc(pdf_info_list)- annotate_hybrid_cross_page_merge_prev(+ merge_para_text_blocks(pdf_info_list,- prefer_edge_line_hints=_vlm_ocr_enable,+ allow_cross_page=True,+ auto_merge_by_det=True,)- merge_para_text_blocks(pdf_info_list, allow_cross_page=True)table_enable = get_table_enable(os.getenv('MINERU_VLM_TABLE_ENABLE', 'True').lower() == 'true')if table_enable:@@ -275,59 +269,6 @@ def finalize_middle_json(pdf_info_list, hybrid_pipeline_model, _ocr_enable, _vlmcleanup_internal_para_block_metadata(pdf_info_list)-def _detect_edge_text_line_hints(page_blocks, page_pil_img, scale):- text_blocks = [block for block in page_blocks if block.get("type") == "text"]- if not text_blocks:- return {}-- edge_blocks = {}- edge_blocks["first"] = text_blocks[0]- edge_blocks["last"] = text_blocks[-1]-- ocr_model = get_ch_lite_ocr_det_model()-- edge_line_hints = {}- for edge_name, block in edge_blocks.items():- line_bboxes = _detect_block_line_bboxes(block, page_pil_img, scale, ocr_model)- if line_bboxes:- edge_line_hints[edge_name] = {- "index": block.get("index"),- "lines": [{"bbox": bbox, "spans": []} for bbox in line_bboxes],- }-- return edge_line_hints---def _detect_block_line_bboxes(block, page_pil_img, scale, ocr_model):- block_bbox = block.get("bbox")- if not block_bbox:- return []-- ocr_det_res, padding = detect_ocr_boxes_from_padded_crop(- block_bbox,- page_pil_img,- scale,- ocr_model=ocr_model,- )- if not ocr_det_res:- return []-- block_x0, block_y0 = block_bbox[0], block_bbox[1]- line_bboxes = []- for box in ocr_det_res:- x_coords = [point[0] - padding for point in box]- y_coords = [point[1] - padding for point in box]- line_bboxes.append([- block_x0 + min(x_coords) / scale,- block_y0 + min(y_coords) / scale,- block_x0 + max(x_coords) / scale,- block_y0 + max(y_coords) / scale,- ])-- line_bboxes.sort(key=lambda bbox: bbox[1])- return line_bboxes--def result_to_middle_json(model_list,images_list,diff --git a/mineru/backend/utils/para_block_utils.py b/mineru/backend/utils/para_block_utils.pyindex b2ae8b5e..1101b6c5 100644--- a/mineru/backend/utils/para_block_utils.py+++ b/mineru/backend/utils/para_block_utils.py@@ -13,7 +13,9 @@ MERGE_BARRIER_TYPES = {BlockType.LIST,}_CROSS_PAGE_MERGE_KEY = "_cross_page_merge_prev"-_EDGE_TEXT_LINE_HINTS_KEY = "_edge_text_line_hints"+OCR_DET_LINES_KEY = "_ocr_det_lines"+MIN_AUTO_MERGE_HORIZONTAL_OVERLAP_RATIO = 0.5+MAX_AUTO_MERGE_VERTICAL_GAP_LINE_RATIO = 3def iter_block_spans(block):@@ -30,7 +32,7 @@ def build_para_blocks_from_preproc(pdf_info_list):page_info["para_blocks"] = copy.deepcopy(page_info.get("preproc_blocks", []))-def merge_para_text_blocks(pdf_info_list, allow_cross_page=False):+def merge_para_text_blocks(pdf_info_list, allow_cross_page=False, auto_merge_by_det=False):ordered_blocks = []for page_info in pdf_info_list:page_idx = page_info.get("page_idx")@@ -41,18 +43,41 @@ def merge_para_text_blocks(pdf_info_list, allow_cross_page=False):current_page_idx, _, current_block = ordered_blocks[current_index]if current_block.get("type") != BlockType.TEXT:continue- if not current_block.get("merge_prev"):- continueif not _block_has_lines(current_block):continue- previous_block = _find_previous_text_block(- ordered_blocks,- current_index,- current_block,- current_page_idx,- allow_cross_page=allow_cross_page,- )+ previous_block = None+ if current_block.get("merge_prev"):+ previous_block = _find_previous_text_block(+ ordered_blocks,+ current_index,+ current_block,+ current_page_idx,+ allow_cross_page=allow_cross_page,+ )++ if previous_block is None and auto_merge_by_det:+ previous_block = _find_previous_text_block(+ ordered_blocks,+ current_index,+ current_block,+ current_page_idx,+ allow_cross_page=allow_cross_page,+ force_cross_page=allow_cross_page,+ )+ if previous_block is not None:+ previous_page_idx, _, previous_text_block = previous_block+ is_cross_page = current_page_idx != previous_page_idx+ if can_auto_merge_text_blocks(+ current_block,+ previous_text_block,+ is_cross_page=is_cross_page,+ ):+ if is_cross_page:+ current_block[_CROSS_PAGE_MERGE_KEY] = True+ else:+ previous_block = None+if previous_block is None:continue@@ -64,113 +89,75 @@ def merge_para_text_blocks(pdf_info_list, allow_cross_page=False):)-def annotate_hybrid_cross_page_merge_prev(pdf_info_list, prefer_edge_line_hints=False):- for page_index in range(1, len(pdf_info_list)):- previous_page_info = pdf_info_list[page_index - 1]- current_page_info = pdf_info_list[page_index]-- previous_text_block = _find_last_page_edge_text_block(previous_page_info)- current_text_block = _find_first_page_edge_text_block(current_page_info)- if previous_text_block is None or current_text_block is None:- continue-- previous_metric_lines = _resolve_metric_lines(- previous_page_info,- previous_text_block,- edge_name="last",- prefer_edge_line_hints=prefer_edge_line_hints,- )- current_metric_lines = _resolve_metric_lines(- current_page_info,- current_text_block,- edge_name="first",- prefer_edge_line_hints=prefer_edge_line_hints,- )- if not previous_metric_lines or not current_metric_lines:- continue-- if can_merge_text_blocks(- current_text_block,- previous_text_block,- current_metric_lines=current_metric_lines,- previous_metric_lines=previous_metric_lines,- ):- current_text_block["merge_prev"] = True- current_text_block[_CROSS_PAGE_MERGE_KEY] = True---def can_merge_text_blocks(current_block, previous_block, current_metric_lines=None, previous_metric_lines=None):+def can_auto_merge_text_blocks(current_block, previous_block, is_cross_page=False):+ """基于 OCR det 行几何和 canonical 文本首尾规则判断 Hybrid text 是否应自动合并。"""current_lines = current_block.get("lines", [])previous_lines = previous_block.get("lines", [])- if not current_lines or not previous_lines:- return False-- current_metric_lines = current_metric_lines or current_lines- previous_metric_lines = previous_metric_lines or previous_lines- if not current_metric_lines or not previous_metric_lines:+ current_metric_lines = _resolve_auto_metric_lines(current_block)+ previous_metric_lines = _resolve_auto_metric_lines(previous_block)+ if not current_lines or not previous_lines or not current_metric_lines or not previous_metric_lines:return Falsefirst_metric_line = current_metric_lines[0]- first_line_height = _line_height(first_metric_line)- if first_line_height <= 0:- return False-- current_bbox_fs = _build_bbox_fs(current_block, current_metric_lines)- if abs(current_bbox_fs[0] - first_metric_line["bbox"][0]) >= first_line_height / 2:- return False-last_metric_line = previous_metric_lines[-1]+ first_line_height = _line_height(first_metric_line)last_line_height = _line_height(last_metric_line)- if last_line_height <= 0:+ if first_line_height <= 0 or last_line_height <= 0:return False+ current_bbox_fs = _build_bbox_fs(current_block, current_metric_lines)previous_bbox_fs = _build_bbox_fs(previous_block, previous_metric_lines)-- first_span = _first_span(current_lines[0])- last_span = _last_span(previous_lines[-1])- if first_span is None or last_span is None:- return False-- first_content = first_span.get("content", "")- last_content = last_span.get("content", "")- if not first_content:+ if abs(current_bbox_fs[0] - first_metric_line["bbox"][0]) >= first_line_height / 2:return False-- current_block_width = current_block["bbox"][2] - current_block["bbox"][0]- previous_block_width = previous_block["bbox"][2] - previous_block["bbox"][0]- min_block_width = min(current_block_width, previous_block_width)- if min_block_width <= 0:+ if abs(previous_bbox_fs[2] - last_metric_line["bbox"][2]) >= last_line_height:return False- if abs(previous_bbox_fs[2] - last_metric_line["bbox"][2]) >= last_line_height:+ first_content = _first_non_empty_content(current_lines)+ last_content = _last_non_empty_content(previous_lines)+ if not first_content or not last_content:return Falseif last_content.endswith(LINE_STOP_FLAG):return False- if abs(current_block_width - previous_block_width) >= min_block_width:- return Falseif first_content[0].isdigit() or first_content[0].isupper():return False- if current_block["bbox"][1] >= previous_block["bbox"][3]:++ current_metric_width = current_bbox_fs[2] - current_bbox_fs[0]+ previous_metric_width = previous_bbox_fs[2] - previous_bbox_fs[0]+ min_metric_width = min(current_metric_width, previous_metric_width)+ if min_metric_width <= 0:+ return False+ if abs(current_metric_width - previous_metric_width) >= min_metric_width:return False+if len(current_metric_lines) <= 1 and len(previous_metric_lines) <= 1:return False-- return True+ return _has_mergeable_block_bbox_relation(+ current_block,+ previous_block,+ current_metric_lines,+ previous_metric_lines,+ is_cross_page,+ )def cleanup_internal_para_block_metadata(pdf_info_list):for page_info in pdf_info_list:- page_info.pop(_EDGE_TEXT_LINE_HINTS_KEY, None)- for block in page_info.get("para_blocks", []):- block.pop(_CROSS_PAGE_MERGE_KEY, None)---def edge_text_line_hints_key():- return _EDGE_TEXT_LINE_HINTS_KEY---def _find_previous_text_block(ordered_blocks, current_index, current_block, current_page_idx, allow_cross_page):- cross_page_allowed = allow_cross_page and current_block.get(_CROSS_PAGE_MERGE_KEY, False)+ for block_key in ["preproc_blocks", "para_blocks", "discarded_blocks"]:+ for block in page_info.get(block_key, []):+ _cleanup_block_internal_metadata(block)+++def _find_previous_text_block(+ ordered_blocks,+ current_index,+ current_block,+ current_page_idx,+ allow_cross_page,+ force_cross_page=False,+):+ cross_page_allowed = allow_cross_page and (+ force_cross_page or current_block.get(_CROSS_PAGE_MERGE_KEY, False)+ )for previous_index in range(current_index - 1, -1, -1):previous_page_idx, _, previous_block = ordered_blocks[previous_index]@@ -187,34 +174,9 @@ def _find_previous_text_block(ordered_blocks, current_index, current_block, currreturn None-def _find_first_page_edge_text_block(page_info):- for block in page_info.get("para_blocks", []):- block_type = block.get("type")- if block_type in MERGE_BARRIER_TYPES:- return None- if block_type == BlockType.TEXT and _block_has_lines(block):- return block- return None---def _find_last_page_edge_text_block(page_info):- for block in reversed(page_info.get("para_blocks", [])):- block_type = block.get("type")- if block_type in MERGE_BARRIER_TYPES:- return None- if block_type == BlockType.TEXT and _block_has_lines(block):- return block- return None---def _resolve_metric_lines(page_info, block, edge_name, prefer_edge_line_hints):- if prefer_edge_line_hints:- edge_line_hints = page_info.get(_EDGE_TEXT_LINE_HINTS_KEY, {})- edge_hint = edge_line_hints.get(edge_name)- if edge_hint and edge_hint.get("index") == block.get("index"):- return edge_hint.get("lines", [])- return []- return block.get("lines", [])+def _resolve_auto_metric_lines(block):+ """优先使用 OCR det 行提示;没有提示时退回 block 自身 lines。"""+ return block.get(OCR_DET_LINES_KEY) or block.get("lines", [])def _merge_text_block(current_block, previous_block, is_cross_page):@@ -224,7 +186,12 @@ def _merge_text_block(current_block, previous_block, is_cross_page):span[SplitFlag.CROSS_PAGE] = Trueprevious_block.setdefault("lines", []).extend(current_block.get("lines", []))+ if current_block.get(OCR_DET_LINES_KEY):+ previous_block.setdefault(OCR_DET_LINES_KEY, []).extend(+ current_block.get(OCR_DET_LINES_KEY, [])+ )current_block["lines"] = []+ current_block[OCR_DET_LINES_KEY] = []current_block[SplitFlag.LINES_DELETED] = True@@ -250,11 +217,70 @@ def _block_has_lines(block):return any(line.get("spans") for line in block.get("lines", []))-def _first_span(line):- spans = line.get("spans", [])- return spans[0] if spans else None+def _first_non_empty_content(lines):+ """从行列表中提取第一个非空 span 文本,用于段落起始字符规则判断。"""+ for line in lines:+ for span in line.get("spans", []):+ content = span.get("content", "")+ if content:+ return content+ return ""+++def _last_non_empty_content(lines):+ """从行列表中提取最后一个非空 span 文本,用于段落结尾字符规则判断。"""+ for line in reversed(lines):+ for span in reversed(line.get("spans", [])):+ content = span.get("content", "")+ if content:+ return content+ return ""+++def _horizontal_projection_overlap_ratio(bbox1, bbox2):+ """计算两个 block 在水平方向投影的重叠比例,辅助判断是否同栏同流。"""+ x_left = max(bbox1[0], bbox2[0])+ x_right = min(bbox1[2], bbox2[2])+ overlap = max(0, x_right - x_left)+ min_width = min(bbox1[2] - bbox1[0], bbox2[2] - bbox2[0])+ if min_width <= 0:+ return 0+ return overlap / min_width-def _last_span(line):- spans = line.get("spans", [])- return spans[-1] if spans else None+def _has_mergeable_block_bbox_relation(+ current_block,+ previous_block,+ current_metric_lines,+ previous_metric_lines,+ is_cross_page,+):+ """校验两个 text block 的 bbox 是否处于同一阅读流,避免跨栏或跨标题误合并。"""+ if is_cross_page:+ return current_block["bbox"][1] < previous_block["bbox"][3]++ if current_block["bbox"][1] < previous_block["bbox"][1]:+ return False+ if (+ _horizontal_projection_overlap_ratio(current_block["bbox"], previous_block["bbox"])+ < MIN_AUTO_MERGE_HORIZONTAL_OVERLAP_RATIO+ ):+ return False++ vertical_gap = current_block["bbox"][1] - previous_block["bbox"][3]+ if vertical_gap <= 0:+ return True++ max_line_height = max(+ _line_height(current_metric_lines[0]),+ _line_height(previous_metric_lines[-1]),+ )+ return vertical_gap <= max_line_height * MAX_AUTO_MERGE_VERTICAL_GAP_LINE_RATIO+++def _cleanup_block_internal_metadata(block):+ """递归清理只供 Hybrid 内部段落合并使用的临时字段。"""+ block.pop(_CROSS_PAGE_MERGE_KEY, None)+ block.pop(OCR_DET_LINES_KEY, None)+ for sub_block in block.get("blocks", []):+ _cleanup_block_internal_metadata(sub_block)