Skip to content

Onnx Model Session

Shared ONNX Runtime session lifecycle for ONNX-backed media toolkit components.

OnnxModelSession owns one model's source and its lazily created ONNX Runtime session. The module also validates ONNX Runtime execution providers and CPU thread counts so every ONNX backend applies the same rules.

OnnxModelSession(owner_name, component, task, usage, model_identifier, input_name_resolver, is_builtin=False, source_path=None, num_threads=None, providers=None)

Own one ONNX model's source and its lazily created ONNX Runtime session.

The lifecycle is: 1. The model source starts as a local ONNX path, or is set later to a path or verified in-memory bytes with set_model_source. 2. ensure_session creates one session at most once across threads, validates its inputs, and drops in-memory bytes once the session holds the model. 3. close releases the session and in-memory bytes; later use raises MediaOperationFailedError. A session still running inference on another thread is released when its last run finishes, so close never tears down a session in use. Runs are counted rather than serialized, so concurrent inference stays parallel.

Execution providers default to CPUExecutionProvider. Other providers, such as OpenVINOExecutionProvider or CUDAExecutionProvider, need the ONNX Runtime package that ships them (for example onnxruntime-openvino or onnxruntime-gpu) installed in place of onnxruntime. Requested providers are checked against the installed build so a missing one raises instead of silently falling back to CPU.

Intra-op thread spinning is disabled because inference runs between CPU-bound pre- and post-processing steps, and idle worker threads busy-waiting for the next run would take CPU away from that work.

Error messages name the owner's component and task, and the model identifier, never the model path, so a private local file name cannot leak through them.

Attributes:

Name Type Description
num_threads int | None

ONNX Runtime CPU intra-op thread count, or None to let ONNX Runtime choose.

providers tuple[ExecutionProvider, ...]

ONNX Runtime execution providers in priority order.

Initialize an open model session holder without I/O.

Parameters:

Name Type Description Default
owner_name str

Class name of the owner, such as "OnnxPPOCRTextDetector". Used by the optional-package check.

required
component str

Friendly component name used in configuration errors, such as "Text detector".

required
task str

Friendly task name used in operation errors, such as "text detection".

required
usage str

The owner call that needs loaded weights, such as "detect()".

required
model_identifier str

Safe model identifier used in local file errors, such as "ppocr". Never a path.

required
input_name_resolver Callable[[Sequence[Any]], str]

Validates a new session's ONNX inputs and returns the image input name. Any exception it raises releases the session and propagates unchanged.

required
is_builtin bool

Whether the source is a built-in model, which selects the built-in load failure over the local file failure. Defaults to False.

False
source_path Path | None

Readable local ONNX path, or None when the source is set later with set_model_source. Defaults to None.

None
num_threads int | None

ONNX Runtime CPU intra-op thread count. None or 0 lets ONNX Runtime choose. Defaults to None.

None
providers Sequence[ExecutionProvider] | None

ONNX Runtime execution providers in priority order, each a provider name or a (name, options) pair. None uses CPUExecutionProvider. Defaults to None.

None

Raises:

Type Description
ComponentConfigError

If num_threads is negative or not an integer, or providers is empty or contains a malformed entry.

is_closed property

Return whether close has been called.

Returns:

Name Type Description
bool bool

Whether the holder is closed.

model_data property

Return the in-memory ONNX weights not yet handed to a session.

Returns:

Type Description
bytes | None

bytes | None: Verified model bytes, or None once a session or path holds them.

session property

Return the live ONNX Runtime session, if one was created.

Returns:

Type Description
Any | None

Any | None: The session, or None before first use or after close.

source_path property

Return the local ONNX path the session is built from, if any.

Returns:

Type Description
Path | None

Path | None: Local or cached ONNX path, or None for in-memory weights.

close()

Idempotently release the session and in-memory model bytes.

This method is safe to call multiple times and from multiple threads. New runs fail as soon as it returns. When runs are still in flight, the session is released by the last of them to finish instead of here.

ensure_model_source(resolve_model_source) async

Resolve and store the model source once, sharing one resolution across concurrent callers.

Parameters:

Name Type Description Default
resolve_model_source Callable[[], Awaitable[Path | bytes]]

Coroutine factory that downloads or loads the weights, returning a cached path or verified bytes. It is awaited only when no model source is set yet.

required

Raises:

Type Description
MediaOperationFailedError

If the holder has been closed.

ensure_open()

Raise after explicit lifecycle closure.

Raises:

Type Description
MediaOperationFailedError

If close has already been called.

ensure_session()

Return the session and its image input name, creating them at most once across threads.

Returns:

Type Description
tuple[Any, str]

tuple[Any, str]: The reused or newly created session and its image input name.

Raises:

Type Description
MediaOperationFailedError

If the holder is closed, or ONNX Runtime cannot load a built-in model.

ComponentConfigError

If the ONNX inputs do not fit the owner's model.

ComponentModelError

If ONNX Runtime cannot load a local model file.

MediaOperationConfigError

If no model source is set yet.

MediaBackendUnavailableError

If a requested execution provider is not installed.

ImportError

If onnxruntime is not installed.

has_model_source()

Return whether a session can be used or created without further preparation.

Returns:

Name Type Description
bool bool

Whether a local path, in-memory weights, or a live session exists.

run(batch)

Run the session, created on first use, on one batch and return its first output.

Parameters:

Name Type Description Default
batch Any

Input tensor fed to the session's image input.

required

Returns:

Name Type Description
Any Any

The session's first output tensor.

Raises:

Type Description
MediaOperationFailedError

If the holder is closed, ONNX Runtime fails on the input, or the session returns no output tensors.

ComponentConfigError

If the ONNX inputs do not fit the owner's model.

ComponentModelError

If ONNX Runtime cannot load a local model file.

MediaOperationConfigError

If no model source is set yet.

MediaBackendUnavailableError

If a requested execution provider is not installed.

ImportError

If onnxruntime is not installed.

set_model_source(model_source)

Store resolved weights as the source of the next session.

Parameters:

Name Type Description Default
model_source Path | bytes

Cached ONNX path or verified in-memory model bytes.

required

Raises:

Type Description
MediaOperationFailedError

If the holder has been closed.

execution_provider_names(providers)

Return the provider name of each execution provider entry.

Parameters:

Name Type Description Default
providers Sequence[ExecutionProvider]

Validated provider names or (name, options) pairs.

required

Returns:

Type Description
list[str]

list[str]: Provider names in their given order.

local_model_file_error(model_identifier, debug_info=None)

Build the error for a local model file that is missing, unreadable, or cannot be loaded.

Parameters:

Name Type Description Default
model_identifier str

Safe model identifier, such as "ppocr". Never a path.

required
debug_info dict[str, str] | None

Sanitized diagnostic context. Defaults to None.

None

Returns:

Name Type Description
ComponentModelError ComponentModelError

Error that names the model identifier without its path.

release_onnx_session(session)

Release an ONNX Runtime session through whichever teardown hook it exposes.

Parameters:

Name Type Description Default
session Any | None

Session to release, or None when never created.

required

validate_execution_providers(providers, component)

Validate ONNX Runtime execution providers and apply the CPU default.

Parameters:

Name Type Description Default
providers Sequence[ExecutionProvider] | None

Provider names or (name, options) pairs in priority order, or None for CPUExecutionProvider.

required
component str

Friendly component name reported in the error, such as "Text detector".

required

Returns:

Type Description
tuple[ExecutionProvider, ...]

tuple[ExecutionProvider, ...]: The validated providers in their given order.

Raises:

Type Description
ComponentConfigError

If providers is a string, is empty, or contains an entry that is not a non-empty name or a (name, options) pair with a dict of options.

validate_local_cache_dir(local_path, cache_dir, component)

Reject a cache directory supplied together with a local model file.

Parameters:

Name Type Description Default
local_path Path | None

The local model file, or None for a built-in model.

required
cache_dir str | Path | None

The persistent weight cache root, or None.

required
component str

Friendly component name reported in the error, such as "Text detector".

required

Raises:

Type Description
ComponentConfigError

If a local model file and a cache directory are both given.

validate_num_threads(num_threads, component)

Validate an ONNX Runtime CPU intra-op thread count.

Parameters:

Name Type Description Default
num_threads int | None

Thread count, or None to let ONNX Runtime choose.

required
component str

Friendly component name reported in the error, such as "Text detector".

required

Raises:

Type Description
ComponentConfigError

If num_threads is not None or a non-negative integer.