Skip to content

📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.

fix: fixed issue #566 (#573)

SWHL787819457f18
diff --git a/python/demo.py b/python/demo.py
index 200c2ed..f5a223e 100644
--- a/python/demo.py
+++ b/python/demo.py
@@ -1,14 +1,20 @@
# -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: [email protected]
-from rapidocr import RapidOCR
+from rapidocr import EngineType, RapidOCR
-engine = RapidOCR()
+engine = RapidOCR(
+ params={
+ "Det.engine_type": EngineType.TORCH,
+ "Cls.engine_type": EngineType.TORCH,
+ "Rec.engine_type": EngineType.TORCH,
+ "EngineConfig.torch.use_cuda": True, # 使用torch GPU版推理
+ "EngineConfig.torch.gpu_id": 0, # 指定GPU id
+ }
+)
-img_url = "https://img1.baidu.com/it/u=3619974146,1266987475&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=516"
-img_url = "tests/test_files/return_word_debug.jpg"
-result = engine(img_url, return_word_box=True)
+img_url = "https://github.com/RapidAI/RapidOCR/blob/main/python/tests/test_files/ch_en_num.jpg?raw=true"
+result = engine(img_url)
print(result)
result.vis("vis_result.jpg")
-print(result)
diff --git a/python/rapidocr/config.yaml b/python/rapidocr/config.yaml
index 6779fc3..173b455 100644
--- a/python/rapidocr/config.yaml
+++ b/python/rapidocr/config.yaml
@@ -55,17 +55,24 @@ EngineConfig:
paddle:
cpu_math_library_num_threads: -1
+
use_npu: false
- npu_id: 0
+ npu_ep_cfg:
+ device_id: 0
+
use_cuda: false
- gpu_id: 0
- gpu_mem: 500
+ cuda_ep_cfg:
+ device_id: 0
+ gpu_mem: 500
torch:
use_cuda: false
- gpu_id: 0
+ cuda_ep_cfg:
+ device_id: 0
+
use_npu: false
- npu_id: 0
+ npu_ep_cfg:
+ device_id: 0
Det:
engine_type: "onnxruntime"
diff --git a/python/rapidocr/inference_engine/base.py b/python/rapidocr/inference_engine/base.py
index 868cd96..a185030 100644
--- a/python/rapidocr/inference_engine/base.py
+++ b/python/rapidocr/inference_engine/base.py
@@ -49,7 +49,7 @@ def get_engine(engine_type: EngineType):
if not import_package(engine_type.value):
raise ImportError(f"{engine_type.value} is not installed")
- from .torch import TorchInferSession
+ from .pytorch import TorchInferSession
return TorchInferSession
diff --git a/python/rapidocr/inference_engine/pytorch/__init__.py b/python/rapidocr/inference_engine/pytorch/__init__.py
new file mode 100644
index 0000000..33ac8b0
--- /dev/null
+++ b/python/rapidocr/inference_engine/pytorch/__init__.py
@@ -0,0 +1,4 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from .main import TorchInferError, TorchInferSession
diff --git a/python/rapidocr/inference_engine/pytorch/device_config.py b/python/rapidocr/inference_engine/pytorch/device_config.py
new file mode 100644
index 0000000..06ea723
--- /dev/null
+++ b/python/rapidocr/inference_engine/pytorch/device_config.py
@@ -0,0 +1,93 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from pathlib import Path
+
+import torch
+
+from ...utils.log import logger
+from ...utils.typings import DeviceType
+from ...utils.utils import mkdir
+
+cur_dir = Path(__file__).resolve().parent
+root_dir = cur_dir.parent.parent
+model_dir = root_dir / "models"
+
+
+class DeviceConfig:
+ def __init__(self, cfg):
+ self.use_cuda = cfg.engine_cfg.use_cuda
+ self.use_npu = cfg.engine_cfg.use_npu
+
+ self.cfg = cfg
+
+ def setup_device(self):
+ if self.use_cuda:
+ device_id = self.cfg.engine_cfg.cuda_ep_cfg.device_id
+ return self.get_device(DeviceType.CUDA, device_id)
+
+ if self.use_npu:
+ device_id = self.cfg.engine_cfg.npu_ep_cfg.device_id
+ return self.get_device(DeviceType.NPU, device_id)
+
+ return self.get_device(DeviceType.CPU)
+
+ def get_device(
+ self, device_type: DeviceType = DeviceType.CPU, device_id: int = 0
+ ) -> torch.device:
+ if device_type == DeviceType.CPU:
+ return self.config_cpu()
+
+ if device_type == DeviceType.CUDA:
+ return self.config_cuda(device_id)
+
+ if device_type == DeviceType.NPU:
+ return self.config_npu(device_id)
+
+ raise DeviceConfigError(f"Unsupported device type: {device_type}")
+
+ def config_cpu(self) -> torch.device:
+ logger.info("Using CPU device")
+ return torch.device("cpu")
+
+ def config_cuda(self, device_id: int) -> torch.device:
+ if not torch.cuda.is_available():
+ raise DeviceConfigError("CUDA is not available.")
+
+ logger.info(f"Using GPU device with ID: {device_id}")
+ return torch.device(f"cuda:{device_id}")
+
+ def config_npu(self, device_id: int) -> torch.device:
+ try:
+ import torch_npu
+ except ImportError as e:
+ logger.warning(
+ "torch_npu is not installed. \n"
+ "Please refer to https://github.com/Ascend/pytorch to see how to install."
+ )
+ self.use_npu = False
+ return self.config_cpu()
+
+ try:
+ if not torch_npu.npu.is_available():
+ raise DeviceConfigError("NPU is not available.")
+ except DeviceConfigError as e:
+ logger.warning(e)
+ self.use_npu = False
+ return self.config_cpu()
+
+ kernel_meta_dir = (model_dir / "kernel_meta").resolve()
+ mkdir(kernel_meta_dir)
+
+ options = {
+ "ACL_OP_COMPILER_CACHE_MODE": "enable",
+ "ACL_OP_COMPILER_CACHE_DIR": str(kernel_meta_dir),
+ }
+ torch_npu.npu.set_option(options)
+
+ logger.info(f"Using NPU device with ID: {device_id}")
+ return torch.device(f"npu:{device_id}")
+
+
+class DeviceConfigError(Exception):
+ pass
diff --git a/python/rapidocr/inference_engine/pytorch/main.py b/python/rapidocr/inference_engine/pytorch/main.py
new file mode 100644
index 0000000..8dc7a6b
--- /dev/null
+++ b/python/rapidocr/inference_engine/pytorch/main.py
@@ -0,0 +1,29 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+import numpy as np
+import torch
+
+from ..base import InferSession
+from .device_config import DeviceConfig
+from .networks.main import ModelLoader
+
+
+class TorchInferSession(InferSession):
+ def __init__(self, cfg) -> None:
+ self.device = DeviceConfig(cfg).setup_device()
+ self.predictor = ModelLoader(cfg, self.device).predictor
+
+ def __call__(self, img: np.ndarray):
+ with torch.no_grad():
+ inp = torch.from_numpy(img)
+ inp = inp.to(self.device)
+ outputs = self.predictor(inp).cpu().numpy()
+ return outputs
+
+ def have_key(self, key: str = "character") -> bool:
+ return False
+
+
+class TorchInferError(Exception):
+ pass
diff --git a/python/rapidocr/inference_engine/pytorch/networks/__init__.py b/python/rapidocr/inference_engine/pytorch/networks/__init__.py
new file mode 100644
index 0000000..0ecdd4f
--- /dev/null
+++ b/python/rapidocr/inference_engine/pytorch/networks/__init__.py
@@ -0,0 +1,3 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
diff --git a/python/rapidocr/networks/arch_config.yaml b/python/rapidocr/inference_engine/pytorch/networks/arch_config.yaml
similarity index 100%
rename from python/rapidocr/networks/arch_config.yaml
rename to python/rapidocr/inference_engine/pytorch/networks/arch_config.yaml
diff --git a/python/rapidocr/networks/architectures/__init__.py b/python/rapidocr/inference_engine/pytorch/networks/architectures/__init__.py
similarity index 100%
rename from python/rapidocr/networks/architectures/__init__.py
rename to python/rapidocr/inference_engine/pytorch/networks/architectures/__init__.py
diff --git a/python/rapidocr/networks/architectures/base_model.py b/python/rapidocr/inference_engine/pytorch/networks/architectures/base_model.py
similarity index 100%
rename from python/rapidocr/networks/architectures/base_model.py
rename to python/rapidocr/inference_engine/pytorch/networks/architectures/base_model.py
diff --git a/python/rapidocr/networks/backbones/__init__.py b/python/rapidocr/inference_engine/pytorch/networks/backbones/__init__.py
similarity index 100%
rename from python/rapidocr/networks/backbones/__init__.py
rename to python/rapidocr/inference_engine/pytorch/networks/backbones/__init__.py
diff --git a/python/rapidocr/networks/backbones/det_mobilenet_v3.py b/python/rapidocr/inference_engine/pytorch/networks/backbones/det_mobilenet_v3.py
similarity index 100%
rename from python/rapidocr/networks/backbones/det_mobilenet_v3.py
rename to python/rapidocr/inference_engine/pytorch/networks/backbones/det_mobilenet_v3.py
diff --git a/python/rapidocr/networks/backbones/rec_donut_swin.py b/python/rapidocr/inference_engine/pytorch/networks/backbones/rec_donut_swin.py
similarity index 100%
rename from python/rapidocr/networks/backbones/rec_donut_swin.py
rename to python/rapidocr/inference_engine/pytorch/networks/backbones/rec_donut_swin.py
diff --git a/python/rapidocr/networks/backbones/rec_hgnet.py b/python/rapidocr/inference_engine/pytorch/networks/backbones/rec_hgnet.py
similarity index 100%
rename from python/rapidocr/networks/backbones/rec_hgnet.py
rename to python/rapidocr/inference_engine/pytorch/networks/backbones/rec_hgnet.py
diff --git a/python/rapidocr/networks/backbones/rec_lcnetv3.py b/python/rapidocr/inference_engine/pytorch/networks/backbones/rec_lcnetv3.py
similarity index 100%
rename from python/rapidocr/networks/backbones/rec_lcnetv3.py
rename to python/rapidocr/inference_engine/pytorch/networks/backbones/rec_lcnetv3.py
diff --git a/python/rapidocr/networks/backbones/rec_mobilenet_v3.py b/python/rapidocr/inference_engine/pytorch/networks/backbones/rec_mobilenet_v3.py
similarity index 100%
rename from python/rapidocr/networks/backbones/rec_mobilenet_v3.py
rename to python/rapidocr/inference_engine/pytorch/networks/backbones/rec_mobilenet_v3.py
diff --git a/python/rapidocr/networks/backbones/rec_mv1_enhance.py b/python/rapidocr/inference_engine/pytorch/networks/backbones/rec_mv1_enhance.py
similarity index 81%
rename from python/rapidocr/networks/backbones/rec_mv1_enhance.py
rename to python/rapidocr/inference_engine/pytorch/networks/backbones/rec_mv1_enhance.py
index 447c48f..d475cf0 100644
--- a/python/rapidocr/networks/backbones/rec_mv1_enhance.py
+++ b/python/rapidocr/inference_engine/pytorch/networks/backbones/rec_mv1_enhance.py
@@ -1,4 +1,3 @@
-import os, sys
import torch
import torch.nn as nn
import torch.nn.functional as F
@@ -7,15 +6,17 @@ from ..common import Activation
class ConvBNLayer(nn.Module):
- def __init__(self,
- num_channels,
- filter_size,
- num_filters,
- stride,
- padding,
- channels=None,
- num_groups=1,
- act='hard_swish'):
+ def __init__(
+ self,
+ num_channels,
+ filter_size,
+ num_filters,
+ stride,
+ padding,
+ channels=None,
+ num_groups=1,
+ act="hard_swish",
+ ):
super(ConvBNLayer, self).__init__()
self.act = act
self._conv = nn.Conv2d(
@@ -25,7 +26,8 @@ class ConvBNLayer(nn.Module):
stride=stride,
padding=padding,
groups=num_groups,
- bias=False)
+ bias=False,
+ )
self._batch_norm = nn.BatchNorm2d(
num_filters,
@@ -42,16 +44,18 @@ class ConvBNLayer(nn.Module):
class DepthwiseSeparable(nn.Module):
- def __init__(self,
- num_channels,
- num_filters1,
- num_filters2,
- num_groups,
- stride,
- scale,
- dw_size=3,
- padding=1,
- use_se=False):
+ def __init__(
+ self,
+ num_channels,
+ num_filters1,
+ num_filters2,
+ num_groups,
+ stride,
+ scale,
+ dw_size=3,
+ padding=1,
+ use_se=False,
+ ):
super(DepthwiseSeparable, self).__init__()
self.use_se = use_se
self._depthwise_conv = ConvBNLayer(
@@ -60,7 +64,8 @@ class DepthwiseSeparable(nn.Module):
filter_size=dw_size,
stride=stride,
padding=padding,
- num_groups=int(num_groups * scale))
+ num_groups=int(num_groups * scale),
+ )
if use_se:
self._se = SEModule(int(num_filters1 * scale))
self._pointwise_conv = ConvBNLayer(
@@ -68,7 +73,8 @@ class DepthwiseSeparable(nn.Module):
filter_size=1,
num_filters=int(num_filters2 * scale),
stride=1,
- padding=0)
+ padding=0,
+ )
def forward(self, inputs):
y = self._depthwise_conv(inputs)
@@ -79,12 +85,14 @@ class DepthwiseSeparable(nn.Module):
class MobileNetV1Enhance(nn.Module):
- def __init__(self,
- in_channels=3,
- scale=0.5,
- last_conv_stride=1,
- last_pool_type='max',
- **kwargs):
+ def __init__(
+ self,
+ in_channels=3,
+ scale=0.5,
+ last_conv_stride=1,
+ last_pool_type="max",
+ **kwargs
+ ):
super().__init__()
self.scale = scale
self.block_list = []
@@ -95,7 +103,8 @@ class MobileNetV1Enhance(nn.Module):
channels=3,
num_filters=int(32 * scale),
stride=2,
- padding=1)
+ padding=1,
+ )
conv2_1 = DepthwiseSeparable(
num_channels=int(32 * scale),
@@ -103,7 +112,8 @@ class MobileNetV1Enhance(nn.Module):
num_filters2=64,
num_groups=32,
stride=1,
- scale=scale)
+ scale=scale,
+ )
self.block_list.append(conv2_1)
conv2_2 = DepthwiseSeparable(
@@ -112,7 +122,8 @@ class MobileNetV1Enhance(nn.Module):
num_filters2=128,
num_groups=64,
stride=1,
- scale=scale)
+ scale=scale,
+ )
self.block_list.append(conv2_2)
conv3_1 = DepthwiseSeparable(
@@ -121,7 +132,8 @@ class MobileNetV1Enhance(nn.Module):
num_filters2=128,
num_groups=128,
stride=1,
- scale=scale)
+ scale=scale,
+ )
self.block_list.append(conv3_1)
conv3_2 = DepthwiseSeparable(
@@ -130,7 +142,8 @@ class MobileNetV1Enhance(nn.Module):
num_filters2=256,
num_groups=128,
stride=(2, 1),
- scale=scale)
+ scale=scale,
+ )
self.block_list.append(conv3_2)
conv4_1 = DepthwiseSeparable(
@@ -139,7 +152,8 @@ class MobileNetV1Enhance(nn.Module):
num_filters2=256,
num_groups=256,
stride=1,
- scale=scale)
+ scale=scale,
+ )
self.block_list.append(conv4_1)
conv4_2 = DepthwiseSeparable(
@@ -148,7 +162,8 @@ class MobileNetV1Enhance(nn.Module):
num_filters2=512,
num_groups=256,
stride=(2, 1),
- scale=scale)
+ scale=scale,
+ )
self.block_list.append(conv4_2)
for _ in range(5):
@@ -161,7 +176,8 @@ class MobileNetV1Enhance(nn.Module):
dw_size=5,
padding=2,
scale=scale,
- use_se=False)
+ use_se=False,
+ )
self.block_list.append(conv5)
conv5_6 = DepthwiseSeparable(
@@ -173,7 +189,8 @@ class MobileNetV1Enhance(nn.Module):
dw_size=5,
padding=2,
scale=scale,
- use_se=True)
+ use_se=True,
+ )
self.block_list.append(conv5_6)
conv6 = DepthwiseSeparable(
@@ -185,11 +202,12 @@ class MobileNetV1Enhance(nn.Module):
dw_size=5,
padding=2,
use_se=True,
- scale=scale)
+ scale=scale,
+ )
self.block_list.append(conv6)
self.block_list = nn.Sequential(*self.block_list)
- if last_pool_type == 'avg':
+ if last_pool_type == "avg":
self.pool = nn.AvgPool2d(kernel_size=2, stride=2, padding=0)
else:
self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
@@ -201,8 +219,10 @@ class MobileNetV1Enhance(nn.Module):
y = self.pool(y)
return y
+
def hardsigmoid(x):
- return F.relu6(x + 3., inplace=True) / 6.
+ return F.relu6(x + 3.0, inplace=True) / 6.0
+
class SEModule(nn.Module):
def __init__(self, channel, reduction=4):
@@ -214,14 +234,16 @@ class SEModule(nn.Module):
kernel_size=1,
stride=1,
padding=0,
- bias=True)
+ bias=True,
+ )
self.conv2 = nn.Conv2d(
in_channels=channel // reduction,
out_channels=channel,
kernel_size=1,
stride=1,
padding=0,
- bias=True)
+ bias=True,
+ )
def forward(self, inputs):
outputs = self.avg_pool(inputs)
diff --git a/python/rapidocr/networks/backbones/rec_pphgnetv2.py b/python/rapidocr/inference_engine/pytorch/networks/backbones/rec_pphgnetv2.py
similarity index 100%
rename from python/rapidocr/networks/backbones/rec_pphgnetv2.py
rename to python/rapidocr/inference_engine/pytorch/networks/backbones/rec_pphgnetv2.py
diff --git a/python/rapidocr/networks/backbones/rec_svtrnet.py b/python/rapidocr/inference_engine/pytorch/networks/backbones/rec_svtrnet.py
similarity index 100%
rename from python/rapidocr/networks/backbones/rec_svtrnet.py
rename to python/rapidocr/inference_engine/pytorch/networks/backbones/rec_svtrnet.py
diff --git a/python/rapidocr/networks/common.py b/python/rapidocr/inference_engine/pytorch/networks/common.py
similarity index 100%
rename from python/rapidocr/networks/common.py
rename to python/rapidocr/inference_engine/pytorch/networks/common.py
diff --git a/python/rapidocr/networks/heads/__init__.py b/python/rapidocr/inference_engine/pytorch/networks/heads/__init__.py
similarity index 100%
rename from python/rapidocr/networks/heads/__init__.py
rename to python/rapidocr/inference_engine/pytorch/networks/heads/__init__.py
diff --git a/python/rapidocr/networks/heads/cls_head.py b/python/rapidocr/inference_engine/pytorch/networks/heads/cls_head.py
similarity index 100%
rename from python/rapidocr/networks/heads/cls_head.py
rename to python/rapidocr/inference_engine/pytorch/networks/heads/cls_head.py
diff --git a/python/rapidocr/networks/heads/det_db_head.py b/python/rapidocr/inference_engine/pytorch/networks/heads/det_db_head.py
similarity index 100%
rename from python/rapidocr/networks/heads/det_db_head.py
rename to python/rapidocr/inference_engine/pytorch/networks/heads/det_db_head.py
diff --git a/python/rapidocr/networks/heads/rec_ctc_head.py b/python/rapidocr/inference_engine/pytorch/networks/heads/rec_ctc_head.py
similarity index 100%
rename from python/rapidocr/networks/heads/rec_ctc_head.py
rename to python/rapidocr/inference_engine/pytorch/networks/heads/rec_ctc_head.py
diff --git a/python/rapidocr/networks/heads/rec_multi_head.py b/python/rapidocr/inference_engine/pytorch/networks/heads/rec_multi_head.py
similarity index 100%
rename from python/rapidocr/networks/heads/rec_multi_head.py
rename to python/rapidocr/inference_engine/pytorch/networks/heads/rec_multi_head.py
diff --git a/python/rapidocr/inference_engine/pytorch/networks/main.py b/python/rapidocr/inference_engine/pytorch/networks/main.py
new file mode 100644
index 0000000..c40bdcf
--- /dev/null
+++ b/python/rapidocr/inference_engine/pytorch/networks/main.py
@@ -0,0 +1,67 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from pathlib import Path
+
+import torch
+from omegaconf import OmegaConf
+
+from ....utils.download_file import DownloadFile, DownloadFileInput
+from ....utils.log import logger
+from ...base import FileInfo, InferSession
+from .architectures.base_model import BaseModel
+
+
+class ModelLoader:
+ root_dir = Path(__file__).resolve().parent
+ DEFAULT_CFG_PATH = root_dir / "arch_config.yaml"
+
+ def __init__(self, cfg, device: torch.device):
+ model_path = self._init_model_path(cfg)
+ arch_config = self._load_arch_config(model_path)
+
+ self.predictor = self._build_and_load_model(arch_config, model_path)
+ self.predictor.to(device)
+ self.predictor.eval()
+
+ def _init_model_path(self, cfg) -> Path:
+ model_path = cfg.get("model_path", None)
+ if model_path is None:
+ model_info = InferSession.get_model_url(
+ FileInfo(
+ engine_type=cfg.engine_type,
+ ocr_version=cfg.ocr_version,
+ task_type=cfg.task_type,
+ lang_type=cfg.lang_type,
+ model_type=cfg.model_type,
+ )
+ )
+ default_model_url = model_info["model_dir"]
+ model_path = InferSession.DEFAULT_MODEL_PATH / Path(default_model_url).name
+ DownloadFile.run(
+ DownloadFileInput(
+ file_url=default_model_url,
+ sha256=model_info["SHA256"],
+ save_path=model_path,
+ logger=logger,
+ )
+ )
+
+ logger.info(f"Using {model_path}")
+ InferSession._verify_model(model_path)
+ return Path(model_path)
+
+ def _load_arch_config(self, model_path: Path):
+ all_arch_config = OmegaConf.load(self.DEFAULT_CFG_PATH)
+
+ file_name = model_path.stem
+ if file_name not in all_arch_config:
+ raise ValueError(f"architecture {file_name} is not in arch_config.yaml")
+
+ return all_arch_config.get(file_name)
+
+ def _build_and_load_model(self, arch_config, model_path: Path):
+ model = BaseModel(arch_config)
+ state_dict = torch.load(model_path, map_location="cpu", weights_only=False)
+ model.load_state_dict(state_dict)
+ return model
diff --git a/python/rapidocr/networks/necks/__init__.py b/python/rapidocr/inference_engine/pytorch/networks/necks/__init__.py
similarity index 100%
rename from python/rapidocr/networks/necks/__init__.py
rename to python/rapidocr/inference_engine/pytorch/networks/necks/__init__.py
diff --git a/python/rapidocr/networks/necks/db_fpn.py b/python/rapidocr/inference_engine/pytorch/networks/necks/db_fpn.py
similarity index 100%
rename from python/rapidocr/networks/necks/db_fpn.py
rename to python/rapidocr/inference_engine/pytorch/networks/necks/db_fpn.py
diff --git a/python/rapidocr/networks/necks/intracl.py b/python/rapidocr/inference_engine/pytorch/networks/necks/intracl.py
similarity index 100%
rename from python/rapidocr/networks/necks/intracl.py
rename to python/rapidocr/inference_engine/pytorch/networks/necks/intracl.py
diff --git a/python/rapidocr/networks/necks/rnn.py b/python/rapidocr/inference_engine/pytorch/networks/necks/rnn.py
similarity index 100%
rename from python/rapidocr/networks/necks/rnn.py
rename to python/rapidocr/inference_engine/pytorch/networks/necks/rnn.py
diff --git a/python/rapidocr/inference_engine/torch.py b/python/rapidocr/inference_engine/torch.py
deleted file mode 100644
index 6877872..0000000
--- a/python/rapidocr/inference_engine/torch.py
+++ /dev/null
@@ -1,129 +0,0 @@
-# -*- encoding: utf-8 -*-
-# @Author: SWHL
-# @Contact: [email protected]
-from pathlib import Path
-
-import numpy as np
-import torch
-from omegaconf import OmegaConf
-
-from ..networks.architectures.base_model import BaseModel
-from ..utils.download_file import DownloadFile, DownloadFileInput
-from ..utils.log import logger
-from ..utils.utils import mkdir
-from .base import FileInfo, InferSession
-
-root_dir = Path(__file__).resolve().parent.parent
-DEFAULT_CFG_PATH = root_dir / "networks" / "arch_config.yaml"
-
-
-class TorchInferSession(InferSession):
- def __init__(self, cfg) -> None:
- model_path = self._init_model_path(cfg)
- arch_config = self._load_arch_config(model_path)
-
- self.predictor = self._build_and_load_model(arch_config, model_path)
-
- self._setup_device(cfg)
-
- self.predictor.eval()
-
- def _init_model_path(self, cfg) -> Path:
- model_path = cfg.get("model_path", None)
- if model_path is None:
- model_info = self.get_model_url(
- FileInfo(
- engine_type=cfg.engine_type,
- ocr_version=cfg.ocr_version,
- task_type=cfg.task_type,
- lang_type=cfg.lang_type,
- model_type=cfg.model_type,
- )
- )
- default_model_url = model_info["model_dir"]
- model_path = self.DEFAULT_MODEL_PATH / Path(default_model_url).name
- DownloadFile.run(
- DownloadFileInput(
- file_url=default_model_url,
- sha256=model_info["SHA256"],
- save_path=model_path,
- logger=logger,
- )
- )
-
- logger.info(f"Using {model_path}")
- self._verify_model(model_path)
- return Path(model_path)
-
- def _load_arch_config(self, model_path: Path):
- all_arch_config = OmegaConf.load(DEFAULT_CFG_PATH)
-
- file_name = model_path.stem
- if file_name not in all_arch_config:
- raise ValueError(f"architecture {file_name} is not in arch_config.yaml")
-
- return all_arch_config.get(file_name)
-
- def _build_and_load_model(self, arch_config, model_path: Path):
- model = BaseModel(arch_config)
- state_dict = torch.load(model_path, map_location="cpu", weights_only=False)
- model.load_state_dict(state_dict)
- return model
-
- def _setup_device(self, cfg):
- self.device, self.use_gpu, self.use_npu = self._resolve_device_config(cfg)
-
- if self.use_npu:
- self._config_npu()
-
- self._move_model_to_device()
-
- def _resolve_device_config(self, cfg):
- if cfg.engine_cfg.use_cuda:
- return torch.device(f"cuda:{cfg.engine_cfg.gpu_id}"), True, False
-
- if cfg.engine_cfg.use_npu:
- return torch.device(f"npu:{cfg.engine_cfg.npu_id}"), False, True
-
- return torch.device("cpu"), False, False
-
- def _config_npu(self):
- try:
- import torch_npu
-
- kernel_meta_dir = (root_dir / "kernel_meta").resolve()
- mkdir(kernel_meta_dir)
-
- options = {
- "ACL_OP_COMPILER_CACHE_MODE": "enable",
- "ACL_OP_COMPILER_CACHE_DIR": str(kernel_meta_dir),
- }
- torch_npu.npu.set_option(options)
- except ImportError:
- logger.warning(
- "torch_npu is not installed, options with ACL setting failed. \n"
- "Please refer to https://github.com/Ascend/pytorch to see how to install."
- )
-
- self.device = torch.device("cpu")
- self.use_npu = False
-
- def _move_model_to_device(self):
- self.predictor.to(self.device)
-
- def __call__(self, img: np.ndarray):
- with torch.no_grad():
- inp = torch.from_numpy(img)
- if self.use_gpu or self.use_npu:
- inp = inp.to(self.device)
-
- # 适配跟onnx对齐取值逻辑
- outputs = self.predictor(inp).cpu().numpy()
- return outputs
-
- def have_key(self, key: str = "character") -> bool:
- return False
-
-
-class TorchInferError(Exception):
- pass
diff --git a/python/rapidocr/networks/__init__.py b/python/rapidocr/networks/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/python/rapidocr/utils/typings.py b/python/rapidocr/utils/typings.py
index 4525b03..c35d29e 100644
--- a/python/rapidocr/utils/typings.py
+++ b/python/rapidocr/utils/typings.py
@@ -4,6 +4,12 @@
from enum import Enum
+class DeviceType(Enum):
+ CPU = "cpu"
+ CUDA = "cuda"
+ NPU = "npu"
+
+
class LangDet(Enum):
CH = "ch"
EN = "en"
diff --git a/python/tests/test_input.py b/python/tests/test_input.py
index cc744ec..d3d665d 100644
--- a/python/tests/test_input.py
+++ b/python/tests/test_input.py
@@ -50,7 +50,7 @@ def test_transparent_img(engine, img_name: str, gt: str):
def test_long_img(engine):
- img_url = "https://github.com/RapidAI/RapidOCR/releases/download/v1.1.0/long.jpeg"
+ img_url = "https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/resources/test_files/long.jpeg"
result = engine(img_url)
assert result is not None
@@ -65,7 +65,7 @@ def test_full_black_img(engine):
def test_img_url_input(engine):
- img_url = "https://github.com/RapidAI/RapidOCR/blob/a9bb7c1f44b6e00556ada90ac588f020d7637c4b/python/tests/test_files/ch_en_num.jpg?raw=true"
+ img_url = "https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/resources/test_files/ch_en_num.jpg"
result = engine(img_url)
assert result.txts is not None
assert result.txts[0] == "正品促销"