Download sumoocr/backend.py from docsumo/sumoOCR-tiny: direct link, hf CLI and curl.
- Browser
- Download file 2.74 kB
-
https://huggingface.co/docsumo/sumoOCR-tiny/resolve/main/sumoocr/backend.py
- Command line
-
hf download hf://docsumo/sumoOCR-tiny/sumoocr/backend.py
-
curl -L -o backend.py https://huggingface.co/docsumo/sumoOCR-tiny/resolve/main/sumoocr/backend.py
2.74 kB
| """Model runtimes: ONNX Runtime (default) or OpenVINO (`pip install sumoocr[openvino]`), CPU.""" | |
| from __future__ import annotations | |
| import os | |
| from typing import Optional | |
| import numpy as np | |
| BACKENDS = ("onnxruntime", "openvino") | |
| class ORTModel: | |
| def __init__(self, path: str, threads: Optional[int] = None, arena: bool = True): | |
| import onnxruntime as ort | |
| so = ort.SessionOptions() | |
| so.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL | |
| if threads: | |
| so.intra_op_num_threads = int(threads) | |
| so.inter_op_num_threads = 1 | |
| if int(threads) == 1: | |
| so.add_session_config_entry("session.intra_op.allow_spinning", "0") | |
| so.enable_cpu_mem_arena = bool(arena) | |
| so.log_severity_level = 3 | |
| self.sess = ort.InferenceSession(path, so, providers=["CPUExecutionProvider"]) | |
| self._in = self.sess.get_inputs()[0].name | |
| def __call__(self, x: np.ndarray) -> np.ndarray: | |
| return self.sess.run(None, {self._in: np.ascontiguousarray(x, dtype=np.float32)})[0] | |
| class OVModel: | |
| def __init__(self, path: str, threads: Optional[int] = None, fix_height: int = 0): | |
| os.environ.setdefault("CI", "true") # openvino_telemetry: never prompt | |
| import platform | |
| import openvino as ov | |
| core = ov.Core() | |
| model = core.read_model(path) | |
| if fix_height: # recognizer: fixed height, dynamic batch and width | |
| inp = model.inputs[0] | |
| ps = inp.get_partial_shape() | |
| if ps.rank.is_static and len(ps) == 4 and ps[2].is_dynamic: | |
| model.reshape({inp.get_any_name(): ov.PartialShape([-1, ps[1], int(fix_height), -1])}) | |
| props = {"NUM_STREAMS": 1, "PERFORMANCE_HINT": "LATENCY", "INFERENCE_PRECISION_HINT": "f32"} | |
| if any(op.get_type_name() == "FakeQuantize" for op in model.get_ops()) and \ | |
| platform.machine().lower() not in ("x86_64", "amd64"): | |
| props["LP_TRANSFORMS_MODE"] = False | |
| if threads: | |
| props["INFERENCE_NUM_THREADS"] = int(threads) | |
| self.req = core.compile_model(model, "CPU", props).create_infer_request() | |
| def __call__(self, x: np.ndarray) -> np.ndarray: | |
| self.req.infer({0: np.ascontiguousarray(x, dtype=np.float32)}, share_inputs=True) | |
| return self.req.get_output_tensor(0).data.copy() | |
| def load_model(path: str, backend: str = "onnxruntime", threads: Optional[int] = None, fix_height: int = 0, | |
| arena: bool = True): | |
| if backend == "onnxruntime": | |
| return ORTModel(path, threads, arena=arena) | |
| if backend == "openvino": | |
| return OVModel(path, threads, fix_height) | |
| raise ValueError(f"backend must be one of {BACKENDS}, not {backend!r}") | |