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
refactor: standardize layout model batch size and improve OCR processing logic
myhloli86f455176d07
diff --git a/mineru/backend/pipeline/batch_analyze.py b/mineru/backend/pipeline/batch_analyze.pyindex 7063d7d1..819a0fd8 100644--- a/mineru/backend/pipeline/batch_analyze.py+++ b/mineru/backend/pipeline/batch_analyze.py@@ -14,8 +14,7 @@ from ...utils.ocr_utils import merge_det_boxes, update_det_boxes, sorted_boxesfrom ...utils.ocr_utils import get_adjusted_mfdetrec_res, get_ocr_result_list, OcrConfidence, get_rotate_crop_imagefrom ...utils.pdf_image_tools import get_crop_np_img-YOLO_LAYOUT_BASE_BATCH_SIZE = 1-MFD_BASE_BATCH_SIZE = 1+LAYOUT_BASE_BATCH_SIZE = 1MFR_BASE_BATCH_SIZE = 16OCR_DET_BASE_BATCH_SIZE = 16TABLE_ORI_CLS_BATCH_SIZE = 16@@ -47,17 +46,20 @@ class BatchAnalyze:np_images = [np.asarray(image) for image, _, _ in images_with_extra_info]- # doclayout_yolo-+ # pp-doclayout_v2images_layout_res += self.model.layout_model.batch_predict(- pil_images, YOLO_LAYOUT_BASE_BATCH_SIZE+ pil_images, LAYOUT_BASE_BATCH_SIZE)if self.formula_enable:- # 公式检测- images_mfd_res = self.model.mfd_model.batch_predict(- np_images, MFD_BASE_BATCH_SIZE- )+ images_mfd_res = []+ for layout_res in images_layout_res:+ page_formula_res = []+ for res in layout_res:+ if res.get("label") == "formula":+ res.setdefault("latex", "")+ page_formula_res.append(res)+ images_mfd_res.append(page_formula_res)# 公式识别images_formula_list = self.model.mfr_model.batch_predict(@@ -67,8 +69,11 @@ class BatchAnalyze:)mfr_count = 0for image_index in range(len(np_images)):- images_layout_res[image_index] += images_formula_list[image_index]mfr_count += len(images_formula_list[image_index])+ for formula_res, formula_with_latex in zip(+ images_mfd_res[image_index], images_formula_list[image_index]+ ):+ formula_res["latex"] = formula_with_latex.get("latex", "")# 清理显存clean_vram(self.model.device, vram_threshold=8)@@ -94,8 +99,9 @@ class BatchAnalyze:for table_res in table_res_list:def get_crop_table_img(scale):- crop_xmin, crop_ymin = int(table_res['poly'][0]), int(table_res['poly'][1])- crop_xmax, crop_ymax = int(table_res['poly'][4]), int(table_res['poly'][5])+ crop_xmin, crop_ymin, crop_xmax, crop_ymax = [+ int(v) for v in table_res["bbox"]+ ]bbox = (int(crop_xmin / scale), int(crop_ymin / scale), int(crop_xmax / scale), int(crop_ymax / scale))return get_crop_np_img(bbox, np_img, scale=scale)@@ -156,7 +162,7 @@ class BatchAnalyze:ocr_result = det_ocr_engine.ocr(bgr_image, rec=False)[0]# 构造需要 OCR 识别的图片字典,包括cropped_img, dt_box, table_id,并按照语言进行分组for dt_box in ocr_result:- rec_img_lang_group[_lang].append(+ rec_img_lang_group[table_res_dict["lang"]].append({"cropped_img": get_rotate_crop_image(bgr_image, np.asarray(dt_box, dtype=np.float32)@@ -326,7 +332,11 @@ class BatchAnalyze: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_res_list_dict['ocr_enable'], bgr_image, _lang+ ocr_res,+ useful_list,+ ocr_res_list_dict['ocr_enable'],+ bgr_image,+ _lang,)ocr_res_list_dict['layout_res'].extend(ocr_result_list)@@ -358,7 +368,11 @@ class BatchAnalyze:# Integration resultsif ocr_res:ocr_result_list = get_ocr_result_list(- ocr_res, useful_list, ocr_res_list_dict['ocr_enable'],bgr_image, _lang+ ocr_res,+ useful_list,+ ocr_res_list_dict['ocr_enable'],+ bgr_image,+ _lang,)ocr_res_list_dict['layout_res'].extend(ocr_result_list)@@ -370,22 +384,24 @@ class BatchAnalyze:for layout_res in images_layout_res:for layout_res_item in layout_res:- if layout_res_item['category_id'] in [15]:- if 'np_img' in layout_res_item and 'lang' in layout_res_item:- lang = layout_res_item['lang']+ if not layout_res_item.get("_need_ocr_rec"):+ continue+ if 'np_img' in layout_res_item and 'lang' in layout_res_item:+ lang = layout_res_item['lang']- # Initialize lists for this language if not exist- if lang not in need_ocr_lists_by_lang:- need_ocr_lists_by_lang[lang] = []- img_crop_lists_by_lang[lang] = []+ # Initialize lists for this language if not exist+ if lang not in need_ocr_lists_by_lang:+ need_ocr_lists_by_lang[lang] = []+ img_crop_lists_by_lang[lang] = []- # Add to the appropriate language-specific lists- need_ocr_lists_by_lang[lang].append(layout_res_item)- img_crop_lists_by_lang[lang].append(layout_res_item['np_img'])+ # Add to the appropriate language-specific lists+ need_ocr_lists_by_lang[lang].append((layout_res, layout_res_item))+ img_crop_lists_by_lang[lang].append(layout_res_item['np_img'])- # Remove the fields after adding to lists- layout_res_item.pop('np_img')- layout_res_item.pop('lang')+ # Remove temporary fields after collecting+ layout_res_item.pop('np_img', None)+ layout_res_item.pop('lang', None)+ layout_res_item.pop('_need_ocr_rec', None)if len(img_crop_lists_by_lang) > 0:@@ -408,16 +424,17 @@ class BatchAnalyze:assert len(ocr_res_list) == len(need_ocr_lists_by_lang[lang]), f'ocr_res_list: {len(ocr_res_list)}, need_ocr_list: {len(need_ocr_lists_by_lang[lang])} for lang: {lang}'+ items_to_remove = []# Process OCR results for this language- for index, layout_res_item in enumerate(need_ocr_lists_by_lang[lang]):+ for index, (page_layout_res, layout_res_item) in enumerate(need_ocr_lists_by_lang[lang]):ocr_text, ocr_score = ocr_res_list[index]layout_res_item['text'] = ocr_textlayout_res_item['score'] = float(f"{ocr_score:.3f}")+ should_remove = Falseif ocr_score < OcrConfidence.min_confidence:- layout_res_item['category_id'] = 16+ should_remove = Trueelse:- layout_res_bbox = [layout_res_item['poly'][0], layout_res_item['poly'][1],- layout_res_item['poly'][4], layout_res_item['poly'][5]]+ layout_res_bbox = layout_res_item['bbox']layout_res_width = layout_res_bbox[2] - layout_res_bbox[0]layout_res_height = layout_res_bbox[3] - layout_res_bbox[1]if (@@ -429,7 +446,14 @@ class BatchAnalyze:and ocr_score < 0.8and layout_res_width < layout_res_height):- layout_res_item['category_id'] = 16+ should_remove = True++ if should_remove:+ items_to_remove.append((page_layout_res, layout_res_item))++ for page_layout_res, layout_res_item in items_to_remove:+ if layout_res_item in page_layout_res:+ page_layout_res.remove(layout_res_item)total_processed += len(img_crop_list)diff --git a/mineru/backend/pipeline/model_init.py b/mineru/backend/pipeline/model_init.pyindex 2d167ade..5341071f 100644--- a/mineru/backend/pipeline/model_init.py+++ b/mineru/backend/pipeline/model_init.py@@ -4,15 +4,12 @@ import torchfrom loguru import loggerfrom .model_list import AtomicModel-from ...model.layout.doclayoutyolo import DocLayoutYOLOModelfrom ...model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel-from ...model.mfd.yolo_v8 import YOLOv8MFDModelfrom ...model.mfr.unimernet.Unimernet import UnimernetModelfrom ...model.mfr.pp_formulanet_plus_m.predict_formula import FormulaRecognizerfrom mineru.model.ocr.pytorch_paddle import PytorchPaddleOCRfrom ...model.ori_cls.paddle_ori_cls import PaddleOrientationClsModelfrom ...model.table.cls.paddle_table_cls import PaddleTableClsModel-# from ...model.table.rec.RapidTable import RapidTableModelfrom ...model.table.rec.slanet_plus.main import RapidTableModelfrom ...model.table.rec.unet_table.main import UnetTableModelfrom ...utils.config_reader import get_device@@ -29,27 +26,6 @@ else:MFR_MODEL = "unimernet_small"-def get_layout_model_name() -> str:- return os.getenv("MINERU_LAYOUT_MODEL", "doclayout_yolo").strip().lower()---def get_layout_model_weight(layout_model_name: str) -> str:- override_path = os.getenv("MINERU_LAYOUT_MODEL_PATH")- if override_path:- return override_path-- if layout_model_name == "doclayout_yolo":- return str(- os.path.join(- auto_download_and_get_model_root_path(ModelPath.doclayout_yolo),- ModelPath.doclayout_yolo,- )- )- if layout_model_name == "pp_doclayout_v2":- return os.getenv("MINERU_PP_DOCLAYOUT_V2_MODEL", ModelPath.pp_doclayout_v2)- raise ValueError(f"Unsupported layout model: {layout_model_name}")--def img_orientation_cls_model_init():atom_model_manager = AtomModelSingleton()ocr_engine = atom_model_manager.get_atom_model(@@ -93,13 +69,6 @@ def wireless_table_model_init(lang=None):return table_model-def mfd_model_init(weight, device='cpu'):- if str(device).startswith('npu'):- device = torch.device(device)- mfd_model = YOLOv8MFDModel(weight, device)- return mfd_model--def mfr_model_init(weight_dir, device='cpu'):if MFR_MODEL == "unimernet_small":mfr_model = UnimernetModel(weight_dir, device)@@ -111,13 +80,6 @@ def mfr_model_init(weight_dir, device='cpu'):return mfr_model-def doclayout_yolo_model_init(weight, device='cpu'):- if str(device).startswith('npu'):- device = torch.device(device)- model = DocLayoutYOLOModel(weight, device)- return model--def pp_doclayout_v2_model_init(weight, device='cpu'):if str(device).startswith('npu'):device = torch.device(device)@@ -190,24 +152,8 @@ class AtomModelSingleton:def atom_model_init(model_name: str, **kwargs):atom_model = Noneif model_name == AtomicModel.Layout:- layout_model_name = kwargs.get('layout_model_name', 'doclayout_yolo')- layout_model_weight = kwargs.get('layout_model_weight')- if layout_model_name == 'doclayout_yolo':- atom_model = doclayout_yolo_model_init(- layout_model_weight or kwargs.get('doclayout_yolo_weights'),- kwargs.get('device')- )- elif layout_model_name == 'pp_doclayout_v2':- atom_model = pp_doclayout_v2_model_init(- layout_model_weight or kwargs.get('pp_doclayout_v2_weights'),- kwargs.get('device')- )- else:- logger.error(f'layout model name not allow: {layout_model_name}')- exit(1)- elif model_name == AtomicModel.MFD:- atom_model = mfd_model_init(- kwargs.get('mfd_weights'),+ atom_model = pp_doclayout_v2_model_init(+ kwargs.get('pp_doclayout_v2_weights'),kwargs.get('device'))elif model_name == AtomicModel.MFR:@@ -257,19 +203,8 @@ class MineruPipelineModel:'DocAnalysis init, this may take some times......')atom_model_manager = AtomModelSingleton()- layout_model_name = get_layout_model_name()- layout_model_weight = get_layout_model_weight(layout_model_name)if self.apply_formula:- # 初始化公式检测模型- self.mfd_model = atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.MFD,- mfd_weights=str(- os.path.join(auto_download_and_get_model_root_path(ModelPath.yolo_v8_mfd), ModelPath.yolo_v8_mfd)- ),- device=self.device,- )-# 初始化公式解析模型if MFR_MODEL == "unimernet_small":mfr_model_path = ModelPath.unimernet_small@@ -286,11 +221,11 @@ class MineruPipelineModel:)# 初始化layout模型- logger.info(f'Using layout model: {layout_model_name}')self.layout_model = atom_model_manager.get_atom_model(atom_model_name=AtomicModel.Layout,- layout_model_name=layout_model_name,- layout_model_weight=layout_model_weight,+ pp_doclayout_v2_weights=str(+ os.path.join(auto_download_and_get_model_root_path(ModelPath.pp_doclayout_v2), ModelPath.pp_doclayout_v2)+ ),device=self.device,)# 初始化ocrdiff --git a/mineru/model/layout/pp_doclayoutv2.py b/mineru/model/layout/pp_doclayoutv2.pyindex 051e6569..079889be 100644--- a/mineru/model/layout/pp_doclayoutv2.py+++ b/mineru/model/layout/pp_doclayoutv2.py@@ -23,11 +23,8 @@ from transformers.models.rt_detr.configuration_rt_detr import RTDetrConfigfrom transformers.models.rt_detr.modeling_rt_detr import RTDetrForObjectDetection, RTDetrModel, RTDetrPreTrainedModelfrom transformers.utils import ModelOutput--DEFAULT_PP_DOCLAYOUT_V2_REPO = "PaddlePaddle/PP-DocLayoutV2_safetensors"DEFAULT_IMAGE_SIZE = (800, 800)DEFAULT_RESCALE_FACTOR = 1.0 / 255.0-MODEL_ALLOW_PATTERNS = ["config.json", "model.safetensors", "preprocessor_config.json"]PP_DOCLAYOUT_V2_LABELS = ["abstract", # 0@@ -161,19 +158,6 @@ def _create_bidirectional_mask(torch.full((1,), min_value, dtype=embeds.dtype, device=embeds.device),)-def _resolve_model_dir(weight: str) -> str:- expanded_weight = os.path.expanduser(weight)- if os.path.isdir(expanded_weight):- return expanded_weight- if os.path.isfile(expanded_weight):- return os.path.dirname(expanded_weight)-- repo_parts = weight.split("/")- if not weight.startswith((".", os.path.sep)) and len(repo_parts) == 2:- return snapshot_download(repo_id=weight, allow_patterns=MODEL_ALLOW_PATTERNS)-- raise FileNotFoundError(f"PP-DocLayoutV2 model source not found: {weight}")-def _load_preprocess_config(model_dir: str) -> Dict:config_path = os.path.join(model_dir, "preprocessor_config.json")@@ -916,15 +900,14 @@ class PPDocLayoutV2ForObjectDetection(RTDetrForObjectDetection):class PPDocLayoutV2LayoutModel:def __init__(self,- weight: str = DEFAULT_PP_DOCLAYOUT_V2_REPO,- device: Optional[str] = None,+ weight: str,+ device: Optional[str] = "cuda",imgsz: Tuple[int, int] = DEFAULT_IMAGE_SIZE,conf: float = 0.5,):- self.weight = weight- self.device = _select_runtime_device(device)+ self.device = deviceself.conf = conf- self.model_dir = _resolve_model_dir(weight)+ self.model_dir = weightself.preprocess_config = _load_preprocess_config(self.model_dir)size = self.preprocess_config.get("size", {})self.imgsz = (diff --git a/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py b/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.pyindex 0b66c06f..02332fc2 100644--- a/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py+++ b/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py@@ -65,9 +65,48 @@ class FormulaRecognizer(BaseOCRV20):character_list=data["PostProcess"]["character_dict"])+ @staticmethod+ def _normalize_bbox(bbox, image):+ if bbox is None:+ return None++ xmin, ymin, xmax, ymax = [int(v) for v in bbox]+ height, width = image.shape[:2]+ xmin = max(0, min(width, xmin))+ xmax = max(0, min(width, xmax))+ ymin = max(0, min(height, ymin))+ ymax = max(0, min(height, ymax))+ if xmax <= xmin or ymax <= ymin:+ return None+ return xmin, ymin, xmax, ymax++ @staticmethod+ def _item_to_bbox(item, image):+ return FormulaRecognizer._normalize_bbox(item.get("bbox"), image)++ def _build_formula_items(self, mfd_res, image, interline_enable=True):+ formula_list = []+ crop_targets = []++ for item in mfd_res or []:+ if not isinstance(item, dict):+ continue+ if item.get("label") != "formula":+ continue++ new_item = dict(item)+ new_item.setdefault("latex", "")+ formula_list.append(new_item)++ bbox = self._item_to_bbox(new_item, image)+ if bbox is not None:+ crop_targets.append((new_item, bbox))++ return formula_list, crop_targets+def predict(self, img_list, batch_size: int = 64):# Reduce batch size by 50% to avoid potential memory issues during inference.- batch_size = int(0.5 * batch_size)+ batch_size = max(1, int(0.5 * batch_size))batch_imgs = self.pre_tfs["UniMERNetImgDecode"](imgs=img_list)batch_imgs = self.pre_tfs["UniMERNetTestTransform"](imgs=batch_imgs)batch_imgs = self.pre_tfs["LatexImageFormat"](imgs=batch_imgs)@@ -104,30 +143,20 @@ class FormulaRecognizer(BaseOCRV20):for image_index in range(len(images_mfd_res)):mfd_res = images_mfd_res[image_index]image = images[image_index]- formula_list = []-- for idx, (xyxy, conf, cla) in enumerate(- zip(mfd_res.boxes.xyxy, mfd_res.boxes.conf, mfd_res.boxes.cls)- ):- if not interline_enable and cla.item() == 1:- continue # Skip interline regions if not enabled- xmin, ymin, xmax, ymax = [int(p.item()) for p in xyxy]- new_item = {- "category_id": 13 + int(cla.item()),- "poly": [xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax],- "score": round(float(conf.item()), 2),- "latex": "",- }- formula_list.append(new_item)+ formula_list, crop_targets = self._build_formula_items(+ mfd_res, image, interline_enable=interline_enable+ )++ for formula_item, (xmin, ymin, xmax, ymax) in crop_targets:bbox_img = image[ymin:ymax, xmin:xmax]area = (xmax - xmin) * (ymax - ymin)curr_idx = len(mf_image_list)image_info.append((area, curr_idx, bbox_img))mf_image_list.append(bbox_img)+ backfill_list.append(formula_item)images_formula_list.append(formula_list)- backfill_list += formula_list# Stable sort by areaimage_info.sort(key=lambda x: x[0]) # sort by areadiff --git a/mineru/model/mfr/unimernet/Unimernet.py b/mineru/model/mfr/unimernet/Unimernet.pyindex 5f8b9513..9b9eee21 100644--- a/mineru/model/mfr/unimernet/Unimernet.py+++ b/mineru/model/mfr/unimernet/Unimernet.py@@ -2,8 +2,6 @@ import torchfrom torch.utils.data import DataLoader, Datasetfrom tqdm import tqdm-from mineru.utils.boxbase import calculate_iou-class MathDataset(Dataset):def __init__(self, image_paths, transform=None):@@ -34,75 +32,57 @@ class UnimernetModel(object):self.model.eval()@staticmethod- def _filter_boxes_by_iou(xyxy, conf, cla, iou_threshold=0.8):- """过滤IOU超过阈值的重叠框,保留置信度较高的框。-- Args:- xyxy: 框坐标张量,shape为(N, 4)- conf: 置信度张量,shape为(N,)- cla: 类别张量,shape为(N,)- iou_threshold: IOU阈值,默认0.9-- Returns:- 过滤后的xyxy, conf, cla张量- """- if len(xyxy) == 0:- return xyxy, conf, cla-- # 转换为CPU进行处理- xyxy_cpu = xyxy.cpu()- conf_cpu = conf.cpu()-- n = len(xyxy_cpu)- keep = [True] * n-- for i in range(n):- if not keep[i]:- continue- bbox1 = xyxy_cpu[i].tolist()- for j in range(i + 1, n):- if not keep[j]:- continue- bbox2 = xyxy_cpu[j].tolist()- iou = calculate_iou(bbox1, bbox2)- if iou > iou_threshold:- # 保留置信度较高的框- if conf_cpu[i] >= conf_cpu[j]:- keep[j] = False- else:- keep[i] = False- break # i被删除,跳出内循环-- keep_indices = [i for i in range(n) if keep[i]]- if len(keep_indices) == n:- return xyxy, conf, cla-- keep_indices = torch.tensor(keep_indices, dtype=torch.long)- return xyxy[keep_indices], conf[keep_indices], cla[keep_indices]+ def _normalize_bbox(bbox, image):+ if bbox is None:+ return None++ xmin, ymin, xmax, ymax = [int(v) for v in bbox]+ height, width = image.shape[:2]+ xmin = max(0, min(width, xmin))+ xmax = max(0, min(width, xmax))+ ymin = max(0, min(height, ymin))+ ymax = max(0, min(height, ymax))+ if xmax <= xmin or ymax <= ymin:+ return None+ return xmin, ymin, xmax, ymax- def predict(self, mfd_res, image):+ @staticmethod+ def _item_to_bbox(item, image):+ return UnimernetModel._normalize_bbox(item.get("bbox"), image)++ def _build_formula_items(self, mfd_res, image, interline_enable=True):formula_list = []- mf_image_list = []+ crop_targets = []- # 对检测框进行IOU去重,保留置信度较高的框- xyxy_filtered, conf_filtered, cla_filtered = self._filter_boxes_by_iou(- mfd_res.boxes.xyxy, mfd_res.boxes.conf, mfd_res.boxes.cls- )+ for item in mfd_res or []:+ if not isinstance(item, dict):+ continue+ if item.get("label") != "formula":+ continue- for xyxy, conf, cla in zip(- xyxy_filtered.cpu(), conf_filtered.cpu(), cla_filtered.cpu()- ):- xmin, ymin, xmax, ymax = [int(p.item()) for p in xyxy]- new_item = {- "category_id": 13 + int(cla.item()),- "poly": [xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax],- "score": round(float(conf.item()), 2),- "latex": "",- }+ new_item = dict(item)+ new_item.setdefault("latex", "")formula_list.append(new_item)++ bbox = self._item_to_bbox(new_item, image)+ if bbox is not None:+ crop_targets.append((new_item, bbox))++ return formula_list, crop_targets++ def predict(self, mfd_res, image):+ formula_list, crop_targets = self._build_formula_items(+ mfd_res, image, interline_enable=True+ )+ mf_image_list = []++ for _, (xmin, ymin, xmax, ymax) in crop_targets:bbox_img = image[ymin:ymax, xmin:xmax]mf_image_list.append(bbox_img)+ if not mf_image_list:+ return formula_list+dataset = MathDataset(mf_image_list, transform=self.model.transform)dataloader = DataLoader(dataset, batch_size=32, num_workers=0)mfr_res = []@@ -112,7 +92,7 @@ class UnimernetModel(object):with torch.no_grad():output = self.model.generate({"image": mf_img})mfr_res.extend(output["fixed_str"])- for res, latex in zip(formula_list, mfr_res):+ for (res, _), latex in zip(crop_targets, mfr_res):res["latex"] = latexreturn formula_list@@ -132,35 +112,20 @@ class UnimernetModel(object):for image_index in range(len(images_mfd_res)):mfd_res = images_mfd_res[image_index]image = images[image_index]- formula_list = []-- # 对检测框进行IOU去重,保留置信度较高的框- xyxy_filtered, conf_filtered, cla_filtered = self._filter_boxes_by_iou(- mfd_res.boxes.xyxy, mfd_res.boxes.conf, mfd_res.boxes.cls+ formula_list, crop_targets = self._build_formula_items(+ mfd_res, image, interline_enable=interline_enable)- for idx, (xyxy, conf, cla) in enumerate(zip(- xyxy_filtered, conf_filtered, cla_filtered- )):- if not interline_enable and cla.item() == 1:- continue # Skip interline regions if not enabled- xmin, ymin, xmax, ymax = [int(p.item()) for p in xyxy]- new_item = {- "category_id": 13 + int(cla.item()),- "poly": [xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax],- "score": round(float(conf.item()), 2),- "latex": "",- }- formula_list.append(new_item)+ for formula_item, (xmin, ymin, xmax, ymax) in crop_targets:bbox_img = image[ymin:ymax, xmin:xmax]area = (xmax - xmin) * (ymax - ymin)curr_idx = len(mf_image_list)image_info.append((area, curr_idx, bbox_img))mf_image_list.append(bbox_img)+ backfill_list.append(formula_item)images_formula_list.append(formula_list)- backfill_list += formula_list# Stable sort by areaimage_info.sort(key=lambda x: x[0]) # sort by areadiff --git a/mineru/model/table/rec/RapidTable.py b/mineru/model/table/rec/RapidTable.pydeleted file mode 100644index 1f991b61..00000000--- a/mineru/model/table/rec/RapidTable.py+++ /dev/null@@ -1,154 +0,0 @@-import html-import os-import time-from pathlib import Path-from typing import List--import cv2-import numpy as np-from loguru import logger-from rapid_table import ModelType, RapidTable, RapidTableInput-from rapid_table.utils import RapidTableOutput-from tqdm import tqdm--from mineru.model.ocr.pytorch_paddle import PytorchPaddleOCR-from mineru.utils.enum_class import ModelPath-from mineru.utils.models_download_utils import auto_download_and_get_model_root_path---def escape_html(input_string):- """Escape HTML Entities."""- return html.escape(input_string)---class CustomRapidTable(RapidTable):- def __init__(self, cfg: RapidTableInput):- import logging- # 通过环境变量控制日志级别- logging.disable(logging.INFO)- super().__init__(cfg)- def __call__(self, img_contents, ocr_results=None, batch_size=1):- if not isinstance(img_contents, list):- img_contents = [img_contents]-- s = time.perf_counter()-- results = RapidTableOutput()-- total_nums = len(img_contents)-- with tqdm(total=total_nums, desc="Table-wireless Predict") as pbar:- for start_i in range(0, total_nums, batch_size):- end_i = min(total_nums, start_i + batch_size)-- imgs = self._load_imgs(img_contents[start_i:end_i])-- pred_structures, cell_bboxes = self.table_structure(imgs)- logic_points = self.table_matcher.decode_logic_points(pred_structures)-- dt_boxes, rec_res = self.get_ocr_results(imgs, start_i, end_i, ocr_results)- pred_htmls = self.table_matcher(- pred_structures, cell_bboxes, dt_boxes, rec_res- )-- results.pred_htmls.extend(pred_htmls)- # 更新进度条- pbar.update(end_i - start_i)-- elapse = time.perf_counter() - s- results.elapse = elapse / total_nums- return results---class RapidTableModel():- def __init__(self, ocr_engine):- slanet_plus_model_path = os.path.join(- auto_download_and_get_model_root_path(ModelPath.slanet_plus),- ModelPath.slanet_plus,- )- input_args = RapidTableInput(- model_type=ModelType.SLANETPLUS,- model_dir_or_path=slanet_plus_model_path,- use_ocr=False- )- self.table_model = CustomRapidTable(input_args)- self.ocr_engine = ocr_engine-- def predict(self, image, ocr_result=None):- bgr_image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)- # Continue with OCR on potentially rotated image-- if not ocr_result:- raw_ocr_result = self.ocr_engine.ocr(bgr_image)[0]- # 分离边界框、文本和置信度- boxes = []- texts = []- scores = []- for item in raw_ocr_result:- if len(item) == 3:- boxes.append(item[0])- texts.append(escape_html(item[1]))- scores.append(item[2])- elif len(item) == 2 and isinstance(item[1], tuple):- boxes.append(item[0])- texts.append(escape_html(item[1][0]))- scores.append(item[1][1])- # 按照 rapid_table 期望的格式构建 ocr_results- ocr_result = [(boxes, texts, scores)]-- if ocr_result:- try:- table_results = self.table_model(img_contents=np.asarray(image), ocr_results=ocr_result)- html_code = table_results.pred_htmls- table_cell_bboxes = table_results.cell_bboxes- logic_points = table_results.logic_points- elapse = table_results.elapse- return html_code, table_cell_bboxes, logic_points, elapse- except Exception as e:- logger.exception(e)-- return None, None, None, None-- def batch_predict(self, table_res_list: List[dict], batch_size: int = 4):- not_none_table_res_list = []- for table_res in table_res_list:- if table_res.get("ocr_result", None):- not_none_table_res_list.append(table_res)-- if not_none_table_res_list:- img_contents = [table_res["table_img"] for table_res in not_none_table_res_list]- ocr_results = []- # ocr_results需要按照rapid_table期望的格式构建- for table_res in not_none_table_res_list:- raw_ocr_result = table_res["ocr_result"]- boxes = []- texts = []- scores = []- for item in raw_ocr_result:- if len(item) == 3:- boxes.append(item[0])- texts.append(escape_html(item[1]))- scores.append(item[2])- elif len(item) == 2 and isinstance(item[1], tuple):- boxes.append(item[0])- texts.append(escape_html(item[1][0]))- scores.append(item[1][1])- ocr_results.append((boxes, texts, scores))- table_results = self.table_model(img_contents=img_contents, ocr_results=ocr_results, batch_size=batch_size)-- for i, result in enumerate(table_results.pred_htmls):- if result:- not_none_table_res_list[i]['table_res']['html'] = result--if __name__ == '__main__':- ocr_engine= PytorchPaddleOCR(- det_db_box_thresh=0.5,- det_db_unclip_ratio=1.6,- enable_merge_det_boxes=False,- )- table_model = RapidTableModel(ocr_engine)- img_path = Path(r"D:\project\20240729ocrtest\pythonProject\images\601c939cc6dabaf07af763e2f935f54896d0251f37cc47beb7fc6b069353455d.jpg")- image = cv2.imread(str(img_path))- html_code, table_cell_bboxes, logic_points, elapse = table_model.predict(image)- print(html_code)-diff --git a/mineru/utils/enum_class.py b/mineru/utils/enum_class.pyindex a30c6391..4dd50861 100644--- a/mineru/utils/enum_class.py+++ b/mineru/utils/enum_class.py@@ -99,13 +99,10 @@ class ModelPath:vlm_root_modelscope = "OpenDataLab/MinerU2.5-2509-1.2B"pipeline_root_modelscope = "OpenDataLab/PDF-Extract-Kit-1.0"pipeline_root_hf = "opendatalab/PDF-Extract-Kit-1.0"- doclayout_yolo = "models/Layout/YOLO/doclayout_yolo_docstructbench_imgsz1280_2501.pt"pp_doclayout_v2 = "models/Layout/PP-DocLayoutV2"- yolo_v8_mfd = "models/MFD/YOLO/yolo_v8_ft.pt"unimernet_small = "models/MFR/unimernet_hf_small_2503"pp_formulanet_plus_m = "models/MFR/pp_formulanet_plus_m"pytorch_paddle = "models/OCR/paddleocr_torch"- layout_reader = "models/ReadingOrder/layout_reader"slanet_plus = "models/TabRec/SlanetPlus/slanet-plus.onnx"unet_structure = "models/TabRec/UnetStructure/unet.onnx"paddle_table_cls = "models/TabCls/paddle_table_cls/PP-LCNet_x1_0_table_cls.onnx"diff --git a/mineru/utils/model_utils.py b/mineru/utils/model_utils.pyindex 06507150..94d991c4 100644--- a/mineru/utils/model_utils.py+++ b/mineru/utils/model_utils.py@@ -5,19 +5,50 @@ from PIL import Imagefrom loguru import loggerimport numpy as np-from mineru.utils.boxbase import get_minbox_if_overlap_by_ratio-try:import torchimport torch_npuexcept ImportError:pass+TEXT_REGION_LABELS = {+ "abstract",+ "algorithm",+ "aside_text",+ "content",+ "doc_title",+ "figure_title",+ "footer",+ "footnote",+ "formula_number",+ "header",+ "number",+ "paragraph_title",+ "reference",+ "reference_content",+ "text",+ "vision_footnote",+}+++def _get_bbox(item):+ bbox = item.get("bbox")+ if bbox is not None:+ xmin, ymin, xmax, ymax = bbox+ return float(xmin), float(ymin), float(xmax), float(ymax)+++def _get_int_bbox(item):+ xmin, ymin, xmax, ymax = _get_bbox(item)+ return int(xmin), int(ymin), int(xmax), int(ymax)-def crop_img(input_res, input_img, crop_paste_x=0, crop_paste_y=0):- crop_xmin, crop_ymin = int(input_res['poly'][0]), int(input_res['poly'][1])- crop_xmax, crop_ymax = int(input_res['poly'][4]), int(input_res['poly'][5])+def _set_bbox(item, bbox):+ item["bbox"] = [float(bbox[0]), float(bbox[1]), float(bbox[2]), float(bbox[3])]+++def crop_img(input_res, input_img, crop_paste_x=0, crop_paste_y=0):+ crop_xmin, crop_ymin, crop_xmax, crop_ymax = _get_int_bbox(input_res)# Calculate new dimensionscrop_new_width = crop_xmax - crop_xmin + crop_paste_x * 2@@ -49,8 +80,7 @@ def crop_img(input_res, input_img, crop_paste_x=0, crop_paste_y=0):def get_coords_and_area(block_with_poly):"""Extract coordinates and area from a table."""- xmin, ymin = int(block_with_poly['poly'][0]), int(block_with_poly['poly'][1])- xmax, ymax = int(block_with_poly['poly'][4]), int(block_with_poly['poly'][5])+ xmin, ymin, xmax, ymax = _get_bbox(block_with_poly)area = (xmax - xmin) * (ymax - ymin)return xmin, ymin, xmax, ymax, area@@ -69,22 +99,6 @@ def calculate_intersection(box1, box2):return intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax-def calculate_iou(box1, box2):- """Calculate IoU between two boxes."""- intersection = calculate_intersection(box1[:4], box2[:4])-- if not intersection:- return 0-- intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax = intersection- intersection_area = (intersection_xmax - intersection_xmin) * (intersection_ymax - intersection_ymin)-- area1, area2 = box1[4], box2[4]- union_area = area1 + area2 - intersection_area-- return intersection_area / union_area if union_area > 0 else 0--def is_inside(small_box, big_box, overlap_threshold=0.8):"""Check if small_box is inside big_box by at least overlap_threshold."""intersection = calculate_intersection(small_box[:4], big_box[:4])@@ -99,318 +113,71 @@ def is_inside(small_box, big_box, overlap_threshold=0.8):return intersection_area >= overlap_threshold * small_box[4]-def do_overlap(box1, box2):- """Check if two boxes overlap."""- return calculate_intersection(box1[:4], box2[:4]) is not None---def merge_high_iou_tables(table_res_list, layout_res, table_indices, iou_threshold=0.7):- """Merge tables with IoU > threshold."""- if len(table_res_list) < 2:- return table_res_list, table_indices-- table_info = [get_coords_and_area(table) for table in table_res_list]- merged = True-- while merged:- merged = False- i = 0- while i < len(table_res_list) - 1:- j = i + 1- while j < len(table_res_list):- iou = calculate_iou(table_info[i], table_info[j])-- if iou > iou_threshold:- # Merge tables by taking their union- x1_min, y1_min, x1_max, y1_max, _ = table_info[i]- x2_min, y2_min, x2_max, y2_max, _ = table_info[j]-- union_xmin = min(x1_min, x2_min)- union_ymin = min(y1_min, y2_min)- union_xmax = max(x1_max, x2_max)- union_ymax = max(y1_max, y2_max)-- # Create merged table- merged_table = table_res_list[i].copy()- merged_table['poly'] = [- union_xmin, union_ymin, union_xmax, union_ymin,- union_xmax, union_ymax, union_xmin, union_ymax- ]- # Update layout_res- to_remove = [table_indices[j], table_indices[i]]- for idx in sorted(to_remove, reverse=True):- del layout_res[idx]- layout_res.append(merged_table)-- # Update tracking lists- table_indices = [k if k < min(to_remove) else- k - 1 if k < max(to_remove) else- k - 2 if k > max(to_remove) else- len(layout_res) - 1- for k in table_indices- if k not in to_remove]- table_indices.append(len(layout_res) - 1)-- # Update table lists- table_res_list.pop(j)- table_res_list.pop(i)- table_res_list.append(merged_table)-- # Update table_info- table_info = [get_coords_and_area(table) for table in table_res_list]-- merged = True- break- j += 1-- if merged:- break- i += 1-- return table_res_list, table_indices---def filter_nested_tables(table_res_list, overlap_threshold=0.8, area_threshold=0.8):- """Remove big tables containing multiple smaller tables within them."""- if len(table_res_list) < 3:- return table_res_list+def remove_nested_ocr_text_blocks(+ ocr_res_list,+ layout_res,+ overlap_threshold=0.8,+ min_area_ratio=1.01,+):+ """Remove OCR candidate text blocks that are contained by any larger layout block."""+ if not ocr_res_list or len(layout_res) < 2:+ return ocr_res_list, []- table_info = [get_coords_and_area(table) for table in table_res_list]- big_tables_idx = []-- for i in range(len(table_res_list)):- # Find tables inside this one- tables_inside = [j for j in range(len(table_res_list))- if i != j and is_inside(table_info[j], table_info[i], overlap_threshold)]-- # Continue if there are at least 3 tables inside- if len(tables_inside) >= 3:- # Check if inside tables overlap with each other- tables_overlap = any(do_overlap(table_info[tables_inside[idx1]], table_info[tables_inside[idx2]])- for idx1 in range(len(tables_inside))- for idx2 in range(idx1 + 1, len(tables_inside)))-- # If no overlaps, check area condition- if not tables_overlap:- total_inside_area = sum(table_info[j][4] for j in tables_inside)- big_table_area = table_info[i][4]-- if total_inside_area > area_threshold * big_table_area:- big_tables_idx.append(i)-- return [table for i, table in enumerate(table_res_list) if i not in big_tables_idx]---def remove_overlaps_min_blocks(res_list):-- for res in res_list:- res['bbox'] = [int(res['poly'][0]), int(res['poly'][1]), int(res['poly'][4]), int(res['poly'][5])]-- # 重叠block,小的不能直接删除,需要和大的那个合并成一个更大的。- # 删除重叠blocks中较小的那些- need_remove = []- for i in range(len(res_list)):- # 如果当前元素已在需要移除列表中,则跳过- if res_list[i] in need_remove:- continue+ layout_info = [(block, get_coords_and_area(block)) for block in layout_res]+ blocks_to_remove = []- for j in range(i + 1, len(res_list)):- # 如果比较对象已在需要移除列表中,则跳过- if res_list[j] in need_remove:+ for text_block in ocr_res_list:+ text_box = get_coords_and_area(text_block)+ text_area = text_box[4]+ for parent_block, parent_box in layout_info:+ if parent_block is text_block:continue+ if parent_box[4] <= text_area * min_area_ratio:+ continue+ if is_inside(text_box, parent_box, overlap_threshold):+ blocks_to_remove.append(text_block)+ break- overlap_box = get_minbox_if_overlap_by_ratio(- res_list[i]['bbox'], res_list[j]['bbox'], 0.8- )-- if overlap_box is not None:-- # 根据重叠框确定哪个是小块,哪个是大块- if overlap_box == res_list[i]['bbox']:- small_res, large_res = res_list[i], res_list[j]- elif overlap_box == res_list[j]['bbox']:- small_res, large_res = res_list[j], res_list[i]- else:- continue # 如果重叠框与任一块都不匹配,跳过处理-- if small_res['score'] <= large_res['score']:- # 如果小块的分数低于大块,则小块为需要移除的块- if small_res is not None and small_res not in need_remove:- # 更新大块的边界为两者的并集- x1, y1, x2, y2 = large_res['bbox']- sx1, sy1, sx2, sy2 = small_res['bbox']- x1 = min(x1, sx1)- y1 = min(y1, sy1)- x2 = max(x2, sx2)- y2 = max(y2, sy2)- large_res['bbox'] = [x1, y1, x2, y2]- need_remove.append(small_res)- else:- # 如果大块的分数低于小块,则大块为需要移除的块, 这时不需要更新小块的边界- if large_res is not None and large_res not in need_remove:- need_remove.append(large_res)-- # 从列表中移除标记的元素- for res in need_remove:- res_list.remove(res)- del res['bbox'] # 删除bbox字段-- for res in res_list:- # 将res的poly使用bbox重构- res['poly'] = [res['bbox'][0], res['bbox'][1], res['bbox'][2], res['bbox'][1],- res['bbox'][2], res['bbox'][3], res['bbox'][0], res['bbox'][3]]- # 删除res的bbox- del res['bbox']-- return res_list, need_remove---def remove_overlaps_low_confidence_blocks(combined_res_list, overlap_threshold=0.8):- """- Remove low-confidence blocks that overlap with other blocks.-- This function identifies and removes blocks with low confidence scores that overlap- with other blocks. It calculates the coordinates and area of each block, and checks- for overlaps based on a specified threshold. Blocks that meet the criteria for removal- are returned in a list.-- Parameters:- combined_res_list (list): A list of blocks, where each block is a dictionary containing- keys like 'poly' (polygon coordinates) and optionally 'score' (confidence score).- overlap_threshold (float): The threshold for determining overlap between blocks. Default is 0.8.-- Returns:- list: A list of blocks to be removed, based on the overlap and confidence criteria.- """- # 计算每个block的坐标和面积- block_info = []- for block in combined_res_list:- xmin, ymin = int(block['poly'][0]), int(block['poly'][1])- xmax, ymax = int(block['poly'][4]), int(block['poly'][5])- area = (xmax - xmin) * (ymax - ymin)- score = block.get('score', 0.5) # 如果没有score字段,默认为0.5- block_info.append((xmin, ymin, xmax, ymax, area, score, block))-- blocks_to_remove = []- marked_indices = set() # 跟踪已标记为删除的block索引-- # 检查每个block内部是否有3个及以上的小block- for i, (xmin, ymin, xmax, ymax, area, score, block) in enumerate(block_info):- # 如果当前block已标记为删除,则跳过- if i in marked_indices:- continue-- # 查找内部的小block (仅考虑尚未被标记为删除的block)- blocks_inside = [(j, j_score, j_block) for j, (xj_min, yj_min, xj_max, yj_max, j_area, j_score, j_block) in- enumerate(block_info)- if i != j and j not in marked_indices and is_inside(block_info[j], block_info[i],- overlap_threshold)]-- # 如果内部有3个及以上的小block- if len(blocks_inside) >= 2:- # 计算小block的平均分数- avg_score = sum(s for _, s, _ in blocks_inside) / len(blocks_inside)-- # 比较大block的分数和小block的平均分数- if score > avg_score:- # 保留大block,扩展其边界- # 首先将所有小block标记为要删除- for j, _, j_block in blocks_inside:- if j_block not in blocks_to_remove:- blocks_to_remove.append(j_block)- marked_indices.add(j) # 标记索引为已处理-- # 扩展大block的边界以包含所有小block- new_xmin, new_ymin, new_xmax, new_ymax = xmin, ymin, xmax, ymax- for _, _, j_block in blocks_inside:- j_xmin, j_ymin = int(j_block['poly'][0]), int(j_block['poly'][1])- j_xmax, j_ymax = int(j_block['poly'][4]), int(j_block['poly'][5])- new_xmin = min(new_xmin, j_xmin)- new_ymin = min(new_ymin, j_ymin)- new_xmax = max(new_xmax, j_xmax)- new_ymax = max(new_ymax, j_ymax)-- # 更新大block的边界- block['poly'][0] = block['poly'][6] = new_xmin- block['poly'][1] = block['poly'][3] = new_ymin- block['poly'][2] = block['poly'][4] = new_xmax- block['poly'][5] = block['poly'][7] = new_ymax- else:- # 保留小blocks,删除大block- blocks_to_remove.append(block)- marked_indices.add(i) # 标记当前索引为已处理- return blocks_to_remove+ remove_ids = {id(block) for block in blocks_to_remove}+ filtered_ocr_res_list = [+ block for block in ocr_res_list if id(block) not in remove_ids+ ]+ return filtered_ocr_res_list, blocks_to_remove-def get_res_list_from_layout_res(layout_res, iou_threshold=0.7, overlap_threshold=0.8, area_threshold=0.8):+def get_res_list_from_layout_res(layout_res, overlap_threshold=0.8):"""Extract OCR, table and other regions from layout results."""ocr_res_list = []text_res_list = []table_res_list = []- table_indices = []single_page_mfdetrec_res = []# Categorize regionsfor i, res in enumerate(layout_res):- category_id = int(res['category_id'])+ label = res.get("label")- if category_id in [13, 14]: # Formula regions+ if label == "formula":+ xmin, ymin, xmax, ymax = _get_bbox(res)single_page_mfdetrec_res.append({- "bbox": [int(res['poly'][0]), int(res['poly'][1]),- int(res['poly'][4]), int(res['poly'][5])],+ "bbox": [xmin, ymin, xmax, ymax],})- elif category_id in [0, 2, 4, 6, 7, 3]: # OCR regions- ocr_res_list.append(res)- elif category_id == 5: # Table regions+ elif label == "table":table_res_list.append(res)- table_indices.append(i)- elif category_id in [1]: # Text regions+ elif label in TEXT_REGION_LABELS:text_res_list.append(res)- # Process tables: merge high IoU tables first, then filter nested tables- table_res_list, table_indices = merge_high_iou_tables(- table_res_list, layout_res, table_indices, iou_threshold)-- filtered_table_res_list = filter_nested_tables(- table_res_list, overlap_threshold, area_threshold)-- filtered_table_res_list, table_need_remove = remove_overlaps_min_blocks(filtered_table_res_list)-- for res in table_need_remove:- if res in layout_res:- layout_res.remove(res)-- # Remove filtered out tables from layout_res- if len(filtered_table_res_list) < len(table_res_list):- kept_tables = set(id(table) for table in filtered_table_res_list)- tables_to_remove = [table for table in table_res_list if id(table) not in kept_tables]- for table in tables_to_remove:- if table in layout_res:- layout_res.remove(table)-- # Remove overlaps in OCR and text regions- text_res_list, need_remove = remove_overlaps_min_blocks(text_res_list)-ocr_res_list.extend(text_res_list)- for res in need_remove:- if res in layout_res:- layout_res.remove(res)-- # 检测大block内部是否包含多个小block, 合并ocr和table列表进行检测- combined_res_list = ocr_res_list + filtered_table_res_list- blocks_to_remove = remove_overlaps_low_confidence_blocks(combined_res_list, overlap_threshold)- # 移除需要删除的blocks- for block in blocks_to_remove:- if block in ocr_res_list:- ocr_res_list.remove(block)- elif block in filtered_table_res_list:- filtered_table_res_list.remove(block)- # 同时从layout_res中删除- if block in layout_res:- layout_res.remove(block)+ ocr_res_list, nested_text_need_remove = remove_nested_ocr_text_blocks(+ ocr_res_list,+ layout_res,+ overlap_threshold=overlap_threshold,+ )+ nested_remove_ids = {id(res) for res in nested_text_need_remove}+ if nested_remove_ids:+ layout_res[:] = [res for res in layout_res if id(res) not in nested_remove_ids]- return ocr_res_list, filtered_table_res_list, single_page_mfdetrec_res+ return ocr_res_list, table_res_list, single_page_mfdetrec_resdef clean_memory(device='cuda'):@@ -444,7 +211,7 @@ def clean_vram(device, vram_threshold=8):gc_start = time.time()clean_memory(device)gc_time = round(time.time() - gc_start, 2)- # logger.info(f"gc time: {gc_time}")+ logger.debug(f"gc time: {gc_time}")def get_vram(device) -> int:diff --git a/mineru/utils/ocr_utils.py b/mineru/utils/ocr_utils.pyindex 9b92a9c0..58767583 100644--- a/mineru/utils/ocr_utils.py+++ b/mineru/utils/ocr_utils.py@@ -330,11 +330,19 @@ def get_adjusted_mfdetrec_res(single_page_mfdetrec_res, useful_list):return adjusted_mfdetrec_res-def get_ocr_result_list(ocr_res, useful_list, ocr_enable, bgr_image, lang):+def get_ocr_result_list(+ ocr_res,+ useful_list,+ ocr_enable,+ bgr_image,+ lang,+):paste_x, paste_y, xmin, ymin, xmax, ymax, new_width, new_height = useful_listocr_result_list = []ori_im = bgr_image.copy()for box_ocr_res in ocr_res:+ img_crop = None+ need_ocr_rec = Falseif len(box_ocr_res) == 2:p1, p2, p3, p4 = box_ocr_res[0]@@ -349,6 +357,7 @@ def get_ocr_result_list(ocr_res, useful_list, ocr_enable, bgr_image, lang):if ocr_enable:tmp_box = copy.deepcopy(np.array([p1, p2, p3, p4]).astype('float32'))img_crop = get_rotate_crop_image(ori_im, tmp_box)+ need_ocr_rec = True# average_angle_degrees = calculate_angle_degrees(box_ocr_res[0])# if average_angle_degrees > 0.5:@@ -377,22 +386,24 @@ def get_ocr_result_list(ocr_res, useful_list, ocr_enable, bgr_image, lang):p3 = [p3[0] - paste_x + xmin, p3[1] - paste_y + ymin]p4 = [p4[0] - paste_x + xmin, p4[1] - paste_y + ymin]- if ocr_enable:- ocr_result_list.append({- 'category_id': 15,- 'poly': p1 + p2 + p3 + p4,- 'score': 1,- 'text': text,- 'np_img': img_crop,- 'lang': lang,- })- else:- ocr_result_list.append({- 'category_id': 15,- 'poly': p1 + p2 + p3 + p4,- 'score': float(round(score, 2)),- 'text': text,- })+ bbox = [+ float(round(p1[0], 4)),+ float(round(p1[1], 4)),+ float(round(p3[0], 4)),+ float(round(p3[1], 4)),+ ]++ ocr_item = {+ "label": "ocr_text",+ "bbox": bbox,+ "score": 1.0 if ocr_enable else float(round(score, 2)),+ "text": text,+ }+ if need_ocr_rec:+ ocr_item["np_img"] = img_crop+ ocr_item["lang"] = lang+ ocr_item["_need_ocr_rec"] = True+ ocr_result_list.append(ocr_item)return ocr_result_list@@ -456,4 +467,4 @@ def get_rotate_crop_image(img, points):rotate_radio = 2if dst_img_height * 1.0 / dst_img_width >= rotate_radio:dst_img = np.rot90(dst_img)- return dst_img\ No newline at end of file+ return dst_img