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: optimize batch processing and inference mode for improved performance
myhloli57639ebd45dd
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.pyindex 96434e7a..8dff3bbf 100644--- a/mineru/backend/hybrid/hybrid_analyze.py+++ b/mineru/backend/hybrid/hybrid_analyze.py@@ -257,63 +257,39 @@ def ocr_det(bgr_image, det_image, useful_list, adjusted_mfdetrec_res, ocr_res_list[-1]))- # 按分辨率分组并同时完成padding- RESOLUTION_GROUP_STRIDE = 64 # 32-- resolution_groups = defaultdict(list)- for crop_info in all_cropped_images_info:- cropped_img = crop_info[1]- h, w = cropped_img.shape[:2]- # 直接计算目标尺寸并用作分组键- target_h = ((h + RESOLUTION_GROUP_STRIDE - 1) // RESOLUTION_GROUP_STRIDE) * RESOLUTION_GROUP_STRIDE- target_w = ((w + RESOLUTION_GROUP_STRIDE - 1) // RESOLUTION_GROUP_STRIDE) * RESOLUTION_GROUP_STRIDE- group_key = (target_h, target_w)- resolution_groups[group_key].append(crop_info)-- # 对每个分辨率组进行批处理- for (target_h, target_w), group_crops in tqdm(resolution_groups.items(), desc="OCR-det"):- # 对所有图像进行padding到统一尺寸- batch_images = []- for crop_info in group_crops:- img = crop_info[1]- h, w = img.shape[:2]- # 创建目标尺寸的白色背景- padded_img = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255- padded_img[:h, :w] = img- batch_images.append(padded_img)-- # 批处理检测- det_batch_size = min(len(batch_images), batch_ratio * OCR_DET_BASE_BATCH_SIZE)- batch_results = run_ocr_inference(- hybrid_pipeline_model.ocr_model.text_detector.batch_predict,- batch_images,- det_batch_size,- )+ batch_images = [crop_info[1] for crop_info in all_cropped_images_info]+ det_batch_size = min(len(batch_images), batch_ratio * OCR_DET_BASE_BATCH_SIZE)+ batch_results = run_ocr_inference(+ hybrid_pipeline_model.ocr_model.text_detector.batch_predict,+ batch_images,+ det_batch_size,+ tqdm_enable=True,+ tqdm_desc="OCR-det",+ )- # 处理批处理结果- for crop_info, (dt_boxes, _) in zip(group_crops, batch_results):- bgr_image, _det_image, useful_list, adjusted_mfdetrec_res, ocr_page_res_list = crop_info-- if dt_boxes is not None and len(dt_boxes) > 0:- # 处理检测框- dt_boxes_sorted = sorted_boxes(dt_boxes)- dt_boxes_merged = merge_det_boxes(dt_boxes_sorted) if dt_boxes_sorted else []-- # 根据公式位置更新检测框- dt_boxes_final = (update_det_boxes(dt_boxes_merged, adjusted_mfdetrec_res)- if dt_boxes_merged and adjusted_mfdetrec_res- else dt_boxes_merged)-- 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,- False,- bgr_image,- hybrid_pipeline_model.lang,- )- ocr_page_res_list.extend(ocr_result_list)+ for crop_info, (dt_boxes, _) in zip(all_cropped_images_info, batch_results):+ bgr_image, _det_image, useful_list, adjusted_mfdetrec_res, ocr_page_res_list = crop_info++ if dt_boxes is not None and len(dt_boxes) > 0:+ # 处理检测框+ dt_boxes_sorted = sorted_boxes(dt_boxes)+ dt_boxes_merged = merge_det_boxes(dt_boxes_sorted) if dt_boxes_sorted else []++ # 根据公式位置更新检测框+ dt_boxes_final = (update_det_boxes(dt_boxes_merged, adjusted_mfdetrec_res)+ if dt_boxes_merged and adjusted_mfdetrec_res+ else dt_boxes_merged)++ 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,+ False,+ bgr_image,+ hybrid_pipeline_model.lang,+ )+ ocr_page_res_list.extend(ocr_result_list)return ocr_res_listdiff --git a/mineru/backend/pipeline/batch_analyze.py b/mineru/backend/pipeline/batch_analyze.pyindex a0420304..5ea2cba8 100644--- a/mineru/backend/pipeline/batch_analyze.py+++ b/mineru/backend/pipeline/batch_analyze.py@@ -687,69 +687,48 @@ class BatchAnalyze:lang=lang)- # 按分辨率分组并同时完成padding- # RESOLUTION_GROUP_STRIDE = 32- RESOLUTION_GROUP_STRIDE = 64-- resolution_groups = defaultdict(list)- for crop_info in lang_crop_list:- cropped_img = crop_info[1]- h, w = cropped_img.shape[:2]- # 直接计算目标尺寸并用作分组键- target_h = ((h + RESOLUTION_GROUP_STRIDE - 1) // RESOLUTION_GROUP_STRIDE) * RESOLUTION_GROUP_STRIDE- target_w = ((w + RESOLUTION_GROUP_STRIDE - 1) // RESOLUTION_GROUP_STRIDE) * RESOLUTION_GROUP_STRIDE- group_key = (target_h, target_w)- resolution_groups[group_key].append(crop_info)-- # 对每个分辨率组进行批处理- for (target_h, target_w), group_crops in tqdm(resolution_groups.items(), desc=f"OCR-det {lang}"):- # 对所有图像进行padding到统一尺寸- batch_images = []- for crop_info in group_crops:- img = crop_info[1]- h, w = img.shape[:2]- # 创建目标尺寸的白色背景- padded_img = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255- padded_img[:h, :w] = img- batch_images.append(padded_img)-- # 批处理检测- det_batch_size = min(len(batch_images), self.batch_ratio * OCR_DET_BASE_BATCH_SIZE)- batch_results = run_ocr_inference(- ocr_model.text_detector.batch_predict, batch_images, det_batch_size- )+ batch_images = [crop_info[1] for crop_info in lang_crop_list]+ det_batch_size = min(+ len(batch_images), self.batch_ratio * OCR_DET_BASE_BATCH_SIZE+ )+ batch_results = run_ocr_inference(+ ocr_model.text_detector.batch_predict,+ batch_images,+ det_batch_size,+ tqdm_enable=True,+ tqdm_desc=f"OCR-det {lang}",+ )- # 处理批处理结果- for crop_info, (dt_boxes, _) in zip(group_crops, batch_results):- (- bgr_image,- _det_image,- useful_list,- ocr_res_list_dict,- adjusted_mfdetrec_res,- _lang,- ) = crop_info-- if dt_boxes is not None and len(dt_boxes) > 0:- # 处理检测框- dt_boxes_sorted = sorted_boxes(dt_boxes)- dt_boxes_merged = merge_det_boxes(dt_boxes_sorted) if dt_boxes_sorted else []-- # 根据公式位置更新检测框- dt_boxes_final = (update_det_boxes(dt_boxes_merged, adjusted_mfdetrec_res)- if dt_boxes_merged and adjusted_mfdetrec_res- else dt_boxes_merged)-- 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_list_dict['layout_res'].extend(ocr_result_list)+ for crop_info, (dt_boxes, _) in zip(lang_crop_list, batch_results):+ (+ bgr_image,+ _det_image,+ useful_list,+ ocr_res_list_dict,+ adjusted_mfdetrec_res,+ _lang,+ ) = crop_info++ if dt_boxes is not None and len(dt_boxes) > 0:+ # 处理检测框+ dt_boxes_sorted = sorted_boxes(dt_boxes)+ dt_boxes_merged = merge_det_boxes(dt_boxes_sorted) if dt_boxes_sorted else []++ # 根据公式位置更新检测框+ dt_boxes_final = (update_det_boxes(dt_boxes_merged, adjusted_mfdetrec_res)+ if dt_boxes_merged and adjusted_mfdetrec_res+ else dt_boxes_merged)++ 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_list_dict['layout_res'].extend(ocr_result_list)# 清理显存clean_vram(self.model.device, vram_threshold=8)diff --git a/mineru/model/ocr/pytorch_paddle.py b/mineru/model/ocr/pytorch_paddle.pyindex 2cf86dc1..d8f09eba 100644--- a/mineru/model/ocr/pytorch_paddle.py+++ b/mineru/model/ocr/pytorch_paddle.py@@ -245,7 +245,7 @@ class PytorchPaddleOCR(TextSystem):logger.debug("no valid image provided")return None, None- ori_im = img.copy()+ ori_im = imgdt_boxes, elapse = self.text_detector(img)if dt_boxes is None:diff --git a/mineru/model/utils/pytorchocr/base_ocr_v20.py b/mineru/model/utils/pytorchocr/base_ocr_v20.pyindex d4177bd0..96af9ef6 100644--- a/mineru/model/utils/pytorchocr/base_ocr_v20.py+++ b/mineru/model/utils/pytorchocr/base_ocr_v20.py@@ -107,6 +107,6 @@ class BaseOCRV20:# print('model is loaded: {}'.format(weights_path))def inference(self, inputs):- with torch.no_grad():+ with torch.inference_mode():infer = self.net(inputs)return inferdiff --git a/mineru/model/utils/pytorchocr/modeling/heads/rec_multi_head.py b/mineru/model/utils/pytorchocr/modeling/heads/rec_multi_head.pyindex 47cebc10..ebcabf3a 100644--- a/mineru/model/utils/pytorchocr/modeling/heads/rec_multi_head.py+++ b/mineru/model/utils/pytorchocr/modeling/heads/rec_multi_head.py@@ -1,5 +1,4 @@# Copyright (c) Opendatalab. All rights reserved.-import torch.nn.functional as Ffrom torch import nnfrom ..necks.rnn import EncoderWithLightSVTR, Im2Seq, SequenceEncoder@@ -71,7 +70,8 @@ class MultiHead(nn.Module):ctc_encoder = ctc_encoder.squeeze(dim=2).permute(0, 2, 1)predicts = self.head(ctc_encoder)if not self.training:- predicts = F.softmax(predicts, dim=2)+ # 推理阶段保留 raw logits,交给 CTC 解码端按需计算 max 概率,避免整块 softmax 矩阵搬运。+ return {"ctc_logits": predicts, "ctc_use_raw_logits": True}return predictsctc_encoder = self.ctc_encoder(x)return self.ctc_head(ctc_encoder)diff --git a/mineru/model/utils/pytorchocr/postprocess/rec_postprocess.py b/mineru/model/utils/pytorchocr/postprocess/rec_postprocess.pyindex e4cd4b06..d1400455 100644--- a/mineru/model/utils/pytorchocr/postprocess/rec_postprocess.py+++ b/mineru/model/utils/pytorchocr/postprocess/rec_postprocess.py@@ -181,11 +181,33 @@ class CTCLabelDecode(BaseRecLabelDecode):super(CTCLabelDecode, self).__init__(character_dict_path,use_space_char)+ def _decode_raw_logits(self, preds):+ """从 raw logits 直接计算 CTC argmax 和 max softmax 概率,避免完整 softmax。"""+ logits = preds["ctc_logits"]+ if torch.is_tensor(logits):+ preds_idx = logits.argmax(dim=2)+ max_logits = logits.amax(dim=2)+ preds_prob = torch.exp(max_logits - torch.logsumexp(logits, dim=2))+ return preds_prob.float().cpu().numpy(), preds_idx.cpu().numpy()++ logits = np.asarray(logits)+ preds_idx = logits.argmax(axis=2)+ max_logits = logits.max(axis=2)+ stable_logits = logits - max_logits[:, :, None]+ logsumexp = max_logits + np.log(np.exp(stable_logits).sum(axis=2))+ preds_prob = np.exp(max_logits - logsumexp).astype(np.float32)+ return preds_prob, preds_idx+def __call__(self, preds, label=None, return_word_box=False, *args, **kwargs):- preds_prob, preds_idx = preds.max(axis=2)+ if isinstance(preds, dict) and preds.get("ctc_use_raw_logits"):+ preds_prob, preds_idx = self._decode_raw_logits(preds)+ else:+ preds_prob, preds_idx = preds.max(axis=2)+ preds_idx = preds_idx.cpu().numpy()+ preds_prob = preds_prob.float().cpu().numpy()text = self.decode(- preds_idx.cpu().numpy(),- preds_prob.float().cpu().numpy(),+ preds_idx,+ preds_prob,is_remove_duplicate=True,return_word_box=return_word_box,)@@ -787,4 +809,4 @@ class CANLabelDecode(BaseRecLabelDecode):if label is None:return textlabel = self.decode(label)- return text, label\ No newline at end of file+ return text, labeldiff --git a/mineru/model/utils/tools/infer/predict_cls.py b/mineru/model/utils/tools/infer/predict_cls.pyindex 5e08151d..f4ca6444 100644--- a/mineru/model/utils/tools/infer/predict_cls.py+++ b/mineru/model/utils/tools/infer/predict_cls.py@@ -86,11 +86,10 @@ class TextClassifier(BaseOCRV20):norm_img = self.resize_norm_img(img_list[indices[ino]])norm_img = norm_img[np.newaxis, :]norm_img_batch.append(norm_img)- norm_img_batch = np.concatenate(norm_img_batch)- norm_img_batch = norm_img_batch.copy()+ norm_img_batch = np.ascontiguousarray(np.concatenate(norm_img_batch))starttime = time.time()- with torch.no_grad():+ with torch.inference_mode():inp = torch.from_numpy(norm_img_batch)inp = inp.to(self.device)inp = self._to_inference_dtype(inp)diff --git a/mineru/model/utils/tools/infer/predict_det.py b/mineru/model/utils/tools/infer/predict_det.pyindex f846c740..ec1e84e2 100644--- a/mineru/model/utils/tools/infer/predict_det.py+++ b/mineru/model/utils/tools/infer/predict_det.py@@ -1,9 +1,11 @@# Copyright (c) Opendatalab. All rights reserved.import sys+from collections import defaultdictimport numpy as npimport timeimport torch+from tqdm import tqdmfrom ...pytorchocr.base_ocr_v20 import BaseOCRV20from . import pytorchocr_utility as utilityfrom ...pytorchocr.data import create_operators, transform@@ -124,70 +126,21 @@ 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):- """- 对相同尺寸的图像进行批处理-- Args:- img_list: 相同尺寸的图像列表-- Returns:- batch_results: 批处理结果列表- total_elapse: 总耗时- """- starttime = time.time()-- # 预处理所有图像- batch_data = []- batch_shapes = []- ori_imgs = []-- for img in img_list:- ori_im = img.copy()- ori_imgs.append(ori_im)-- data = {'image': img}- data = transform(data, self.preprocess_op)- if data is None:- # 如果预处理失败,返回空结果- return [(None, 0) for _ in img_list], 0+ def _preprocess_det_image(self, img):+ """执行 OCR-det 单图预处理,并保留后处理需要的原始尺寸信息。"""+ data = {'image': img}+ data = transform(data, self.preprocess_op)+ if data is None:+ return None- img_processed, shape_list = data- batch_data.append(img_processed)- batch_shapes.append(shape_list)+ img_processed, shape_list = data+ if img_processed is None:+ return None- # 堆叠成批处理张量- try:- batch_tensor = np.stack(batch_data, axis=0)- batch_shapes = np.stack(batch_shapes, axis=0)- except Exception as e:- # 如果堆叠失败,回退到逐个处理- batch_results = []- for img in img_list:- dt_boxes, elapse = self.__call__(img)- batch_results.append((dt_boxes, elapse))- return batch_results, time.time() - starttime+ return np.ascontiguousarray(img_processed), shape_list, img.shape- # 批处理推理- with torch.no_grad():- inp = torch.from_numpy(batch_tensor)- inp = inp.to(self.device)- inp = self._to_inference_dtype(inp)- outputs = self.net(inp)-- # 处理输出+ def _build_det_preds(self, outputs):+ """将模型输出统一转换为后处理需要的 float32 numpy 结构。"""preds = {}if self.det_algorithm == "EAST":preds['f_geo'] = outputs['f_geo'].float().cpu().numpy()@@ -200,42 +153,116 @@ class TextDetector(BaseOCRV20):elif self.det_algorithm in ['DB', 'PSE', 'DB++']:preds['maps'] = outputs['maps'].float().cpu().numpy()elif self.det_algorithm == 'FCE':- for i, (k, output) in enumerate(outputs.items()):+ for i, (_k, output) in enumerate(outputs.items()):preds['level_{}'.format(i)] = output.float().cpu().numpy()else:raise NotImplementedError+ return preds- # 后处理每个图像的结果+ def _postprocess_det_batch(self, preds, batch_shapes, ori_shapes):+ """对完整 batch 执行一次 OCR-det 后处理,再逐张裁剪过滤检测框。"""+ post_results = self.postprocess_op(preds, batch_shapes)batch_results = []- total_elapse = time.time() - starttime+ for post_result, ori_shape in zip(post_results, ori_shapes):+ dt_boxes = post_result['points']+ dt_boxes = self._filter_det_res(dt_boxes, ori_shape)+ batch_results.append(dt_boxes)+ return batch_results- for i in range(len(img_list)):- # 提取单个图像的预测结果- single_preds = {}- for key, value in preds.items():- if isinstance(value, np.ndarray):- single_preds[key] = value[i:i + 1] # 保持批次维度- else:- single_preds[key] = value+ def _batch_process_preprocessed(self, batch_items):+ """对已经完成预处理且形状一致的图片执行批量推理。"""+ starttime = time.time()+ if not batch_items:+ return [], 0- # 后处理- post_result = self.postprocess_op(single_preds, batch_shapes[i:i + 1])- dt_boxes = post_result[0]['points']+ batch_data = [item[1] for item in batch_items]+ batch_shapes = [item[2] for item in batch_items]+ ori_shapes = [item[3] for item in batch_items]- # 过滤和裁剪检测框- dt_boxes = self._filter_det_res(dt_boxes, ori_imgs[i].shape)+ try:+ batch_tensor = np.ascontiguousarray(np.stack(batch_data, axis=0))+ batch_shapes = np.stack(batch_shapes, axis=0)+ except Exception:+ batch_results = []+ for _index, img_processed, shape_list, ori_shape in batch_items:+ single_tensor = np.expand_dims(np.ascontiguousarray(img_processed), axis=0)+ single_shape = np.expand_dims(shape_list, axis=0)+ with torch.inference_mode():+ inp = torch.from_numpy(single_tensor)+ inp = inp.to(self.device)+ inp = self._to_inference_dtype(inp)+ outputs = self.net(inp)+ preds = self._build_det_preds(outputs)+ dt_boxes = self._postprocess_det_batch(preds, single_shape, [ori_shape])[0]+ batch_results.append((dt_boxes, 0))+ return batch_results, time.time() - starttime- batch_results.append((dt_boxes, total_elapse / len(img_list)))+ with torch.inference_mode():+ inp = torch.from_numpy(batch_tensor)+ inp = inp.to(self.device)+ inp = self._to_inference_dtype(inp)+ outputs = self.net(inp)+ preds = self._build_det_preds(outputs)+ dt_boxes_batch = self._postprocess_det_batch(preds, batch_shapes, ori_shapes)+ total_elapse = time.time() - starttime+ batch_elapse = total_elapse / len(batch_items)+ batch_results = [(dt_boxes, batch_elapse) for dt_boxes in dt_boxes_batch]return batch_results, total_elapse- def batch_predict(self, img_list, max_batch_size=8):+ 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):+ """+ 对相同尺寸的图像进行批处理++ Args:+ img_list: 相同尺寸的图像列表++ Returns:+ batch_results: 批处理结果列表+ total_elapse: 总耗时+ """+ starttime = time.time()++ batch_items = []+ for index, img in enumerate(img_list):+ preprocessed = self._preprocess_det_image(img)+ if preprocessed is None:+ return [(None, 0) for _ in img_list], 0+ img_processed, shape_list, ori_shape = preprocessed+ batch_items.append((index, img_processed, shape_list, ori_shape))++ batch_results, _elapsed = self._batch_process_preprocessed(batch_items)+ return batch_results, time.time() - starttime++ def batch_predict(+ self,+ img_list,+ max_batch_size=8,+ tqdm_enable=False,+ tqdm_desc="OCR-det Predict",+ tqdm_progress_bar=None,+ ):"""批处理预测方法,支持多张图像同时检测Args:img_list: 图像列表max_batch_size: 最大批处理大小+ tqdm_enable: 是否显示内部 OCR-det 进度条+ tqdm_desc: 内部 OCR-det 进度条描述+ tqdm_progress_bar: 外部复用进度条,传入时不在本方法内关闭Returns:batch_results: 批处理结果列表,每个元素为(dt_boxes, elapse)@@ -243,14 +270,38 @@ class TextDetector(BaseOCRV20):if not img_list:return []- batch_results = []+ progress_bar = tqdm_progress_bar+ should_close_progress = False+ if progress_bar is None:+ progress_bar = tqdm(total=len(img_list), desc=tqdm_desc, disable=not tqdm_enable)+ should_close_progress = True++ max_batch_size = max(1, int(max_batch_size))+ batch_results = [(None, 0)] * len(img_list)+ grouped_items = defaultdict(list)- # 分批处理- for i in range(0, len(img_list), max_batch_size):- batch_imgs = img_list[i:i + max_batch_size]- # assert尺寸一致- batch_dt_boxes, batch_elapse = self._batch_process_same_size(batch_imgs)- batch_results.extend(batch_dt_boxes)+ try:+ for index, img in enumerate(img_list):+ preprocessed = self._preprocess_det_image(img)+ if preprocessed is None:+ progress_bar.update(1)+ continue+ img_processed, shape_list, ori_shape = preprocessed+ grouped_items[img_processed.shape].append(+ (index, img_processed, shape_list, ori_shape)+ )++ for group_items in grouped_items.values():+ for i in range(0, len(group_items), max_batch_size):+ batch_items = group_items[i:i + max_batch_size]+ group_results, _batch_elapse = self._batch_process_preprocessed(batch_items)+ for batch_item, batch_result in zip(batch_items, group_results):+ original_index = batch_item[0]+ batch_results[original_index] = batch_result+ progress_bar.update(len(batch_items))+ finally:+ if should_close_progress:+ progress_bar.close()return batch_results@@ -310,43 +361,11 @@ class TextDetector(BaseOCRV20):return dt_boxes_newdef __call__(self, img):- ori_shape = img.shape- data = {'image': img}- data = transform(data, self.preprocess_op)- img, shape_list = data- if img is None:+ preprocessed = self._preprocess_det_image(img)+ if preprocessed is None:return None, 0- img = np.expand_dims(img, axis=0)- shape_list = np.expand_dims(shape_list, axis=0)- img = img.copy()- starttime = time.time()-- with torch.no_grad():- inp = torch.from_numpy(img)- inp = inp.to(self.device)- inp = self._to_inference_dtype(inp)- outputs = self.net(inp)-- preds = {}- if self.det_algorithm == "EAST":- preds['f_geo'] = outputs['f_geo'].float().cpu().numpy()- preds['f_score'] = outputs['f_score'].float().cpu().numpy()- elif self.det_algorithm == 'SAST':- preds['f_border'] = outputs['f_border'].float().cpu().numpy()- preds['f_score'] = outputs['f_score'].float().cpu().numpy()- preds['f_tco'] = outputs['f_tco'].float().cpu().numpy()- preds['f_tvo'] = outputs['f_tvo'].float().cpu().numpy()- elif self.det_algorithm in ['DB', 'PSE', 'DB++']:- preds['maps'] = outputs['maps'].float().cpu().numpy()- elif self.det_algorithm == 'FCE':- for i, (k, output) in enumerate(outputs.items()):- preds['level_{}'.format(i)] = output.float().cpu().numpy()- else:- raise NotImplementedError-- post_result = self.postprocess_op(preds, shape_list)- dt_boxes = post_result[0]['points']- dt_boxes = self._filter_det_res(dt_boxes, ori_shape)-- elapse = time.time() - starttime- return dt_boxes, elapse+ img_processed, shape_list, ori_shape = preprocessed+ batch_results, _elapsed = self._batch_process_preprocessed(+ [(0, img_processed, shape_list, ori_shape)]+ )+ return batch_results[0]diff --git a/mineru/model/utils/tools/infer/predict_rec.py b/mineru/model/utils/tools/infer/predict_rec.pyindex 944671bc..45fbcd77 100644--- a/mineru/model/utils/tools/infer/predict_rec.py+++ b/mineru/model/utils/tools/infer/predict_rec.py@@ -364,8 +364,7 @@ class TextRecognizer(BaseOCRV20):max_wh_ratio)norm_img = norm_img[np.newaxis, :]norm_img_batch.append(norm_img)- norm_img_batch = np.concatenate(norm_img_batch)- norm_img_batch = norm_img_batch.copy()+ norm_img_batch = np.ascontiguousarray(np.concatenate(norm_img_batch))if self.rec_algorithm == "SRN":starttime = time.time()@@ -376,7 +375,7 @@ class TextRecognizer(BaseOCRV20):gsrm_slf_attn_bias2_list = np.concatenate(gsrm_slf_attn_bias2_list)- with torch.no_grad():+ with torch.inference_mode():inp = torch.from_numpy(norm_img_batch)encoder_word_pos_inp = torch.from_numpy(encoder_word_pos_list)gsrm_word_pos_inp = torch.from_numpy(gsrm_word_pos_list)@@ -407,7 +406,7 @@ class TextRecognizer(BaseOCRV20):# valid_ratios,# ]- with torch.no_grad():+ with torch.inference_mode():inp = torch.from_numpy(norm_img_batch)inp = inp.to(self.device)inp = self._to_inference_dtype(inp)@@ -422,7 +421,7 @@ class TextRecognizer(BaseOCRV20):inp = [torch.from_numpy(e_i) for e_i in inputs]inp = [e_i.to(self.device) for e_i in inp]inp = [self._to_inference_dtype(e_i) for e_i in inp]- with torch.no_grad():+ with torch.inference_mode():outputs = self.net(inp)outputs = [v.cpu().numpy() for k, v in enumerate(outputs)]@@ -431,13 +430,13 @@ class TextRecognizer(BaseOCRV20):else:starttime = time.time()- with torch.no_grad():+ with torch.inference_mode():inp = torch.from_numpy(norm_img_batch)inp = inp.to(self.device)inp = self._to_inference_dtype(inp)preds = self.net(inp)- with torch.no_grad():+ with torch.inference_mode():rec_result = self.postprocess_op(preds)for rno in range(len(rec_result)):