Skip to content

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

feat: use same code to create onnx session

jinzhenjb9d915a5b51a
diff --git a/mineru/backend/local_model_runtime.py b/mineru/backend/local_model_runtime.py
index be0ca6ee..451ba751 100644
--- a/mineru/backend/local_model_runtime.py
+++ b/mineru/backend/local_model_runtime.py
@@ -19,8 +19,7 @@ if TYPE_CHECKING:
from ..model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel
from ..model.mfr.unimernet.Unimernet import UnimernetModel
from ..model.ocr.pytorch_paddle import PytorchPaddleOCR
-from ..utils.config_reader import get_device
-from ..utils.config_reader import get_model_stack
+from ..utils.config_reader import get_device, get_model_stack
from ..utils.model_registry import PDF_EXTRACT_KIT, ModelPath
from ..utils.ocr_language import normalize_ocr_model_lang
@@ -37,6 +36,7 @@ class AtomicModel:
TableCls = "table_cls"
TableOrientationCls = "table_ori_cls"
+
LOCAL_MODEL_INIT_LOCK = threading.RLock()
# 这些锁保护 Hybrid medium/high/xhigh 共享的 atom model/native 模型推理调用,避免多线程同时进入同一个模型对象。
LOCAL_MODEL_LAYOUT_INFERENCE_LOCK = threading.RLock()
@@ -211,7 +211,7 @@ def atom_model_init(model_name: str, **kwargs: Any) -> Any:
atom_model = PPDocLayoutV2LayoutModelONNX(
weight=str(PP_DOCLAYOUT_V2_ONNX.onnx.ensure()),
- device=kwargs.get("device", "cpu"),
+ device=kwargs.get("device"),
)
else:
atom_model = pp_doclayout_v2_model_init(kwargs.get("pp_doclayout_v2_weights"), kwargs.get("device"))
@@ -223,7 +223,7 @@ def atom_model_init(model_name: str, **kwargs: Any) -> Any:
atom_model = PPFormulaNetPlusMONNX(
model_path=str(PP_FORMULANET_PLUS_M_ONNX.onnx.ensure()),
config_path=str(PP_FORMULANET_PLUS_M_ONNX.config.ensure()),
- device=kwargs.get("device", "cpu"),
+ device=kwargs.get("device"),
)
else:
atom_model = mfr_model_init(kwargs.get("mfr_weight_dir"), kwargs.get("device"))
@@ -236,7 +236,7 @@ def atom_model_init(model_name: str, **kwargs: Any) -> Any:
det_model_path=str(PP_OCR_V6_SMALL_DET_ONNX.onnx.ensure()),
rec_model_path=str(PP_OCR_V6_SMALL_REC_ONNX.onnx.ensure()),
dict_path=str(PP_OCR_V6_SMALL_REC_ONNX.config.ensure()),
- device=kwargs.get("device", "cpu"),
+ device=kwargs.get("device"),
det_db_box_thresh=kwargs.get("det_db_box_thresh", 0.5),
det_db_unclip_ratio=kwargs.get("det_db_unclip_ratio", 1.5),
enable_merge_det_boxes=kwargs.get("enable_merge_det_boxes", True),
diff --git a/mineru/model/layout/pp_doclayout_v2_onnx.py b/mineru/model/layout/pp_doclayout_v2_onnx.py
index 0af3bb40..ac409c4f 100644
--- a/mineru/model/layout/pp_doclayout_v2_onnx.py
+++ b/mineru/model/layout/pp_doclayout_v2_onnx.py
@@ -15,11 +15,11 @@ from typing import Dict, List, Optional, Sequence, Tuple, Union
import cv2
import numpy as np
-import onnxruntime as ort
from loguru import logger
from PIL import Image
from tqdm import tqdm
+from ..utils.onnxruntime_provider import ort_session
from .pp_doclayout_v2_base import PP_DOCLAYOUT_V2_LABELS, PPDocLayoutV2PostProcessor
__all__ = ["PPDocLayoutV2LayoutModelONNX"]
@@ -28,17 +28,6 @@ __all__ = ["PPDocLayoutV2LayoutModelONNX"]
_INPUT_SIZE = (800, 800)
-def _build_providers(device: Optional[str]) -> list[tuple[str, dict[str, object]]]:
- """根据 device 选择 onnxruntime providers。"""
- norm = (device or "cpu").lower().split(":", 1)[0]
- if norm == "cuda":
- return [
- ("CUDAExecutionProvider", {"device_id": 0, "arena_extend_strategy": "kSameAsRequested"}),
- ("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"}),
- ]
- return [("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"})]
-
-
class PPDocLayoutV2LayoutModelONNX(PPDocLayoutV2PostProcessor):
"""PP-DocLayoutV2 的 ONNX 推理封装。
@@ -55,30 +44,19 @@ class PPDocLayoutV2LayoutModelONNX(PPDocLayoutV2PostProcessor):
def __init__(
self,
weight: str,
- device: Optional[str] = "cpu",
+ device: Optional[str] = None,
imgsz: Tuple[int, int] = _INPUT_SIZE,
conf: float = 0.45,
use_paddlex_filter_boxes: bool = True,
intra_op_num_threads: int = 0,
) -> None:
- self.device = device or "cpu"
+ self.device = device
self.conf = conf
self.use_paddlex_filter_boxes = use_paddlex_filter_boxes
self.model_path = str(weight)
self.imgsz = imgsz
self.rescale_factor = 1.0 / 255.0
-
- opts = ort.SessionOptions()
- opts.log_severity_level = 3
- opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
- if intra_op_num_threads > 0:
- opts.intra_op_num_threads = intra_op_num_threads
- self.session = ort.InferenceSession(
- self.model_path,
- sess_options=opts,
- providers=_build_providers(self.device),
- )
-
+ self.session = ort_session(self.model_path, device, intra_op_num_threads)
self._input_names = [i.name for i in self.session.get_inputs()]
self._output_name = self.session.get_outputs()[0].name
logger.debug(
diff --git a/mineru/model/mfr/pp_formulanet_plus_m_onnx.py b/mineru/model/mfr/pp_formulanet_plus_m_onnx.py
index 93f099e3..00afc7da 100644
--- a/mineru/model/mfr/pp_formulanet_plus_m_onnx.py
+++ b/mineru/model/mfr/pp_formulanet_plus_m_onnx.py
@@ -9,6 +9,7 @@ ONNX 模型输出 token IDs(int64),不是 logits——自回归循环已 b
预处理/后处理参数与 RapidDoc ``inference.yml`` 一致。
"""
+
from __future__ import annotations
import json
@@ -18,12 +19,12 @@ from typing import Any, List, Optional, Tuple
import cv2
import numpy as np
-import onnxruntime as ort
import yaml
from loguru import logger
from PIL import Image, ImageOps
from tqdm import tqdm
+from ..utils.onnxruntime_provider import ort_session
from .post_process import post_process_formula
__all__ = ["PPFormulaNetPlusMONNX"]
@@ -39,16 +40,6 @@ _PAD_TOKEN_ID = 1
_EOS_TOKEN_ID = 2
-def _build_providers(device: str) -> list[tuple[str, dict[str, Any]]]:
- norm = (device or "cpu").lower().split(":", 1)[0]
- if norm == "cuda":
- return [
- ("CUDAExecutionProvider", {"device_id": 0, "arena_extend_strategy": "kSameAsRequested"}),
- ("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"}),
- ]
- return [("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"})]
-
-
class PPFormulaNetPlusMONNX:
"""PP-FormulaNet-Plus-M 的 ONNX 推理封装。
@@ -64,21 +55,11 @@ class PPFormulaNetPlusMONNX:
self,
model_path: str,
config_path: str,
- device: str = "cpu",
+ device: Optional[str] = None,
intra_op_num_threads: int = 0,
) -> None:
- self.device = device or "cpu"
-
- opts = ort.SessionOptions()
- opts.log_severity_level = 3
- opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
- if intra_op_num_threads > 0:
- opts.intra_op_num_threads = intra_op_num_threads
- self.session = ort.InferenceSession(
- model_path,
- sess_options=opts,
- providers=_build_providers(self.device),
- )
+ self.device = device
+ self.session = ort_session(model_path, device, intra_op_num_threads)
self.input_name = self.session.get_inputs()[0].name
# 从 yml 加载 tokenizer
diff --git a/mineru/model/ocr/pp_ocr_v6_onnx.py b/mineru/model/ocr/pp_ocr_v6_onnx.py
index f1e0fbd6..f210f554 100644
--- a/mineru/model/ocr/pp_ocr_v6_onnx.py
+++ b/mineru/model/ocr/pp_ocr_v6_onnx.py
@@ -11,6 +11,7 @@
预处理/后处理参数与 PaddlePaddle 官方 ``inference.yml`` 一似。
"""
+
from __future__ import annotations
import copy
@@ -22,7 +23,6 @@ from typing import Any, List, Optional, Tuple, Union
import cv2
import numpy as np
-import onnxruntime as ort
import pyclipper
from loguru import logger
from shapely.geometry import Polygon
@@ -36,6 +36,7 @@ from ...utils.ocr_utils import (
sorted_boxes,
update_det_boxes,
)
+from ..utils.onnxruntime_provider import ort_session
__all__ = ["PPOCRv6ONNX"]
@@ -43,14 +44,6 @@ __all__ = ["PPOCRv6ONNX"]
# ------------------------------------------------------------------
# 共享工具
# ------------------------------------------------------------------
-def _build_providers(device: str) -> list[tuple[str, dict[str, Any]]]:
- norm = (device or "cpu").lower().split(":", 1)[0]
- if norm == "cuda":
- return [
- ("CUDAExecutionProvider", {"device_id": 0, "arena_extend_strategy": "kSameAsRequested"}),
- ("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"}),
- ]
- return [("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"})]
def _load_character_dict(dict_path: str) -> List[str]:
@@ -65,23 +58,7 @@ def _load_character_dict(dict_path: str) -> List[str]:
raise ValueError(f"character_dict in {dict_path} is not a list")
return chars
# txt 文件:每行一个字符
- return [
- line.decode("utf-8").strip("\n").strip("\r\n")
- for line in Path(dict_path).read_bytes().splitlines()
- ]
-
-
-def _make_session(model_path: str, device: str, intra_op_num_threads: int = 0) -> ort.InferenceSession:
- opts = ort.SessionOptions()
- opts.log_severity_level = 3
- opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
- if intra_op_num_threads > 0:
- opts.intra_op_num_threads = intra_op_num_threads
- return ort.InferenceSession(
- model_path,
- sess_options=opts,
- providers=_build_providers(device),
- )
+ return [line.decode("utf-8").strip("\n").strip("\r\n") for line in Path(dict_path).read_bytes().splitlines()]
# ------------------------------------------------------------------
@@ -97,7 +74,7 @@ class TextDetectorONNX:
def __init__(
self,
model_path: str,
- device: str = "cpu",
+ device: Optional[str] = None,
limit_side_len: int = 960,
limit_type: str = "max",
max_side_limit: int = 4000,
@@ -108,7 +85,7 @@ class TextDetectorONNX:
use_dilation: bool = True,
intra_op_num_threads: int = 0,
) -> None:
- self.session = _make_session(model_path, device, intra_op_num_threads)
+ self.session = ort_session(model_path, device, intra_op_num_threads)
self.input_name = self.session.get_inputs()[0].name
self.limit_side_len = limit_side_len
@@ -332,13 +309,13 @@ class TextRecognizerONNX:
self,
model_path: str,
dict_path: str,
- device: str = "cpu",
+ device: Optional[str] = None,
rec_image_shape: Tuple[int, int, int] = (3, 48, 320),
rec_batch_num: int = 6,
drop_score: float = 0.5,
intra_op_num_threads: int = 0,
) -> None:
- self.session = _make_session(model_path, device, intra_op_num_threads)
+ self.session = ort_session(model_path, device, intra_op_num_threads)
self.input_name = self.session.get_inputs()[0].name
self.img_c, self.img_h, self.img_w = rec_image_shape
@@ -446,7 +423,7 @@ class PPOCRv6ONNX:
det_model_path: str,
rec_model_path: str,
dict_path: str,
- device: str = "cpu",
+ device: Optional[str] = None,
det_db_box_thresh: float = 0.5,
det_db_unclip_ratio: float = 1.5,
enable_merge_det_boxes: bool = True,
@@ -550,9 +527,7 @@ class PPOCRv6ONNX:
return [None]
- def _det_rec(
- self, img: np.ndarray, mfd_res: Optional[List[dict]] = None
- ) -> Tuple[np.ndarray, List[Tuple[str, float]]]:
+ def _det_rec(self, img: np.ndarray, mfd_res: Optional[List[dict]] = None) -> Tuple[np.ndarray, List[Tuple[str, float]]]:
"""det + crop + rec 的完整流程。"""
ori_im = img
dt_boxes, _elapse = self.text_detector(img)
diff --git a/mineru/model/table/cls/paddle_table_cls.py b/mineru/model/table/cls/paddle_table_cls.py
index f2f49400..a470837c 100644
--- a/mineru/model/table/cls/paddle_table_cls.py
+++ b/mineru/model/table/cls/paddle_table_cls.py
@@ -1,18 +1,18 @@
# Copyright (c) Opendatalab. All rights reserved.
-from PIL import Image
import cv2
import numpy as np
-import onnxruntime
+from PIL import Image
from tqdm import tqdm
from ....utils.model_registry import PDF_EXTRACT_KIT
+from ...utils.onnxruntime_provider import ort_session
class PaddleTableClsModel:
def __init__(self):
from mineru.backend.local_model_runtime import AtomicModel
- self.sess = onnxruntime.InferenceSession(str(PDF_EXTRACT_KIT.paddle_table_cls.ensure()))
+ self.sess = ort_session(str(PDF_EXTRACT_KIT.paddle_table_cls.ensure()))
self.less_length = 256
self.cw, self.ch = 224, 224
self.std = [0.229, 0.224, 0.225]
@@ -35,9 +35,7 @@ class PaddleTableClsModel:
x2 = min(w, x1 + cw)
y2 = min(h, y1 + ch)
if w < cw or h < ch:
- raise ValueError(
- f"Input image ({w}, {h}) smaller than the target size ({cw}, {ch})."
- )
+ raise ValueError(f"Input image ({w}, {h}) smaller than the target size ({cw}, {ch}).")
img = img[y1:y2, x1:x2, ...]
# 正则化
split_im = list(cv2.split(img))
@@ -105,9 +103,7 @@ class PaddleTableClsModel:
x2 = min(w, x1 + cw)
y2 = min(h, y1 + ch)
if w < cw or h < ch:
- raise ValueError(
- f"Input image ({w}, {h}) smaller than the target size ({cw}, {ch})."
- )
+ raise ValueError(f"Input image ({w}, {h}) smaller than the target size ({cw}, {ch}).")
img = img[y1:y2, x1:x2, ...]
# 正则化
split_im = list(cv2.split(img))
@@ -126,6 +122,7 @@ class PaddleTableClsModel:
res_imgs.append(img)
x = np.stack(res_imgs, axis=0).astype(dtype=np.float32, copy=False)
return x
+
def batch_predict(self, img_info_list, batch_size=16):
imgs = [item["wired_table_img"] for item in img_info_list]
imgs = self.list_2_batch(imgs, batch_size=batch_size)
@@ -137,8 +134,8 @@ class PaddleTableClsModel:
for img_res in result[0]:
idx = np.argmax(img_res)
conf = float(np.max(img_res))
- label_res.append((self.labels[idx],conf))
+ label_res.append((self.labels[idx], conf))
pbar.update(len(img_batch))
for img_info, (label, conf) in zip(img_info_list, label_res):
- img_info['table_res']["cls_label"] = label
- img_info['table_res']["cls_score"] = round(conf, 3)
+ img_info["table_res"]["cls_label"] = label
+ img_info["table_res"]["cls_score"] = round(conf, 3)
diff --git a/mineru/model/table/rec/onnxruntime_provider.py b/mineru/model/table/rec/onnxruntime_provider.py
deleted file mode 100644
index a7fbe526..00000000
--- a/mineru/model/table/rec/onnxruntime_provider.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from typing import Any, List, Sequence, Tuple
-
-from loguru import logger
-
-from mineru.utils.config_reader import get_device
-
-
-CPU_PROVIDER = "CPUExecutionProvider"
-CUDA_PROVIDER = "CUDAExecutionProvider"
-CPU_PROVIDER_OPTS = {
- "arena_extend_strategy": "kSameAsRequested",
-}
-CUDA_PROVIDER_OPTS = {
- "cudnn_conv_algo_search": "HEURISTIC",
-}
-
-
-def _normalize_device(device: object) -> str:
- """归一化 MinerU 设备名,兼容 cuda:0 这类带索引的写法。"""
- if not isinstance(device, str):
- return ""
- return device.split(":", 1)[0].strip().lower()
-
-
-def _build_cpu_provider() -> Tuple[str, dict[str, Any]]:
- """构建 CPU provider 配置,避免复用可变的模块级字典。"""
- return (CPU_PROVIDER, dict(CPU_PROVIDER_OPTS))
-
-
-def _build_cuda_provider() -> Tuple[str, dict[str, Any]]:
- return (CUDA_PROVIDER, dict(CUDA_PROVIDER_OPTS))
-
-
-def build_table_onnx_providers(
- available_providers: Sequence[str],
-) -> List[Tuple[str, dict[str, Any]]]:
- """根据 MinerU 当前设备为表格 ONNX 模型选择 onnxruntime providers。"""
- cpu_provider = _build_cpu_provider()
- cuda_provider = _build_cuda_provider()
- device = _normalize_device(get_device())
-
- # 只有 MinerU 设备明确为 CUDA 时才尝试 CUDAExecutionProvider,保持默认 CPU 行为。
- if device != "cuda":
- return [cpu_provider]
-
- if CUDA_PROVIDER in available_providers:
- return [cuda_provider, cpu_provider]
-
- return [cpu_provider]
diff --git a/mineru/model/table/rec/slanet_plus/table_structure_utils.py b/mineru/model/table/rec/slanet_plus/table_structure_utils.py
index f865ff29..98eb90bd 100644
--- a/mineru/model/table/rec/slanet_plus/table_structure_utils.py
+++ b/mineru/model/table/rec/slanet_plus/table_structure_utils.py
@@ -18,15 +18,10 @@ from typing import Any, Dict, List, Tuple, Union
import cv2
import numpy as np
-from onnxruntime import (
- GraphOptimizationLevel,
- InferenceSession,
- SessionOptions,
- get_available_providers,
-)
-
from loguru import logger
-from ..onnxruntime_provider import build_table_onnx_providers
+from onnxruntime import GraphOptimizationLevel, InferenceSession, SessionOptions
+
+from ....utils.onnxruntime_provider import ort_providers
class OrtInferSession:
@@ -36,14 +31,10 @@ class OrtInferSession:
model_path = config.get("model_path", None)
self._verify_model(model_path)
- self.had_providers: List[str] = get_available_providers()
- EP_list = self._get_ep_list()
-
- sess_opt = self._init_sess_opts(config)
self.session = InferenceSession(
model_path,
- sess_options=sess_opt,
- providers=EP_list,
+ sess_options=self._init_sess_opts(config),
+ providers=ort_providers(),
)
@staticmethod
@@ -69,9 +60,6 @@ class OrtInferSession:
content_list = meta_dict[key].splitlines()
return content_list
- def _get_ep_list(self) -> List[Tuple[str, Dict[str, Any]]]:
- return build_table_onnx_providers(self.had_providers)
-
def __call__(self, input_content: List[np.ndarray]) -> np.ndarray:
input_dict = dict(zip(self.get_input_names(), input_content))
try:
@@ -267,14 +255,10 @@ class TablePreprocess:
Args:
params(list): a dict list, used to create some operators
"""
- assert isinstance(
- self.pre_process_list, list
- ), "operator config should be a list"
+ assert isinstance(self.pre_process_list, list), "operator config should be a list"
ops = []
for operator in self.pre_process_list:
- assert (
- isinstance(operator, dict) and len(operator) == 1
- ), "yaml format error"
+ assert isinstance(operator, dict) and len(operator) == 1, "yaml format error"
op_name = list(operator)[0]
param = {} if operator[op_name] is None else operator[op_name]
op = eval(op_name)(**param)
@@ -287,9 +271,7 @@ class TablePreprocess:
"max_len": self.table_max_len,
}
}
- pad_op = {
- "PaddingTableImage": {"size": [self.table_max_len, self.table_max_len]}
- }
+ pad_op = {"PaddingTableImage": {"size": [self.table_max_len, self.table_max_len]}}
normalize_op = {
"NormalizeImage": {
"std": [0.229, 0.224, 0.225],
@@ -310,13 +292,10 @@ class TablePreprocess:
class BatchTablePreprocess:
-
def __init__(self):
self.preprocess = TablePreprocess()
- def __call__(
- self, img_list: List[np.ndarray]
- ) -> Tuple[List[np.ndarray], List[List[float]]]:
+ def __call__(self, img_list: List[np.ndarray]) -> Tuple[List[np.ndarray], List[List[float]]]:
"""批量处理图像
Args:
diff --git a/mineru/model/table/rec/unet_table/utils.py b/mineru/model/table/rec/unet_table/utils.py
index fb1c35e4..eea1cba9 100644
--- a/mineru/model/table/rec/unet_table/utils.py
+++ b/mineru/model/table/rec/unet_table/utils.py
@@ -3,22 +3,14 @@ import os
import traceback
from io import BytesIO
from pathlib import Path
-from typing import List, Union, Dict, Any, Tuple, Optional
+from typing import Any, Dict, List, Optional, Union
import cv2
import loguru
import numpy as np
-from onnxruntime import (
- GraphOptimizationLevel,
- InferenceSession,
- SessionOptions,
- get_available_providers,
-)
+from onnxruntime import GraphOptimizationLevel, InferenceSession, SessionOptions
from PIL import Image, UnidentifiedImageError
-from ..onnxruntime_provider import build_table_onnx_providers
-
-
root_dir = Path(__file__).resolve().parent
InputType = Union[str, np.ndarray, bytes, Path]
@@ -26,17 +18,12 @@ InputType = Union[str, np.ndarray, bytes, Path]
class OrtInferSession:
def __init__(self, config: Dict[str, Any]):
self.logger = loguru.logger
-
model_path = config.get("model_path", None)
- self.had_providers: List[str] = get_available_providers()
- EP_list = self._get_ep_list()
-
- sess_opt = self._init_sess_opts(config)
self.session = InferenceSession(
model_path,
- sess_options=sess_opt,
- providers=EP_list,
+ sess_options=self._init_sess_opts(config),
+ providers=[("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"})],
)
@staticmethod
@@ -57,9 +44,6 @@ class OrtInferSession:
return sess_opt
- def _get_ep_list(self) -> List[Tuple[str, Dict[str, Any]]]:
- return build_table_onnx_providers(self.had_providers)
-
def __call__(self, input_content: List[np.ndarray]) -> np.ndarray:
input_dict = dict(zip(self.get_input_names(), input_content))
try:
@@ -84,9 +68,7 @@ class LoadImage:
def __call__(self, img: InputType) -> np.ndarray:
if not isinstance(img, InputType.__args__):
- raise LoadImageError(
- f"The img type {type(img)} does not in {InputType.__args__}"
- )
+ raise LoadImageError(f"The img type {type(img)} does not in {InputType.__args__}")
img = self.load_img(img)
img = self.convert_img(img)
@@ -128,9 +110,7 @@ class LoadImage:
if channel == 3:
return cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
- raise LoadImageError(
- f"The channel({channel}) of the img is not in [1, 2, 3, 4]"
- )
+ raise LoadImageError(f"The channel({channel}) of the img is not in [1, 2, 3, 4]")
raise LoadImageError(f"The ndim({img.ndim}) of the img is not in [2, 3]")
@@ -209,9 +189,7 @@ def resize_img(img, scale, keep_ratio=True):
interpolation = "area"
else:
interpolation = "bicubic" # bilinear
- img_new, scale_factor = imrescale(
- img, scale, return_scale=True, interpolation=interpolation
- )
+ img_new, scale_factor = imrescale(img, scale, return_scale=True, interpolation=interpolation)
# the w_scale and h_scale has minor difference
# a real fix should be done in the mmcv.imrescale in the future
new_h, new_w = img_new.shape[:2]
@@ -249,9 +227,7 @@ def imrescale(img, scale, return_scale=False, interpolation="bilinear", backend=
return rescaled_img
-def imresize(
- img, size, return_scale=False, interpolation="bilinear", out=None, backend=None
-):
+def imresize(img, size, return_scale=False, interpolation="bilinear", out=None, backend=None):
"""Resize image to a given size.
Args:
@@ -274,10 +250,7 @@ def imresize(
if backend is None:
backend = "cv2"
if backend not in ["cv2", "pillow"]:
- raise ValueError(
- f"backend: {backend} is not supported for resize."
- f"Supported backends are 'cv2', 'pillow'"
- )
+ raise ValueError(f"backend: {backend} is not supported for resize.Supported backends are 'cv2', 'pillow'")
if backend == "pillow":
assert img.dtype == np.uint8, "Pillow backend only support uint8 type"
@@ -285,9 +258,7 @@ def imresize(
pil_image = pil_image.resize(size, pillow_interp_codes[interpolation])
resized_img = np.array(pil_image)
else:
- resized_img = cv2.resize(
- img, size, dst=out, interpolation=cv2_interp_codes[interpolation]
- )
+ resized_img = cv2.resize(img, size, dst=out, interpolation=cv2_interp_codes[interpolation])
if not return_scale:
return resized_img
else:
@@ -321,9 +292,7 @@ def rescale_size(old_size, scale, return_scale=False):
max_short_edge = min(scale)
scale_factor = min(max_long_edge / max(h, w), max_short_edge / min(h, w))
else:
- raise TypeError(
- f"Scale must be a number or tuple of int, but got {type(scale)}"
- )
+ raise TypeError(f"Scale must be a number or tuple of int, but got {type(scale)}")
new_size = _scale_size((w, h), scale_factor)
@@ -385,9 +354,7 @@ class VisTable:
if save_logic_path:
polygons = [[box[0], box[1], box[4], box[5]] for box in table_cell_bboxes]
- self.plot_rec_box_with_logic_info(
- img, save_logic_path, table_logic_points, polygons
- )
+ self.plot_rec_box_with_logic_info(img, save_logic_path, table_logic_points, polygons)
return drawed_img
def insert_border_style(self, table_html_str: str):
@@ -410,9 +377,7 @@ class VisTable:
html_with_border = f"{prefix_table}{style_res}<body>{suffix_table}"
return html_with_border
- def plot_rec_box_with_logic_info(
- self, img, output_path, logic_points, sorted_polygons
- ):
+ def plot_rec_box_with_logic_info(self, img, output_path, logic_points, sorted_polygons):
"""
:param img_path
:param output_path
@@ -421,9 +386,7 @@ class VisTable:
:return:
"""
# 读取原图
- img = cv2.copyMakeBorder(
- img, 0, 0, 0, 100, cv2.BORDER_CONSTANT, value=[255, 255, 255]
- )
+ img = cv2.copyMakeBorder(img, 0, 0, 0, 100, cv2.BORDER_CONSTANT, value=[255, 255, 255])
# 绘制 polygons 矩形
for idx, polygon in enumerate(sorted_polygons):
x0, y0, x1, y1 = polygon[0], polygon[1], polygon[2], polygon[3]
diff --git a/mineru/model/utils/onnxruntime_provider.py b/mineru/model/utils/onnxruntime_provider.py
new file mode 100644
index 00000000..ac9c5379
--- /dev/null
+++ b/mineru/model/utils/onnxruntime_provider.py
@@ -0,0 +1,28 @@
+import onnxruntime as ort
+
+AVAILABLE_PROVIDERS: list[str] = ort.get_available_providers()
+
+
+def ort_providers(device: str | None = None) -> list[tuple[str, dict[str, object]]]:
+ """根据 device 选择 onnxruntime providers。"""
+ norm = (device or "").lower().split(":", 1)[0]
+ if norm != "cpu" and "CUDAExecutionProvider" in AVAILABLE_PROVIDERS:
+ return [
+ ("CUDAExecutionProvider", {"cudnn_conv_algo_search": "HEURISTIC"}),
+ ("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"}),
+ ]
+ # if "CoreMLExecutionProvider" in AVAILABLE_PROVIDERS:
+ # return [
+ # ("CoreMLExecutionProvider", {}),
+ # ("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"}),
+ # ]
+ return [("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"})]
+
+
+def ort_session(model_path: str, device: str | None = None, intra_op_num_threads: int = 0) -> ort.InferenceSession:
+ opts = ort.SessionOptions()
+ opts.log_severity_level = 3
+ opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
+ if intra_op_num_threads > 0:
+ opts.intra_op_num_threads = intra_op_num_threads
+ return ort.InferenceSession(model_path, sess_options=opts, providers=ort_providers(device))