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: add seal_PP-OCRv4 model support and enhance detection processing
myhloli37e53f8b708e
diff --git a/mineru/backend/pipeline/batch_analyze.py b/mineru/backend/pipeline/batch_analyze.pyindex 2b524938..9295377e 100644--- a/mineru/backend/pipeline/batch_analyze.py+++ b/mineru/backend/pipeline/batch_analyze.py@@ -889,4 +889,51 @@ class BatchAnalyze:total_processed += len(img_crop_list)+ seal_ocr_model = None+ for ocr_res_list_dict in tqdm(ocr_res_list_all_page, desc="Seal-ocr Predict"):+ layout_res = ocr_res_list_dict['layout_res']+ np_img = ocr_res_list_dict['np_img']+ image_h, image_w = np_img.shape[:2]++ for layout_res_item in layout_res:+ if layout_res_item.get("label") != "seal":+ continue++ layout_res_item["text"] = ""+ seal_bbox = normalize_to_int_bbox(+ layout_res_item.get("bbox"),+ image_size=(image_h, image_w),+ )+ if seal_bbox is None:+ continue++ x0, y0, x1, y1 = seal_bbox+ seal_crop_rgb = np_img[y0:y1, x0:x1]+ if seal_crop_rgb.size == 0:+ continue++ if seal_ocr_model is None:+ seal_ocr_model = atom_model_manager.get_atom_model(+ atom_model_name=AtomicModel.OCR,+ lang="seal",+ )++ seal_crop_bgr = cv2.cvtColor(seal_crop_rgb, cv2.COLOR_RGB2BGR)+ seal_ocr_res = seal_ocr_model.ocr(seal_crop_bgr, det=True, rec=True)[0]+ if not seal_ocr_res:+ continue++ seal_texts = []+ for seal_item in seal_ocr_res:+ if not seal_item or len(seal_item) != 2:+ continue+ rec_result = seal_item[1]+ if not rec_result or len(rec_result) < 1:+ continue+ rec_text = rec_result[0]+ if rec_text:+ seal_texts.append(rec_text)++ layout_res_item["text"] = seal_texts+return images_layout_resdiff --git a/mineru/model/ocr/pytorch_paddle.py b/mineru/model/ocr/pytorch_paddle.pyindex d03e0717..23dc56e4 100644--- a/mineru/model/ocr/pytorch_paddle.py+++ b/mineru/model/ocr/pytorch_paddle.py@@ -1,5 +1,6 @@# Copyright (c) Opendatalab. All rights reserved.import copy+import jsonimport osimport warningsfrom pathlib import Path@@ -9,6 +10,7 @@ import numpy as npimport yamlfrom loguru import logger+from mineru.model.ocr.seal_crop import CropByPolys, SortPolyBoxesfrom mineru.utils.config_reader import get_devicefrom mineru.utils.enum_class import ModelPathfrom mineru.utils.models_download_utils import auto_download_and_get_model_root_path@@ -135,6 +137,11 @@ def get_model_params(lang, config):root_dir = os.path.join(Path(__file__).resolve().parent.parent, 'utils')+DEFAULT_SEAL_DEBUG_DIR = os.path.join(+ Path(__file__).resolve().parents[3],+ 'output_images',+ 'seal_ocr_debug',+)class PytorchPaddleOCR(TextSystem):@@ -143,12 +150,16 @@ class PytorchPaddleOCR(TextSystem):args = parser.parse_args(args)self.lang = kwargs.get('lang', 'ch')+ self.is_seal = self.lang in ['seal', 'seal_lite']self.enable_merge_det_boxes = kwargs.get("enable_merge_det_boxes", True)device = get_device()- if device == 'cpu' and self.lang in ['ch', 'ch_server', 'japan', 'chinese_cht']:- # logger.warning("The current device in use is CPU. To ensure the speed of parsing, the language is automatically switched to ch_lite.")- self.lang = 'ch_lite'+ if device == 'cpu':+ if self.lang in ['ch', 'ch_server', 'japan', 'chinese_cht']:+ # logger.warning("The current device in use is CPU. To ensure the speed of parsing, the language is automatically switched to ch_lite.")+ self.lang = 'ch_lite'+ elif self.lang in ['seal']:+ self.lang = 'seal_lite'if self.lang in latin_lang:self.lang = 'latin'@@ -177,6 +188,18 @@ class PytorchPaddleOCR(TextSystem):kwargs['rec_model_path'] = rec_model_pathkwargs['rec_char_dict_path'] = os.path.join(root_dir, 'pytorchocr', 'utils', 'resources', 'dict', dict_file)kwargs['rec_batch_num'] = 6+ if self.is_seal:+ kwargs['det_limit_side_len'] = 736+ kwargs['det_limit_type'] = 'min'+ kwargs['det_max_side_limit'] = 4000+ kwargs['det_db_thresh'] = 0.2+ kwargs['det_db_box_thresh'] = 0.6+ kwargs['det_db_unclip_ratio'] = 0.5+ kwargs['det_box_type'] = 'poly'+ kwargs['use_dilation'] = False+ kwargs['enable_merge_det_boxes'] = False+ kwargs['drop_score'] = 0+ self.enable_merge_det_boxes = Falsekwargs['device'] = device@@ -185,6 +208,72 @@ class PytorchPaddleOCR(TextSystem):args = argparse.Namespace(**default_args)super().__init__(args)+ if self.is_seal:+ self._seal_sort_boxes = SortPolyBoxes()+ self._seal_crop_by_polys = CropByPolys(det_box_type='poly')+ self._seal_debug_counter = 0+ self._seal_debug_dir = self._resolve_seal_debug_dir()++ def _resolve_seal_debug_dir(self):+ if not self.is_seal:+ return None++ debug_dir = os.getenv("MINERU_SEAL_OCR_DEBUG_DIR")+ if debug_dir:+ return debug_dir++ debug_enable = os.getenv("MINERU_SEAL_OCR_DEBUG", "").lower()+ if debug_enable in {"1", "true", "yes", "on"}:+ return DEFAULT_SEAL_DEBUG_DIR++ return None++ def _dump_seal_debug_artifacts(self, input_image, dt_boxes, img_crop_list, rec_res=None):+ if not self._seal_debug_dir:+ return++ sample_dir = os.path.join(+ self._seal_debug_dir,+ f"sample_{self._seal_debug_counter:04d}",+ )+ self._seal_debug_counter += 1+ os.makedirs(sample_dir, exist_ok=True)++ cv2.imwrite(os.path.join(sample_dir, "input.png"), input_image)++ det_vis = input_image.copy()+ for index, box in enumerate(dt_boxes or []):+ points = np.asarray(box, dtype=np.int32).reshape((-1, 1, 2))+ cv2.polylines(det_vis, [points], isClosed=True, color=(0, 0, 255), thickness=2)+ anchor = tuple(np.asarray(box[0], dtype=np.int32).tolist())+ cv2.putText(+ det_vis,+ str(index),+ anchor,+ cv2.FONT_HERSHEY_SIMPLEX,+ 0.6,+ (255, 0, 0),+ 2,+ cv2.LINE_AA,+ )+ cv2.imwrite(os.path.join(sample_dir, "det_vis.png"), det_vis)++ records = []+ for index, crop_img in enumerate(img_crop_list or []):+ crop_name = f"crop_{index:02d}.png"+ cv2.imwrite(os.path.join(sample_dir, crop_name), crop_img)+ record = {+ "index": index,+ "crop_path": crop_name,+ }+ if rec_res is not None and index < len(rec_res):+ text, score = rec_res[index]+ record["text"] = text+ record["score"] = float(score)+ records.append(record)++ with open(os.path.join(sample_dir, "meta.json"), "w", encoding="utf-8") as f:+ json.dump(records, f, ensure_ascii=False, indent=2)def ocr(self,img,@@ -222,12 +311,17 @@ class PytorchPaddleOCR(TextSystem):if dt_boxes is None:ocr_res.append(None)continue- dt_boxes = sorted_boxes(dt_boxes)- # merge_det_boxes 和 update_det_boxes 都会把poly转成bbox再转回poly,因此需要过滤所有倾斜程度较大的文本框- if self.enable_merge_det_boxes:- dt_boxes = merge_det_boxes(dt_boxes)- if mfd_res:- dt_boxes = update_det_boxes(dt_boxes, mfd_res)+ if self.is_seal:+ dt_boxes = self._seal_sort_boxes(dt_boxes)+ img_crop_list = self._seal_crop_by_polys(img, dt_boxes)+ self._dump_seal_debug_artifacts(img, dt_boxes, img_crop_list)+ else:+ dt_boxes = sorted_boxes(dt_boxes)+ # merge_det_boxes 和 update_det_boxes 都会把poly转成bbox再转回poly,因此需要过滤所有倾斜程度较大的文本框+ if self.enable_merge_det_boxes:+ dt_boxes = merge_det_boxes(dt_boxes)+ if mfd_res:+ dt_boxes = update_det_boxes(dt_boxes, mfd_res)tmp_res = [box.tolist() for box in dt_boxes]ocr_res.append(tmp_res)return ocr_res@@ -257,24 +351,30 @@ class PytorchPaddleOCR(TextSystem):else:pass# logger.debug("dt_boxes num : {}, elapsed : {}".format(len(dt_boxes), elapse))- img_crop_list = []+ if self.is_seal:+ dt_boxes = self._seal_sort_boxes(dt_boxes)+ img_crop_list = self._seal_crop_by_polys(ori_im, dt_boxes)+ else:+ img_crop_list = []- dt_boxes = sorted_boxes(dt_boxes)+ dt_boxes = sorted_boxes(dt_boxes)- # merge_det_boxes 和 update_det_boxes 都会把poly转成bbox再转回poly,因此需要过滤所有倾斜程度较大的文本框- if self.enable_merge_det_boxes:- dt_boxes = merge_det_boxes(dt_boxes)+ # merge_det_boxes 和 update_det_boxes 都会把poly转成bbox再转回poly,因此需要过滤所有倾斜程度较大的文本框+ if self.enable_merge_det_boxes:+ dt_boxes = merge_det_boxes(dt_boxes)- if mfd_res:- dt_boxes = update_det_boxes(dt_boxes, mfd_res)+ if mfd_res:+ dt_boxes = update_det_boxes(dt_boxes, mfd_res)- for bno in range(len(dt_boxes)):- tmp_box = copy.deepcopy(dt_boxes[bno])- img_crop = get_rotate_crop_image(ori_im, tmp_box)- img_crop_list.append(img_crop)+ for bno in range(len(dt_boxes)):+ tmp_box = copy.deepcopy(dt_boxes[bno])+ img_crop = get_rotate_crop_image(ori_im, tmp_box)+ img_crop_list.append(img_crop)rec_res, elapse = self.text_recognizer(img_crop_list)# logger.debug("rec_res num : {}, elapsed : {}".format(len(rec_res), elapse))+ if self.is_seal:+ self._dump_seal_debug_artifacts(ori_im, dt_boxes, img_crop_list, rec_res)filter_boxes, filter_rec_res = [], []for box, rec_result in zip(dt_boxes, rec_res):@@ -296,5 +396,3 @@ if __name__ == '__main__':tmp_res = [[box.tolist(), res] for box, res in zip(dt_boxes, rec_res)]ocr_res.append(tmp_res)print(ocr_res)--diff --git a/mineru/model/utils/pytorchocr/data/imaug/operators.py b/mineru/model/utils/pytorchocr/data/imaug/operators.pyindex a4676aec..3c046f94 100644--- a/mineru/model/utils/pytorchocr/data/imaug/operators.py+++ b/mineru/model/utils/pytorchocr/data/imaug/operators.py@@ -188,6 +188,7 @@ class DetResizeForTest(object):def __init__(self, **kwargs):super(DetResizeForTest, self).__init__()self.resize_type = 0+ self.max_side_limit = kwargs.get('max_side_limit', 4000)if 'image_shape' in kwargs:self.image_shape = kwargs['image_shape']self.resize_type = 1@@ -261,6 +262,11 @@ class DetResizeForTest(object):resize_h = int(h * ratio)resize_w = int(w * ratio)+ if max(resize_h, resize_w) > self.max_side_limit:+ ratio = float(self.max_side_limit) / max(resize_h, resize_w)+ resize_h = int(resize_h * ratio)+ resize_w = int(resize_w * ratio)+resize_h = max(int(round(resize_h / 32) * 32), 32)resize_w = max(int(round(resize_w / 32) * 32), 32)diff --git a/mineru/model/utils/pytorchocr/postprocess/db_postprocess.py b/mineru/model/utils/pytorchocr/postprocess/db_postprocess.pyindex 7d1a5650..bd58eadb 100644--- a/mineru/model/utils/pytorchocr/postprocess/db_postprocess.py+++ b/mineru/model/utils/pytorchocr/postprocess/db_postprocess.py@@ -25,6 +25,7 @@ class DBPostProcess(object):unclip_ratio=2.0,use_dilation=False,score_mode="fast",+ box_type="quad",**kwargs):self.thresh = threshself.box_thresh = box_thresh@@ -32,6 +33,7 @@ class DBPostProcess(object):self.unclip_ratio = unclip_ratioself.min_size = 3self.score_mode = score_mode+ self.box_type = box_typeassert score_mode in ["slow", "fast"], "Score mode must be in [slow, fast] but got: {}".format(score_mode)@@ -39,6 +41,56 @@ class DBPostProcess(object):self.dilation_kernel = None if not use_dilation else np.array([[1, 1], [1, 1]])+ def polygons_from_bitmap(self, pred, _bitmap, dest_width, dest_height):+ """+ _bitmap: single map with shape (1, H, W),+ whose values are binarized as {0, 1}+ """++ bitmap = _bitmap+ height, width = bitmap.shape++ boxes = []+ scores = []++ contours, _ = cv2.findContours(+ (bitmap * 255).astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)++ for contour in contours[:self.max_candidates]:+ epsilon = 0.002 * cv2.arcLength(contour, True)+ approx = cv2.approxPolyDP(contour, epsilon, True)+ points = approx.reshape((-1, 2))+ if points.shape[0] < 4:+ continue++ score = self.box_score_fast(pred, points.reshape(-1, 2))+ if self.box_thresh > score:+ continue++ if points.shape[0] > 2:+ box = self.unclip(points, self.unclip_ratio)+ if len(box) > 1:+ continue+ else:+ continue++ box = np.array(box).reshape(-1, 2)+ if len(box) == 0:+ continue++ _, sside = self.get_mini_boxes(box.reshape((-1, 1, 2)))+ if sside < self.min_size + 2:+ continue++ box = np.array(box)+ box[:, 0] = np.clip(+ np.round(box[:, 0] / width * dest_width), 0, dest_width)+ box[:, 1] = np.clip(+ np.round(box[:, 1] / height * dest_height), 0, dest_height)+ boxes.append(box.tolist())+ scores.append(score)+ return boxes, scores+def boxes_from_bitmap(self, pred, _bitmap, dest_width, dest_height):'''_bitmap: single map with shape (1, H, W),@@ -72,7 +124,10 @@ class DBPostProcess(object):if self.box_thresh > score:continue- box = self.unclip(points).reshape(-1, 1, 2)+ box = self.unclip(points, self.unclip_ratio)+ if len(box) > 1:+ continue+ box = np.array(box).reshape(-1, 1, 2)box, sside = self.get_mini_boxes(box)if sside < self.min_size + 2:continue@@ -86,13 +141,12 @@ class DBPostProcess(object):scores.append(score)return np.array(boxes, dtype=np.int16), scores- def unclip(self, box):- unclip_ratio = self.unclip_ratio+ def unclip(self, box, unclip_ratio):poly = Polygon(box)distance = poly.area * unclip_ratio / poly.lengthoffset = pyclipper.PyclipperOffset()offset.AddPath(box, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)- expanded = np.array(offset.Execute(distance))+ expanded = offset.Execute(distance)return expandeddef get_mini_boxes(self, contour):@@ -172,8 +226,14 @@ class DBPostProcess(object):self.dilation_kernel)else:mask = segmentation[batch_index]- boxes, scores = self.boxes_from_bitmap(pred[batch_index], mask,- src_w, src_h)+ if self.box_type == "poly":+ boxes, scores = self.polygons_from_bitmap(+ pred[batch_index], mask, src_w, src_h)+ elif self.box_type == "quad":+ boxes, scores = self.boxes_from_bitmap(+ pred[batch_index], mask, src_w, src_h)+ else:+ raise ValueError("box_type can only be one of ['quad', 'poly']")boxes_batch.append({'points': boxes})- return boxes_batch\ No newline at end of file+ return boxes_batchdiff --git a/mineru/model/utils/pytorchocr/utils/resources/arch_config.yaml b/mineru/model/utils/pytorchocr/utils/resources/arch_config.yamlindex 6131ade5..5f7bca28 100644--- a/mineru/model/utils/pytorchocr/utils/resources/arch_config.yaml+++ b/mineru/model/utils/pytorchocr/utils/resources/arch_config.yaml@@ -44,6 +44,22 @@ seal_PP-OCRv4_det_infer:name: DBHeadk: 50+seal_PP-OCRv4_det_server_infer:+ model_type: det+ algorithm: DB+ Transform: null+ Backbone:+ name: PPHGNet_small+ det: True+ Neck:+ name: LKPAN+ out_channels: 256+ intracl: true+ Head:+ name: PFHeadLocal+ k: 50+ mode: "large"+ch_PP-OCRv5_det_infer:model_type: detalgorithm: DBdiff --git a/mineru/model/utils/pytorchocr/utils/resources/models_config.yml b/mineru/model/utils/pytorchocr/utils/resources/models_config.ymlindex 960e7d18..acc54ec0 100644--- a/mineru/model/utils/pytorchocr/utils/resources/models_config.yml+++ b/mineru/model/utils/pytorchocr/utils/resources/models_config.yml@@ -68,6 +68,10 @@ lang:rec: en_PP-OCRv5_rec_infer.pthdict: ppocrv5_en_dict.txtseal:+ det: seal_PP-OCRv4_det_server_infer.pth+ rec: ch_PP-OCRv5_rec_server_infer.pth+ dict: ppocrv5_dict.txt+ seal_lite:det: seal_PP-OCRv4_det_infer.pthrec: ch_PP-OCRv5_rec_infer.pthdict: ppocrv5_dict.txt\ No newline at end of filediff --git a/mineru/model/utils/tools/infer/predict_det.py b/mineru/model/utils/tools/infer/predict_det.pyindex 012beeae..211b15ac 100644--- a/mineru/model/utils/tools/infer/predict_det.py+++ b/mineru/model/utils/tools/infer/predict_det.py@@ -18,6 +18,7 @@ class TextDetector(BaseOCRV20):'DetResizeForTest': {'limit_side_len': args.det_limit_side_len,'limit_type': args.det_limit_type,+ 'max_side_limit': args.det_max_side_limit,}}, {'NormalizeImage': {@@ -42,6 +43,7 @@ class TextDetector(BaseOCRV20):postprocess_params["unclip_ratio"] = args.det_db_unclip_ratiopostprocess_params["use_dilation"] = args.use_dilationpostprocess_params["score_mode"] = args.det_db_score_mode+ postprocess_params["box_type"] = args.det_box_typeelif self.det_algorithm == "DB++":postprocess_params['name'] = 'DBPostProcess'postprocess_params["thresh"] = args.det_db_thresh@@ -50,6 +52,7 @@ class TextDetector(BaseOCRV20):postprocess_params["unclip_ratio"] = args.det_db_unclip_ratiopostprocess_params["use_dilation"] = args.use_dilationpostprocess_params["score_mode"] = args.det_db_score_mode+ postprocess_params["box_type"] = args.det_box_typepre_process_list[1] = {'NormalizeImage': {'std': [1.0, 1.0, 1.0],@@ -120,6 +123,18 @@ class TextDetector(BaseOCRV20):if hasattr(module, 'rep'):module.rep()+ def _should_only_clip_det_res(self):+ if self.det_algorithm == "SAST" and getattr(self, "det_sast_polygon", False):+ return True+ if self.det_algorithm in ["DB", "DB++", "PSE", "FCE"]:+ return getattr(self.postprocess_op, "box_type", "quad") == "poly"+ return False++ def _filter_det_res(self, dt_boxes, image_shape):+ if self._should_only_clip_det_res():+ return self.filter_tag_det_res_only_clip(dt_boxes, image_shape)+ return self.filter_tag_det_res(dt_boxes, image_shape)+def _batch_process_same_size(self, img_list):"""对相同尺寸的图像进行批处理@@ -206,12 +221,7 @@ class TextDetector(BaseOCRV20):dt_boxes = post_result[0]['points']# 过滤和裁剪检测框- if (self.det_algorithm == "SAST" and- self.det_sast_polygon) or (self.det_algorithm in ["PSE", "FCE"] and- self.postprocess_op.box_type == 'poly'):- dt_boxes = self.filter_tag_det_res_only_clip(dt_boxes, ori_imgs[i].shape)- else:- dt_boxes = self.filter_tag_det_res(dt_boxes, ori_imgs[i].shape)+ dt_boxes = self._filter_det_res(dt_boxes, ori_imgs[i].shape)batch_results.append((dt_boxes, total_elapse / len(img_list)))@@ -290,10 +300,10 @@ class TextDetector(BaseOCRV20):img_height, img_width = image_shape[0:2]dt_boxes_new = []for box in dt_boxes:+ box = np.array(box)box = self.clip_det_res(box, img_height, img_width)dt_boxes_new.append(box)- dt_boxes = np.array(dt_boxes_new)- return dt_boxes+ return dt_boxes_newdef __call__(self, img):ori_shape = img.shape@@ -331,12 +341,7 @@ class TextDetector(BaseOCRV20):post_result = self.postprocess_op(preds, shape_list)dt_boxes = post_result[0]['points']- if (self.det_algorithm == "SAST" and- self.det_sast_polygon) or (self.det_algorithm in ["PSE", "FCE"] and- self.postprocess_op.box_type == 'poly'):- dt_boxes = self.filter_tag_det_res_only_clip(dt_boxes, ori_shape)- else:- dt_boxes = self.filter_tag_det_res(dt_boxes, ori_shape)+ dt_boxes = self._filter_det_res(dt_boxes, ori_shape)elapse = time.time() - starttimereturn dt_boxes, elapsediff --git a/mineru/model/utils/tools/infer/pytorchocr_utility.py b/mineru/model/utils/tools/infer/pytorchocr_utility.pyindex 912d124e..5b3bd56a 100644--- a/mineru/model/utils/tools/infer/pytorchocr_utility.py+++ b/mineru/model/utils/tools/infer/pytorchocr_utility.py@@ -32,6 +32,8 @@ def init_args():parser.add_argument("--det_model_path", type=str)parser.add_argument("--det_limit_side_len", type=float, default=960)parser.add_argument("--det_limit_type", type=str, default='max')+ parser.add_argument("--det_max_side_limit", type=int, default=4000)+ parser.add_argument("--det_box_type", type=str, default='quad')# DB parmasparser.add_argument("--det_db_thresh", type=float, default=0.3)@@ -224,4 +226,4 @@ def get_arch_config(model_path):raise ValueError(f"architecture {file_name} is not in arch_config.yaml")arch_config = all_arch_config[file_name]- return arch_config\ No newline at end of file+ return arch_configdiff --git a/mineru/utils/pdf_image_tools.py b/mineru/utils/pdf_image_tools.pyindex a1438344..cb29773a 100644--- a/mineru/utils/pdf_image_tools.py+++ b/mineru/utils/pdf_image_tools.py@@ -285,9 +285,13 @@ def images_bytes_to_pdf_bytes(image_bytes):image = image.convert("RGB")# 第一张图保存为 PDF,其余追加+ # Keep image inputs at the same raster size when CLI later renders the+ # wrapper PDF at 200 dpi; PIL defaults to 72 dpi for PDF output, which+ # would upscale the image and noticeably hurt seal OCR detection quality.image.save(pdf_buffer,format="PDF",+ resolution=200.0,# save_all=True)