1use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Mutex, OnceLock};
6
7use ort::execution_providers::ExecutionProvider;
8use ort::session::builder::GraphOptimizationLevel;
9use ort::session::Session;
10
11static EP_LOGGED: AtomicBool = AtomicBool::new(false);
14
15static ACTIVE_PROVIDER: Mutex<&'static str> = Mutex::new("Not initialized");
18#[cfg(target_os = "windows")]
19static WINDOWS_RUNTIME_LIBS: OnceLock<Vec<libloading::Library>> = OnceLock::new();
20static ORT_INITIALIZED: OnceLock<()> = OnceLock::new();
21static ORT_INIT_LOCK: Mutex<()> = Mutex::new(());
22
23pub fn active_execution_provider() -> &'static str {
26 *ACTIVE_PROVIDER.lock().unwrap_or_else(|e| e.into_inner())
27}
28
29#[cfg(target_os = "windows")]
31const ORT_LIB_NAME: &str = "onnxruntime.dll";
32#[cfg(target_os = "macos")]
33const ORT_LIB_NAME: &str = "libonnxruntime.dylib";
34#[cfg(not(any(target_os = "windows", target_os = "macos")))]
35const ORT_LIB_NAME: &str = "libonnxruntime.so";
36
37pub struct OnnxRuntime;
48
49impl OnnxRuntime {
50 fn usable_runtime_file(path: &Path) -> bool {
51 std::fs::metadata(path)
52 .is_ok_and(|metadata| metadata.is_file() && metadata.len() >= 1024 * 1024)
53 }
54
55 fn runtime_file_name_matches(name: &str) -> bool {
56 #[cfg(target_os = "macos")]
57 {
58 name.starts_with("libonnxruntime") && name.ends_with(".dylib")
59 }
60 #[cfg(not(target_os = "macos"))]
61 {
62 name.starts_with(ORT_LIB_NAME)
63 }
64 }
65
66 fn find_runtime_in_dir(dir: &Path) -> Option<PathBuf> {
67 let direct = dir.join(ORT_LIB_NAME);
68 if Self::usable_runtime_file(&direct) {
69 return Some(direct);
70 }
71
72 let entries = std::fs::read_dir(dir).ok()?;
74 for entry in entries.flatten() {
75 let path = entry.path();
76 if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
77 if Self::runtime_file_name_matches(name) && Self::usable_runtime_file(&path) {
78 return Some(path);
79 }
80 }
81 }
82
83 None
84 }
85
86 fn resolve_dylib_path() -> Option<PathBuf> {
91 if let Ok(path) = std::env::var("ORT_DYLIB_PATH") {
93 let p = PathBuf::from(&path);
94 if p.exists() {
95 tracing::info!("Using ONNX Runtime from ORT_DYLIB_PATH: {}", p.display());
96 return Some(p);
97 }
98 tracing::warn!("ORT_DYLIB_PATH set but file not found: {}", path);
99 }
100
101 if let Some(candidate) = crate::bootstrap::onnx_runtime_path() {
105 tracing::info!(
106 "Using ONNX Runtime from optional asset-pack path: {}",
107 candidate.display()
108 );
109 return Some(candidate);
110 }
111
112 let rel_dir = Path::new("libs").join("onnxruntime");
113
114 if let Ok(exe) = std::env::current_exe() {
119 if let Some(exe_dir) = exe.parent() {
120 for base in [exe_dir.to_path_buf(), exe_dir.join("..").join("..")] {
121 let candidate_dir = base.join(&rel_dir);
122 if let Some(candidate) = Self::find_runtime_in_dir(&candidate_dir) {
123 tracing::info!(
124 "Using ONNX Runtime from exe-relative path: {}",
125 candidate.display()
126 );
127 return Some(candidate);
128 }
129 }
130 }
131 }
132
133 if let Ok(cwd) = std::env::current_dir() {
137 let mut bases: Vec<PathBuf> = vec![cwd.clone()];
138 if let Some(parent) = cwd.parent() {
139 bases.push(parent.to_path_buf());
140 }
141 for base in bases {
142 let candidate_dir = base.join(&rel_dir);
143 if let Some(candidate) = Self::find_runtime_in_dir(&candidate_dir) {
144 tracing::info!(
145 "Using ONNX Runtime from cwd-relative path: {}",
146 candidate.display()
147 );
148 return Some(candidate);
149 }
150 }
151 }
152
153 None
154 }
155
156 pub fn init() -> ort::Result<Self> {
163 if ORT_INITIALIZED.get().is_some() {
164 return Ok(Self);
165 }
166
167 let _guard = ORT_INIT_LOCK.lock().map_err(|_| {
168 ort::Error::new("ONNX Runtime initialization lock is poisoned".to_string())
169 })?;
170 if ORT_INITIALIZED.get().is_some() {
171 return Ok(Self);
172 }
173
174 if let Some(dylib_path) = Self::resolve_dylib_path() {
175 #[cfg(target_os = "windows")]
176 if WINDOWS_RUNTIME_LIBS.get().is_none() {
177 use libloading::os::windows::{
178 Library, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR,
179 };
180 let root = dylib_path
181 .parent()
182 .ok_or_else(|| ort::Error::new("Runtime path has no parent"))?;
183 let mut libraries = Vec::new();
184 for dependency in [
185 "DirectML.dll",
186 "onnxruntime_providers_shared.dll",
187 ORT_LIB_NAME,
188 ] {
189 let path = root.join(dependency);
190 if !path.is_file() {
191 continue;
192 } let library = unsafe {
197 Library::load_with_flags(
198 &path,
199 LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS,
200 )
201 }
202 .map_err(|e| {
203 ort::Error::new(format!("Failed loading {}: {e}", path.display()))
204 })?;
205 libraries.push(library.into());
206 }
207 let _ = WINDOWS_RUNTIME_LIBS.set(libraries);
208 }
209 ort::init_from(&dylib_path)?.commit();
210 let _ = ORT_INITIALIZED.set(());
211 tracing::info!(
212 "ONNX Runtime initialized (dynamic) from: {}",
213 dylib_path.display()
214 );
215 } else {
216 return Err(ort::Error::new(
217 format!(
218 "ONNX Runtime library not found. Set ORT_DYLIB_PATH or place {} (1.23.x) in libs/onnxruntime/",
219 ORT_LIB_NAME
220 ),
221 ));
222 }
223 Ok(Self)
224 }
225
226 pub fn load_model_with_threads<P: AsRef<Path>>(
240 &self,
241 path: P,
242 intra_threads: usize,
243 ) -> ort::Result<Session> {
244 let path = path.as_ref();
247 let providers = vec![
248 #[cfg(target_os = "windows")]
249 (
250 "DirectML registered (placement unverified)",
251 ort::execution_providers::DirectMLExecutionProvider::default().build(),
252 ),
253 #[cfg(target_os = "linux")]
254 (
255 "CUDA registered (placement unverified)",
256 ort::execution_providers::CUDAExecutionProvider::default().build(),
257 ),
258 #[cfg(target_os = "linux")]
259 (
260 "OpenVINO registered (placement unverified)",
261 ort::execution_providers::OpenVINO::default()
262 .with_device_type("GPU")
263 .build(),
264 ),
265 #[cfg(target_os = "macos")]
266 (
267 "CoreML registered (placement unverified)",
268 ort::execution_providers::CoreMLExecutionProvider::default().build(),
269 ),
270 (
271 "CPU",
272 ort::execution_providers::CPUExecutionProvider::default().build(),
273 ),
274 ];
275
276 if !EP_LOGGED.swap(true, Ordering::Relaxed) {
277 Self::probe_and_log_providers();
278 }
279 let mut last_error = None;
280 for (label, provider) in providers {
281 let attempt = (|| {
282 let builder = Session::builder()?
283 .with_optimization_level(GraphOptimizationLevel::Level3)?
284 .with_intra_threads(intra_threads.clamp(1, 2))?
285 .with_parallel_execution(false)?
286 .with_config_entry("session.intra_op.allow_spinning", "0")?
287 .with_config_entry("session.inter_op.allow_spinning", "0")?;
288 let builder = if label.starts_with("DirectML") {
289 builder.with_memory_pattern(false)?
290 } else {
291 builder
292 };
293 builder
294 .with_execution_providers([provider.error_on_failure()])?
295 .commit_from_file(path)
296 })();
297 match attempt {
298 Ok(session) => {
299 let mut active = ACTIVE_PROVIDER.lock().unwrap_or_else(|e| e.into_inner());
300 *active = if *active == "Not initialized" || *active == label {
301 label
302 } else {
303 "Mixed model providers (see logs; placement unverified)"
304 };
305 tracing::info!(model = %path.display(), provider = label, "Inference session initialized");
306 return Ok(session);
307 }
308 Err(error) => {
309 tracing::warn!(model = %path.display(), provider = label, %error,
310 "Provider initialization failed; trying fallback");
311 last_error = Some(error);
312 }
313 }
314 }
315 Err(last_error.expect("CPU provider is always attempted"))
316 }
317
318 pub fn load_cpu_model(path: &Path) -> ort::Result<Session> {
320 let session = Self::load_cpu_model_with_threads(path, 1)?;
321 *ACTIVE_PROVIDER.lock().unwrap_or_else(|e| e.into_inner()) =
322 "CPU fallback used (see per-model logs)";
323 tracing::warn!(model = %path.display(), "Inference moved to CPU after device/provider failure");
324 Ok(session)
325 }
326
327 pub fn load_cpu_model_with_threads(path: &Path, intra_threads: usize) -> ort::Result<Session> {
333 let session = Session::builder()?
334 .with_optimization_level(GraphOptimizationLevel::Level3)?
335 .with_intra_threads(intra_threads.max(1))?
336 .with_parallel_execution(false)?
337 .with_config_entry("session.intra_op.allow_spinning", "0")?
338 .with_config_entry("session.inter_op.allow_spinning", "0")?
339 .with_execution_providers([ort::execution_providers::CPUExecutionProvider::default()
340 .build()
341 .error_on_failure()])?
342 .commit_from_file(path)?;
343 let mut active = ACTIVE_PROVIDER.lock().unwrap_or_else(|e| e.into_inner());
344 *active = if *active == "Not initialized" || *active == "CPU" {
345 "CPU"
346 } else {
347 "Mixed model providers (see logs; placement unverified)"
348 };
349 tracing::info!(model = %path.display(), threads = intra_threads.max(1), "CPU inference session initialized");
350 Ok(session)
351 }
352
353 pub fn load_cpu_model_for_interactive(path: &Path) -> ort::Result<Session> {
358 let session = Session::builder()?
359 .with_optimization_level(GraphOptimizationLevel::Level1)?
360 .with_intra_threads(1)?
361 .with_parallel_execution(false)?
362 .with_config_entry("session.intra_op.allow_spinning", "0")?
363 .with_config_entry("session.inter_op.allow_spinning", "0")?
364 .with_execution_providers([ort::execution_providers::CPUExecutionProvider::default()
365 .build()
366 .error_on_failure()])?
367 .commit_from_file(path)?;
368 tracing::info!(model = %path.display(), "Interactive CPU inference session initialized");
369 Ok(session)
370 }
371
372 fn probe_and_log_providers() {
385 let mut accelerated: Vec<&'static str> = Vec::new();
386
387 #[cfg(target_os = "windows")]
388 {
389 let ep = ort::execution_providers::DirectMLExecutionProvider::default();
390 if ep.is_available().unwrap_or(false) {
391 accelerated.push("DirectML");
392 }
393 }
394
395 #[cfg(target_os = "linux")]
396 {
397 let ep = ort::execution_providers::CUDAExecutionProvider::default();
398 if ep.is_available().unwrap_or(false) {
399 accelerated.push("CUDA");
400 }
401
402 let ep = ort::execution_providers::OpenVINO::default();
403 if ep.is_available().unwrap_or(false) {
404 accelerated.push("OpenVINO");
405 }
406 }
407
408 #[cfg(target_os = "macos")]
409 {
410 let ep = ort::execution_providers::CoreMLExecutionProvider::default();
411 if ep.is_available().unwrap_or(false) {
412 accelerated.push("CoreML");
413 }
414 }
415
416 tracing::info!(
417 accelerated = %if accelerated.is_empty() { "none".to_string() } else { accelerated.join(", ") },
418 "Execution providers present. Face detection/embedding always run on CPU; \
419 the provider-selecting path (semantic search) tries accelerated providers first, \
420 then CPU."
421 );
422 }
423}