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 cell matching by adding token extraction and splitting logic
myhloli75d1a48a1965
diff --git a/mineru/model/table/rec/unet_table/utils_table_recover.py b/mineru/model/table/rec/unet_table/utils_table_recover.pyindex 795ece60..b9fb5eaa 100644--- a/mineru/model/table/rec/unet_table/utils_table_recover.py+++ b/mineru/model/table/rec/unet_table/utils_table_recover.py@@ -1,4 +1,5 @@# Copyright (c) Opendatalab. All rights reserved.+import refrom typing import Any, Dict, List, Union, Tupleimport numpy as np@@ -203,6 +204,214 @@ def _pred_boxes_to_array(pred_bboxes: np.ndarray) -> np.ndarray:)+_TABLE_CELL_TOKEN_RE = re.compile(+ r"""+ \d{4}[-/]\d{1,2}[-/]\d{1,2}+ |[-+]?\d{1,3}(?:,\d{3})+(?:\.\d{2})?%?+ |[-+]?\d+(?:\.\d+)?%?+ |[A-Za-z]++ |[\u4e00-\u9fff]++ """,+ re.VERBOSE,+)+++def _char_visual_weight(char: str) -> float:+ """按字符视觉宽度估算拆分位置,避免简单按字符数切分造成明显偏移。"""+ if "\u4e00" <= char <= "\u9fff":+ return 1.8+ if char.isdigit() or char.isalpha():+ return 1.0+ if char.isspace():+ return 0.35+ if char in {",", ".", "-", "+", "%", "/", ":", ";", "'", '"'}:+ return 0.45+ return 0.8+++def _intersect_box(box1: np.ndarray, box2: np.ndarray) -> List[float]:+ """生成 OCR 子框与目标 cell 的交集框,作为拆分后伪 OCR 的 bbox。"""+ x0 = max(float(box1[0]), float(box2[0]))+ y0 = max(float(box1[1]), float(box2[1]))+ x1 = min(float(box1[2]), float(box2[2]))+ y1 = min(float(box1[3]), float(box2[3]))+ if x1 <= x0:+ x0, x1 = float(box2[0]), float(box2[2])+ if y1 <= y0:+ y0, y1 = float(box1[1]), float(box1[3])+ return [x0, y0, x1, y1]+++def _make_split_ocr_result(gt_box: List[Union[Any, str]], bbox: List[float], text: str):+ """复制原 OCR 结果,只替换 bbox 和文本,保持 score 等后续字段不变。"""+ split_result = list(gt_box)+ split_result[0] = box_4_1_poly_to_box_4_2(bbox)+ split_result[1] = text+ return split_result+++def _extract_cell_tokens(text: str, cell_count: int) -> List[str]:+ """优先用金额、日期、百分比和短 token 拆分跨格文本。"""+ stripped_text = text.strip()+ if not stripped_text:+ return []++ matches = list(_TABLE_CELL_TOKEN_RE.finditer(stripped_text))+ tokens = [match.group(0) for match in matches]+ if len(tokens) != cell_count:+ return []++ covered = "".join(tokens)+ uncovered = _TABLE_CELL_TOKEN_RE.sub("", stripped_text)+ if covered and not uncovered.strip():+ return tokens+ return []+++def _split_text_by_cell_boundaries(+ text: str,+ ocr_box: np.ndarray,+ candidate_boxes: List[np.ndarray],+) -> List[str]:+ """按 cell 边界在 OCR 框中的相对位置,结合字符宽度估算文本切点。"""+ stripped_text = text.strip()+ if len(stripped_text) < len(candidate_boxes):+ return []++ ocr_width = float(ocr_box[2] - ocr_box[0])+ if ocr_width <= 0:+ return []++ weights = [_char_visual_weight(char) for char in stripped_text]+ total_weight = sum(weights)+ if total_weight <= 0:+ return []++ cumulative_weights = np.cumsum(weights)+ split_indices = []+ previous_idx = 0+ for left_box, right_box in zip(candidate_boxes, candidate_boxes[1:]):+ boundary_x = (float(left_box[2]) + float(right_box[0])) / 2+ ratio = (boundary_x - float(ocr_box[0])) / ocr_width+ target_weight = total_weight * min(max(ratio, 0.0), 1.0)+ split_idx = int(np.searchsorted(cumulative_weights, target_weight, side="left") + 1)++ remaining_boundaries = len(candidate_boxes) - len(split_indices) - 1+ min_idx = previous_idx + 1+ max_idx = len(stripped_text) - remaining_boundaries+ split_idx = min(max(split_idx, min_idx), max_idx)+ if split_idx <= previous_idx:+ return []+ split_indices.append(split_idx)+ previous_idx = split_idx++ segments = []+ start = 0+ for split_idx in split_indices + [len(stripped_text)]:+ segment = stripped_text[start:split_idx].strip()+ if not segment:+ return []+ segments.append(segment)+ start = split_idx+ return segments+++def _same_row_adjacent_cells(candidate_boxes: List[np.ndarray]) -> bool:+ """确认候选 cell 位于同一行且横向相邻,避免拆分跨行或非相邻文本。"""+ if len(candidate_boxes) < 2:+ return False++ for left_box, right_box in zip(candidate_boxes, candidate_boxes[1:]):+ y_overlap = min(float(left_box[3]), float(right_box[3])) - max(+ float(left_box[1]), float(right_box[1])+ )+ min_height = min(+ float(left_box[3] - left_box[1]),+ float(right_box[3] - right_box[1]),+ )+ if min_height <= 0 or y_overlap / min_height < 0.6:+ return False++ gap = float(right_box[0] - left_box[2])+ min_width = min(+ float(left_box[2] - left_box[0]),+ float(right_box[2] - right_box[0]),+ )+ if abs(gap) > max(2.0, min_width * 0.3):+ return False+ return True+++def _split_cross_cell_ocr_result(+ gt_box: List[Union[Any, str]],+ ocr_box: np.ndarray,+ pred_boxes: np.ndarray,+ candidate_indices: np.ndarray,+ allow_weighted_split: bool = True,+) -> List[Tuple[int, List[Union[Any, str]]]]:+ """把横跨同一行相邻 cell 的 OCR 结果拆成多个伪 OCR 结果。"""+ if len(candidate_indices) < 2:+ return []++ sorted_indices = sorted(candidate_indices.tolist(), key=lambda idx: pred_boxes[idx][0])+ candidate_boxes = [pred_boxes[idx] for idx in sorted_indices]+ if not _same_row_adjacent_cells(candidate_boxes):+ return []++ text = str(gt_box[1])+ segments = _extract_cell_tokens(text, len(sorted_indices))+ if not segments and allow_weighted_split:+ segments = _split_text_by_cell_boundaries(text, ocr_box, candidate_boxes)+ if len(segments) != len(sorted_indices):+ return []++ split_results = []+ for cell_idx, cell_box, segment in zip(sorted_indices, candidate_boxes, segments):+ bbox = _intersect_box(ocr_box, cell_box)+ split_results.append((cell_idx, _make_split_ocr_result(gt_box, bbox, segment)))+ return split_results+++def _select_clear_best_cell(+ candidate_indices: np.ndarray,+ coverage_scores: np.ndarray,+ iou_scores: np.ndarray,+ ocr_box: np.ndarray,+ pred_boxes: np.ndarray,+) -> Union[int, None]:+ """当某个 cell 明显优于其他候选时直接归属,避免不必要拆分。"""+ if len(candidate_indices) == 1:+ return int(candidate_indices[0])++ ranked = sorted(+ candidate_indices.tolist(),+ key=lambda idx: (coverage_scores[idx], iou_scores[idx]),+ reverse=True,+ )+ best_idx = ranked[0]+ second_idx = ranked[1]+ best_coverage = float(coverage_scores[best_idx])+ second_coverage = float(coverage_scores[second_idx])++ center_x = (float(ocr_box[0]) + float(ocr_box[2])) / 2+ center_y = (float(ocr_box[1]) + float(ocr_box[3])) / 2+ center_hits = [+ idx+ for idx in candidate_indices.tolist()+ if (+ float(pred_boxes[idx][0]) <= center_x < float(pred_boxes[idx][2])+ and float(pred_boxes[idx][1]) <= center_y <= float(pred_boxes[idx][3])+ )+ ]+ if len(center_hits) == 1 and center_hits[0] == best_idx:+ if best_coverage >= 0.55 and best_coverage - second_coverage >= 0.15:+ return int(best_idx)++ if best_coverage >= 0.65 and best_coverage - second_coverage >= 0.2:+ return int(best_idx)+ return None++def match_ocr_cell(dt_rec_boxes: List[List[Union[Any, str]]], pred_bboxes: np.ndarray):""":param dt_rec_boxes: [[(4.2), text, score]]@@ -229,10 +438,16 @@ def match_ocr_cell(dt_rec_boxes: List[List[Union[Any, str]]], pred_bboxes: np.ndinter_y1 = np.maximum(ocr[..., 1], pred[..., 1])inter_x2 = np.minimum(ocr[..., 2], pred[..., 2])inter_y2 = np.minimum(ocr[..., 3], pred[..., 3])- inter_area = np.maximum(0, inter_x2 - inter_x1) * np.maximum(0, inter_y2 - inter_y1)+ inter_width = np.maximum(0, inter_x2 - inter_x1)+ inter_height = np.maximum(0, inter_y2 - inter_y1)+ inter_area = inter_width * inter_height- ocr_area = (ocr[..., 2] - ocr[..., 0]) * (ocr[..., 3] - ocr[..., 1])- pred_area = (pred[..., 2] - pred[..., 0]) * (pred[..., 3] - pred[..., 1])+ ocr_width = ocr[..., 2] - ocr[..., 0]+ ocr_height = ocr[..., 3] - ocr[..., 1]+ pred_width = pred[..., 2] - pred[..., 0]+ pred_height = pred[..., 3] - pred[..., 1]+ ocr_area = ocr_width * ocr_height+ pred_area = pred_width * pred_height# 等价实现 is_box_contained(ocr_box, pred_box, 0.6) == 1。ocr_outside_ratio = np.divide(@@ -253,16 +468,72 @@ def match_ocr_cell(dt_rec_boxes: List[List[Union[Any, str]]], pred_bboxes: np.nd)iou[no_intersection] = 0.0matched_mask = contained | (iou > 0.8)+ coverage = np.divide(+ inter_area,+ ocr_area,+ out=np.zeros_like(inter_area, dtype=np.float64),+ where=ocr_area > 0,+ )+ # 低覆盖率横向长 OCR 需要按投影找同一行候选。这里复用上面已经算出的交集矩阵,+ # 避免每个 unmatched OCR 再用 Python 循环扫描所有 cell。+ projection_y_ratio = np.divide(+ inter_height,+ ocr_height,+ out=np.zeros_like(inter_height, dtype=np.float64),+ where=ocr_height > 0,+ )+ projection_x_ratio = np.divide(+ inter_width,+ pred_width,+ out=np.zeros_like(inter_width, dtype=np.float64),+ where=pred_width > 0,+ )+ projection_mask = intersects & (projection_y_ratio >= 0.6) & (projection_x_ratio >= 0.25)matched = {}not_match_orc_boxes = []for i, gt_box in enumerate(dt_rec_boxes):matched_indices = np.flatnonzero(matched_mask[i])- for j in matched_indices:- matched.setdefault(int(j), []).append(gt_box)- not_match_orc_boxes.extend(- [gt_box] * int(pred_boxes.shape[0] - matched_indices.size)+ if len(matched_indices) == 0:+ projection_indices = np.flatnonzero(projection_mask[i])+ split_results = _split_cross_cell_ocr_result(+ gt_box,+ ocr_boxes[i],+ pred_boxes,+ projection_indices,+ allow_weighted_split=False,+ )+ if split_results:+ for cell_idx, split_gt_box in split_results:+ matched.setdefault(cell_idx, []).append(split_gt_box)+ continue+ not_match_orc_boxes.append(gt_box)+ continue++ best_cell_idx = _select_clear_best_cell(+ matched_indices,+ coverage[i],+ iou[i],+ ocr_boxes[i],+ pred_boxes,+ )+ if best_cell_idx is not None:+ matched.setdefault(best_cell_idx, []).append(gt_box)+ continue++ split_results = _split_cross_cell_ocr_result(+ gt_box,+ ocr_boxes[i],+ pred_boxes,+ matched_indices,)+ if split_results:+ for cell_idx, split_gt_box in split_results:+ matched.setdefault(cell_idx, []).append(split_gt_box)+ continue++ # 无法确定归属时不要把同一 OCR 重复塞进多个 cell,交给空 cell 裁剪 OCR 兜底。+ not_match_orc_boxes.append(gt_box)return matched, not_match_orc_boxes