|
| 1 | +import onnxruntime |
| 2 | +from typing import Any, Dict, List |
| 3 | + |
| 4 | +class ONNXModule: |
| 5 | + """ |
| 6 | + A class that encapsulates an ONNX model for inference. |
| 7 | +
|
| 8 | + Attributes: |
| 9 | + weight (str): Path to the ONNX model file. |
| 10 | + session (onnxruntime.InferenceSession): The ONNX Runtime inference session for the model. |
| 11 | +
|
| 12 | + Methods: |
| 13 | + __init__(self, weight: str): Initializes the EnhancedONNXModule instance. |
| 14 | + __init_engine(self): Initializes the ONNX Runtime inference engine. |
| 15 | + __call__(self, inputs: Dict[str, Any]): Performs inference on the given inputs. |
| 16 | + """ |
| 17 | + |
| 18 | + def __init__(self, weight: str) -> None: |
| 19 | + """ |
| 20 | + Initializes the EnhancedONNXModule with the given ONNX model. |
| 21 | +
|
| 22 | + Parameters: |
| 23 | + weight (str): The path to the ONNX model file. |
| 24 | + """ |
| 25 | + self.weight = weight |
| 26 | + self.session: onnxruntime.InferenceSession = self.__init_engine() |
| 27 | + |
| 28 | + def __init_engine(self) -> onnxruntime.InferenceSession: |
| 29 | + """ |
| 30 | + Initializes the ONNX Runtime inference engine with the model. |
| 31 | +
|
| 32 | + Returns: |
| 33 | + onnxruntime.InferenceSession: The initialized inference session. |
| 34 | + """ |
| 35 | + try: |
| 36 | + session = onnxruntime.InferenceSession(self.weight, providers=['CPUExecutionProvider']) |
| 37 | + return session |
| 38 | + except onnxruntime.OnnxRuntimeException as e: |
| 39 | + raise RuntimeError(f"Failed to initialize ONNX Runtime session: {e}") |
| 40 | + |
| 41 | + def __call__(self, inputs: Dict[str, Any]) -> List[Any]: |
| 42 | + """ |
| 43 | + Performs inference on the provided inputs using the ONNX model. |
| 44 | +
|
| 45 | + Parameters: |
| 46 | + inputs (Dict[str, Any]): The inputs for the model inference. Keys are input names, and values are input tensors. |
| 47 | +
|
| 48 | + Returns: |
| 49 | + List[Any]: The outputs from the model inference. |
| 50 | + """ |
| 51 | + try: |
| 52 | + outputs = self.session.run(None, inputs) |
| 53 | + return outputs |
| 54 | + except Exception as e: |
| 55 | + raise RuntimeError(f"Inference failed: {e}") |
0 commit comments