Skip to content

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

feat: enhance OCR processing with blank cell filtering and batch detection improvements

myhlolie8736be860bf
diff --git a/mineru/model/table/cls/mineru_table_ori_cls.py b/mineru/model/table/cls/mineru_table_ori_cls.py
index cd01da7e..17d1b828 100644
--- a/mineru/model/table/cls/mineru_table_ori_cls.py
+++ b/mineru/model/table/cls/mineru_table_ori_cls.py
@@ -1,10 +1,13 @@
# Copyright (c) Opendatalab. All rights reserved.
-from PIL import Image
from collections import defaultdict
+import inspect
from typing import List, Dict
+
import cv2
import numpy as np
+from loguru import logger
+from PIL import Image
# 旋转候选门控回到旧规则,先尽量召回疑似旋转表,再由 OCR rec 评分决定最终角度。
@@ -15,7 +18,7 @@ ROTATED_TEXT_MIN_BOXES = 3
ORIENTATION_SCORE_MAX_SAMPLE_BOXES = 18
ORIENTATION_SCORE_MIN_VALID_RESULTS = 5
ORIENTATION_ZERO_SCORE_PRIORITY_THRESHOLD = 0.9
-ORIENTATION_SCORE_TIE_THRESHOLD = 0.1
+ORIENTATION_SCORE_TIE_THRESHOLD = 0.08
ORIENTATION_SCORE_LABELS = ("0", "90", "270")
@@ -127,12 +130,14 @@ class MineruTableOrientationClsModel:
return None
return img[ymin:ymax, xmin:xmax].copy()
- def _build_orientation_score_task(self, label: str, img_bgr: np.ndarray) -> Dict:
- """为单个角度构造评分任务,只做 det、抽样和切图,不执行 rec。"""
- det_ocr_res = self.ocr_engine.ocr(img_bgr, rec=False)
- det_res = det_ocr_res[0] if det_ocr_res else None
- sampled_boxes = self._sample_det_boxes(det_res)
-
+ def _build_orientation_score_task_from_det_boxes(
+ self,
+ label: str,
+ img_bgr: np.ndarray,
+ det_boxes,
+ ) -> Dict:
+ """根据已有 OCR det 框构造评分任务,复用门控检测结果并统一裁图逻辑。"""
+ sampled_boxes = self._sample_det_boxes(det_boxes)
img_crop_list = []
for box in sampled_boxes:
crop_img = self._crop_image_without_text_rotation(img_bgr, box)
@@ -147,6 +152,12 @@ class MineruTableOrientationClsModel:
"crop_end": len(img_crop_list),
}
+ def _build_orientation_score_task(self, label: str, img_bgr: np.ndarray) -> Dict:
+ """为单个角度构造评分任务,只做 det、抽样和切图,不执行 rec。"""
+ det_ocr_res = self.ocr_engine.ocr(img_bgr, rec=False)
+ det_res = det_ocr_res[0] if det_ocr_res else None
+ return self._build_orientation_score_task_from_det_boxes(label, img_bgr, det_res)
+
def _build_orientation_score_tasks(self, img_bgr: np.ndarray) -> List[Dict]:
"""为一张表构造 0/90/270 三个角度的评分任务。"""
tasks = []
@@ -180,12 +191,33 @@ class MineruTableOrientationClsModel:
score_by_label = {}
rec_res = rec_res or []
for task in tasks:
+ if "score" in task:
+ score_by_label[task["label"]] = task["score"]
+ continue
crop_start = task.get("crop_start", 0)
crop_end = task.get("crop_end", crop_start + task.get("crop_count", 0))
task_rec_res = rec_res[crop_start:crop_end]
score_by_label[task["label"]] = self._score_rec_results(task_rec_res)
return score_by_label
+ @staticmethod
+ def _debug_log_orientation_rec_scores(
+ table_index: int,
+ score_by_label: Dict[str, tuple[float, int, int]],
+ ) -> None:
+ """输出单张表格各旋转候选的 OCR-rec 分数,便于排查误旋转。"""
+ score_parts = []
+ for label in ORIENTATION_SCORE_LABELS:
+ score, valid_count, char_count = score_by_label.get(label, (0.0, 0, 0))
+ score_parts.append(
+ f"{label} score={float(score):.4f} "
+ f"valid_count={valid_count} char_count={char_count}"
+ )
+ logger.debug(
+ f"Table orientation rec scores table_index={table_index}: "
+ f"{'; '.join(score_parts)}"
+ )
+
def _score_rotation_candidate_by_ocr(self, img_bgr: np.ndarray) -> tuple[float, int, int]:
"""对单个候选角度执行 OCR det+抽样 rec,返回平均置信度、有效文本数和字符数。"""
task = self._build_orientation_score_task("", img_bgr)
@@ -225,6 +257,7 @@ class MineruTableOrientationClsModel:
rotated_img = self._rotate_image_by_label(img_bgr, label)
score_by_label[label] = self._score_rotation_candidate_by_ocr(rotated_img)
+ self._debug_log_orientation_rec_scores(-1, score_by_label)
return self._select_rotation_label_by_scores(score_by_label)
@classmethod
@@ -254,6 +287,28 @@ class MineruTableOrientationClsModel:
)
return resolution_groups
+ @classmethod
+ def _collect_portrait_images(cls, imgs: List[Dict]) -> list[Dict]:
+ """扁平收集当前需要方向评分的竖版表格图,保持本地既有候选边界。"""
+ portrait_imgs = []
+ for index, img in enumerate(imgs):
+ bgr_img = cls._to_bgr_table_image(img)
+ img_height, img_width = bgr_img.shape[:2]
+ if img_height <= 0 or img_width <= 0:
+ continue
+
+ img_aspect_ratio = img_height / img_width
+ if img_aspect_ratio <= 1.2:
+ continue
+
+ portrait_imgs.append(
+ {
+ "index": index,
+ "table_img_bgr": bgr_img,
+ }
+ )
+ return portrait_imgs
+
@classmethod
def _pad_group_images(
cls,
@@ -275,51 +330,146 @@ class MineruTableOrientationClsModel:
batch_images.append(padded_img)
return batch_images
+ def _batch_detect_text_boxes(
+ self,
+ img_list: list[np.ndarray],
+ det_batch_size: int,
+ tqdm_enable: bool = False,
+ tqdm_desc: str = "OCR-det Predict",
+ progress_bar=None,
+ ):
+ """统一调用 OCR detector batch_predict,并兼容不支持进度参数的测试替身。"""
+ if not img_list:
+ return []
+
+ max_batch_size = max(1, min(len(img_list), int(det_batch_size)))
+ batch_predict = self.ocr_engine.text_detector.batch_predict
+
+ progress_kwargs = {}
+ try:
+ signature = inspect.signature(batch_predict)
+ params = signature.parameters
+ except (TypeError, ValueError):
+ params = {}
+ accepts_var_kwargs = any(
+ param.kind == inspect.Parameter.VAR_KEYWORD
+ for param in params.values()
+ )
+
+ if "tqdm_enable" in params or accepts_var_kwargs:
+ progress_kwargs["tqdm_enable"] = tqdm_enable
+ if "tqdm_desc" in params or accepts_var_kwargs:
+ progress_kwargs["tqdm_desc"] = tqdm_desc
+ if "tqdm_progress_bar" in params or accepts_var_kwargs:
+ progress_kwargs["tqdm_progress_bar"] = progress_bar
+
+ batch_results = batch_predict(img_list, max_batch_size, **progress_kwargs)
+
+ if progress_bar is not None and "tqdm_progress_bar" not in progress_kwargs:
+ progress_bar.update(len(img_list))
+
+ return batch_results
+
def _detect_rotation_candidates(
self,
- resolution_groups: Dict[tuple[int, int], list[Dict]],
+ portrait_imgs: list[Dict],
det_batch_size: int,
- resolution_group_stride: int,
+ tqdm_enable: bool = False,
+ tqdm_desc: str = "Table orientation",
tqdm_progress_bar=None,
) -> list[Dict]:
"""对竖版表格批量做 OCR det,并筛选需要进入多角度评分的候选。"""
rotated_imgs = []
- for _group_key, group_imgs in resolution_groups.items():
- batch_images = self._pad_group_images(group_imgs, resolution_group_stride)
- batch_results = self.ocr_engine.text_detector.batch_predict(
- batch_images,
- max(1, min(len(batch_images), det_batch_size)),
- )
+ batch_images = [img_info["table_img_bgr"] for img_info in portrait_imgs]
+ batch_results = self._batch_detect_text_boxes(
+ batch_images,
+ det_batch_size,
+ tqdm_enable=tqdm_enable,
+ tqdm_desc=f"{tqdm_desc} det",
+ progress_bar=tqdm_progress_bar,
+ )
- for img_info, (dt_boxes, _elapse) in zip(group_imgs, batch_results):
- if self._is_rotation_candidate_by_det_boxes(dt_boxes):
- rotated_imgs.append(img_info)
- if tqdm_progress_bar is not None:
- tqdm_progress_bar.update(len(batch_images))
+ for img_info, (dt_boxes, _elapse) in zip(portrait_imgs, batch_results):
+ if not self._is_rotation_candidate_by_det_boxes(dt_boxes):
+ continue
+ candidate_info = dict(img_info)
+ candidate_info["gate_det_boxes"] = dt_boxes
+ rotated_imgs.append(candidate_info)
return rotated_imgs
+ @staticmethod
+ def _add_score_task_crops(task: Dict, all_crop_imgs: list[np.ndarray]) -> None:
+ """将有效评分任务加入 OCR-rec 输入,不足阈值的任务直接记为 0 分。"""
+ if task["crop_count"] < ORIENTATION_SCORE_MIN_VALID_RESULTS:
+ task["score"] = (0.0, 0, 0)
+ task["crop_start"] = len(all_crop_imgs)
+ task["crop_end"] = len(all_crop_imgs)
+ return
+
+ crop_start = len(all_crop_imgs)
+ all_crop_imgs.extend(task["crops"])
+ crop_end = len(all_crop_imgs)
+ task["crop_start"] = crop_start
+ task["crop_end"] = crop_end
+
def _build_score_tasks_for_candidates(
self,
rotated_imgs: list[Dict],
+ det_batch_size: int,
) -> tuple[list[tuple[Dict, list[Dict]]], list[np.ndarray]]:
"""为所有旋转候选构造三角度评分任务,并汇总成一次 OCR rec 输入。"""
img_score_tasks = []
all_crop_imgs = []
+ score_det_images = []
+ score_det_tasks = []
+
for img_info in rotated_imgs:
- tasks = self._build_orientation_score_tasks(img_info["table_img_bgr"])
- for task in tasks:
- crop_start = len(all_crop_imgs)
- all_crop_imgs.extend(task["crops"])
- crop_end = len(all_crop_imgs)
- task["crop_start"] = crop_start
- task["crop_end"] = crop_end
+ table_img_bgr = img_info["table_img_bgr"]
+ tasks = [
+ self._build_orientation_score_task_from_det_boxes(
+ "0",
+ table_img_bgr,
+ img_info.get("gate_det_boxes"),
+ )
+ ]
+ for label in ("90", "270"):
+ rotated_img = self._rotate_image_by_label(table_img_bgr, label)
+ task = {
+ "label": label,
+ "rotated_img_bgr": rotated_img,
+ "crops": [],
+ "crop_count": 0,
+ "crop_start": 0,
+ "crop_end": 0,
+ }
+ tasks.append(task)
+ score_det_images.append(rotated_img)
+ score_det_tasks.append(task)
img_score_tasks.append((img_info, tasks))
+
+ score_det_results = self._batch_detect_text_boxes(
+ score_det_images,
+ det_batch_size,
+ )
+ for task, (dt_boxes, _elapse) in zip(score_det_tasks, score_det_results):
+ score_task = self._build_orientation_score_task_from_det_boxes(
+ task["label"],
+ task["rotated_img_bgr"],
+ dt_boxes,
+ )
+ task.update(score_task)
+ task.pop("rotated_img_bgr", None)
+
+ for _img_info, tasks in img_score_tasks:
+ for task in tasks:
+ self._add_score_task_crops(task, all_crop_imgs)
return img_score_tasks, all_crop_imgs
def _recognize_orientation_crops(
self,
all_crop_imgs: list[np.ndarray],
tqdm_enable: bool = False,
+ tqdm_desc: str = "Table orientation",
tqdm_progress_bar=None,
) -> list:
"""对所有候选角度 crop 合并执行 OCR rec,返回可按 slice 回填的结果。"""
@@ -330,8 +480,8 @@ class MineruTableOrientationClsModel:
all_crop_imgs,
det=False,
rec=True,
- tqdm_enable=tqdm_enable,
- tqdm_desc="Table orientation OCR-rec",
+ tqdm_enable=tqdm_enable and tqdm_progress_bar is None,
+ tqdm_desc=f"{tqdm_desc} rec",
tqdm_progress_bar=tqdm_progress_bar,
)
return rec_ocr_res[0] if rec_ocr_res else []
@@ -339,7 +489,9 @@ class MineruTableOrientationClsModel:
def _score_rotation_candidates(
self,
rotated_imgs: list[Dict],
+ det_batch_size: int,
tqdm_enable: bool = False,
+ tqdm_desc: str = "Table orientation",
tqdm_progress_bar=None,
) -> Dict[int, str]:
"""批量评分旋转候选,并返回原始表格下标到最终角度标签的映射。"""
@@ -348,16 +500,19 @@ class MineruTableOrientationClsModel:
label_by_index = {}
img_score_tasks, all_crop_imgs = self._build_score_tasks_for_candidates(
- rotated_imgs
+ rotated_imgs,
+ det_batch_size,
)
rec_res = self._recognize_orientation_crops(
all_crop_imgs,
tqdm_enable=tqdm_enable,
+ tqdm_desc=tqdm_desc,
tqdm_progress_bar=tqdm_progress_bar,
)
for img_info, tasks in img_score_tasks:
score_by_label = self._score_orientation_tasks_with_rec(tasks, rec_res)
+ self._debug_log_orientation_rec_scores(img_info["index"], score_by_label)
label_by_index[img_info["index"]] = self._select_rotation_label_by_scores(
score_by_label
)
@@ -368,26 +523,26 @@ class MineruTableOrientationClsModel:
imgs: List[Dict],
det_batch_size: int,
tqdm_enable: bool = False,
+ tqdm_desc: str = "Table orientation",
tqdm_progress_bar=None,
) -> List[str]:
"""
批量预测传入表格图片的旋转角度,只返回角度,不修改输入图片。
"""
- RESOLUTION_GROUP_STRIDE = 128
rotate_labels = ["0"] * len(imgs)
- resolution_groups = self._collect_portrait_image_groups(
- imgs,
- RESOLUTION_GROUP_STRIDE,
- )
+ portrait_imgs = self._collect_portrait_images(imgs)
rotated_imgs = self._detect_rotation_candidates(
- resolution_groups,
+ portrait_imgs,
det_batch_size,
- RESOLUTION_GROUP_STRIDE,
+ tqdm_enable=tqdm_enable,
+ tqdm_desc=tqdm_desc,
tqdm_progress_bar=tqdm_progress_bar,
)
label_by_index = self._score_rotation_candidates(
rotated_imgs,
+ det_batch_size,
tqdm_enable=tqdm_enable,
+ tqdm_desc=tqdm_desc,
tqdm_progress_bar=tqdm_progress_bar,
)
for index, label in label_by_index.items():
diff --git a/mineru/model/table/rec/unet_table/main.py b/mineru/model/table/rec/unet_table/main.py
index c61aa5f8..5e5b0c45 100644
--- a/mineru/model/table/rec/unet_table/main.py
+++ b/mineru/model/table/rec/unet_table/main.py
@@ -28,6 +28,21 @@ from .utils_table_recover import (
sorted_ocr_boxes,
)
+BLANK_CELL_REC_DROP_TEXTS = {
+ "1",
+ "一",
+ "—",
+ "口",
+ "■",
+ "(204号",
+ "(20",
+ "(2",
+ "(2号",
+ "(20号",
+ "号",
+ "(204",
+}
+
@dataclass
class WiredTableInput:
@@ -142,20 +157,18 @@ class WiredTableRecognition:
dict_res["t_ocr_res"] = gather_ocr_list_by_row(dict_res["t_ocr_res"], threhold=0.3)
return res
- # def fill_blank_rec(
- # self,
- # img: np.ndarray,
- # sorted_polygons: np.ndarray,
- # cell_box_map: Dict[int, List[str]],
- # ) -> Dict[int, List[Any]]:
- # """找到poly对应为空的框,尝试将直接将poly框直接送到识别中"""
- # for i in range(sorted_polygons.shape[0]):
- # if cell_box_map.get(i):
- # continue
- # box = sorted_polygons[i]
- # cell_box_map[i] = [[box, "", 1]]
- # continue
- # return cell_box_map
+ @staticmethod
+ def _should_drop_blank_cell_rec_result(text: str, score) -> bool:
+ """判断空单元格二次 OCR-rec 结果是否应作为噪声过滤。"""
+ try:
+ if float(score) < 0.6:
+ return True
+ except (TypeError, ValueError):
+ return True
+
+ normalized_text = "" if text is None else str(text).strip()
+ return not normalized_text or normalized_text in BLANK_CELL_REC_DROP_TEXTS
+
def fill_blank_rec(
self,
img: np.ndarray,
@@ -218,7 +231,7 @@ class WiredTableRecognition:
# 处理ocr结果
ocr_text, ocr_score = ocr_res
# logger.debug(f"OCR result for box {i}: {ocr_text} with score {ocr_score}")
- if ocr_score < 0.6 or ocr_text in ["1", "口", "■", "(204号", "(20", "(2", "(2号", "(20号", "号", "(204"]:
+ if self._should_drop_blank_cell_rec_result(ocr_text, ocr_score):
# logger.warning(f"Low confidence OCR result for box {i}: {ocr_text} with score {ocr_score}")
box = sorted_polygons[i]
cell_box_map[i] = [[box, "", 0.1]]