Skip to content

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

feat: optimize OCR processing by consolidating batch handling and switching to inference mode

myhloli06ec29951a6e
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.py
index 34dc6f59..01ac717d 100644
--- a/mineru/backend/hybrid/hybrid_analyze.py
+++ b/mineru/backend/hybrid/hybrid_analyze.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import asyncio
import os
import time
-from collections import defaultdict
from typing import Any, Literal
import cv2
@@ -193,65 +192,41 @@ def _ocr_det(
bgr_image = mask_formula_regions_for_ocr_det(bgr_image, adjusted_mfdetrec_res)
all_cropped_images_info.append((bgr_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[0]
- 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[0]
- 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[0] 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, useful_list, adjusted_mfdetrec_res, ocr_page_res_list = crop_info
+ for crop_info, (dt_boxes, _) in zip(all_cropped_images_info, batch_results):
+ bgr_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 []
+ 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
- )
+ # 根据公式位置更新检测框
+ 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_enable if fill_text else False,
- bgr_image,
- hybrid_pipeline_model.lang,
- )
- ocr_page_res_list.extend(ocr_result_list)
+ 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_enable if fill_text else False,
+ bgr_image,
+ hybrid_pipeline_model.lang,
+ )
+ ocr_page_res_list.extend(ocr_result_list)
return ocr_res_list
diff --git a/mineru/backend/pipeline/batch_analyze.py b/mineru/backend/pipeline/batch_analyze.py
index b2574a18..d6dbfb77 100644
--- a/mineru/backend/pipeline/batch_analyze.py
+++ b/mineru/backend/pipeline/batch_analyze.py
@@ -657,69 +657,48 @@ class BatchAnalyze:
# 获取OCR模型
ocr_model = atom_model_manager.get_atom_model(atom_model_name=AtomicModel.OCR, 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)
-
- # 处理批处理结果
- 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
- )
+ 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}",
+ )
- 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.py
index d2528014..089a55d3 100644
--- a/mineru/model/ocr/pytorch_paddle.py
+++ b/mineru/model/ocr/pytorch_paddle.py
@@ -237,7 +237,7 @@ class PytorchPaddleOCR(TextSystem):
logger.debug("no valid image provided")
return None, None
- ori_im = img.copy()
+ ori_im = img
dt_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.py
index 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 infer
diff --git a/mineru/model/utils/pytorchocr/modeling/heads/rec_multi_head.py b/mineru/model/utils/pytorchocr/modeling/heads/rec_multi_head.py
index 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 F
from torch import nn
from ..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 predicts
ctc_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.py
index 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 text
label = self.decode(label)
- return text, label
\ No newline at end of file
+ return text, label
diff --git a/mineru/model/utils/tools/infer/predict_cls.py b/mineru/model/utils/tools/infer/predict_cls.py
index 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.py
index e2d6b7ad..c638b38d 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 defaultdict
import numpy as np
import time
import torch
+from tqdm import tqdm
from ...pytorchocr.base_ocr_v20 import BaseOCRV20
from . import pytorchocr_utility as utility
from ...pytorchocr.data import create_operators, transform
@@ -124,6 +126,19 @@ class TextDetector(BaseOCRV20):
if hasattr(module, 'rep'):
module.rep()
+ 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
+ if img_processed is None:
+ return None
+
+ return np.ascontiguousarray(img_processed), shape_list, img.shape
+
def _should_only_clip_det_res(self):
if self.det_algorithm == "SAST" and getattr(self, "det_sast_polygon", False):
return True
@@ -156,91 +171,97 @@ class TextDetector(BaseOCRV20):
raise NotImplementedError
return preds
- def _batch_process_same_size(self, img_list):
- """
- 对相同尺寸的图像进行批处理
-
- Args:
- img_list: 相同尺寸的图像列表
+ def _postprocess_det_batch(self, preds, batch_shapes, ori_shapes):
+ """对完整 batch 执行一次 OCR-det 后处理,再逐张裁剪过滤检测框。"""
+ post_results = self.postprocess_op(preds, batch_shapes)
+ batch_results = []
+ 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
- Returns:
- batch_results: 批处理结果列表
- total_elapse: 总耗时
- """
+ def _batch_process_preprocessed(self, batch_items):
+ """对已经完成预处理且形状一致的图片执行批量推理。"""
starttime = time.time()
+ if not batch_items:
+ return [], 0
- # 预处理所有图像
- 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
-
- img_processed, shape_list = data
- batch_data.append(img_processed)
- batch_shapes.append(shape_list)
+ 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]
- # 堆叠成批处理张量
try:
- batch_tensor = np.stack(batch_data, axis=0)
+ batch_tensor = np.ascontiguousarray(np.stack(batch_data, axis=0))
batch_shapes = np.stack(batch_shapes, axis=0)
- except Exception as e:
- # 如果堆叠失败,回退到逐个处理
+ except Exception:
batch_results = []
- for img in img_list:
- dt_boxes, elapse = self.__call__(img)
- batch_results.append((dt_boxes, elapse))
+ 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
- # 批处理推理
- with torch.no_grad():
+ 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)
-
- # 后处理每个图像的结果
- batch_results = []
+ 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
- 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
-
- # 后处理
- post_result = self.postprocess_op(single_preds, batch_shapes[i:i + 1])
- dt_boxes = post_result[0]['points']
-
- # 过滤和裁剪检测框
- dt_boxes = self._filter_det_res(dt_boxes, ori_imgs[i].shape)
-
- batch_results.append((dt_boxes, total_elapse / len(img_list)))
+ def _batch_process_same_size(self, img_list):
+ """
+ 对相同尺寸的图像进行批处理
- return batch_results, total_elapse
+ Args:
+ img_list: 相同尺寸的图像列表
- def batch_predict(self, img_list, max_batch_size=8):
+ 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)
@@ -248,14 +269,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
- # 分批处理
- 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)
+ max_batch_size = max(1, int(max_batch_size))
+ batch_results = [(None, 0)] * len(img_list)
+ grouped_items = defaultdict(list)
+
+ 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
@@ -315,28 +360,11 @@ class TextDetector(BaseOCRV20):
return dt_boxes_new
def __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 = self._build_det_preds(outputs)
-
- 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.py
index f3347a2f..15f3cb6e 100644
--- a/mineru/model/utils/tools/infer/predict_rec.py
+++ b/mineru/model/utils/tools/infer/predict_rec.py
@@ -301,8 +301,14 @@ class TextRecognizer(BaseOCRV20):
rec_res = [['', 0.0]] * img_num
batch_num = self.rec_batch_num
elapse = 0
- # for beg_img_no in range(0, img_num, batch_num):
- with tqdm(total=img_num, desc=tqdm_desc, disable=not tqdm_enable) as pbar:
+ # tqdm_progress_bar 由上层复用时,不再创建内部 OCR-rec 进度条。
+ pbar = tqdm_progress_bar
+ should_close_pbar = False
+ if pbar is None:
+ pbar = tqdm(total=img_num, desc=tqdm_desc, disable=not tqdm_enable)
+ should_close_pbar = True
+
+ try:
index = 0
for beg_img_no in range(0, img_num, batch_num):
end_img_no = min(img_num, beg_img_no + batch_num)
@@ -352,8 +358,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()
@@ -364,7 +369,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)
@@ -395,7 +400,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)
@@ -410,7 +415,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)]
@@ -419,13 +424,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)):
@@ -436,8 +441,9 @@ class TextRecognizer(BaseOCRV20):
current_batch_size = min(batch_num, img_num - index * batch_num)
index += 1
pbar.update(current_batch_size)
- if tqdm_progress_bar is not None:
- tqdm_progress_bar.update(current_batch_size)
+ finally:
+ if should_close_pbar:
+ pbar.close()
# Fix NaN values in recognition results
for i in range(len(rec_res)):