1use std::ffi::CString;
20use std::path::Path;
21use std::sync::{Arc, Mutex};
22
23use transcribe_cpp_sys as sys;
24use transcribe_cpp_types::{
25 Backend, Capabilities, DiarizeInfo, DiarizeSessionOptions, ExtSlot, Feature, LangIdInfo,
26 LangIdSessionOptions, Roles, SessionOptions, TimestampKind, TurnInfo, TurnSessionOptions,
27 VadInfo, VadSessionOptions,
28};
29
30use crate::backend::Device;
31use crate::diarize::DiarizeSession;
32use crate::error::{check, Error, Result};
33use crate::langid::LangIdSession;
34use crate::result::owned_str;
35use crate::session::Session;
36use crate::turn::TurnSession;
37use crate::types::{FromRaw, ToRaw};
38use crate::vad::VadSession;
39use crate::version;
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct ModelOptions {
44 pub backend: Backend,
47 pub device: Option<crate::Device>,
50 pub no_mmap: bool,
57}
58
59impl Default for ModelOptions {
60 fn default() -> Self {
61 ModelOptions {
62 backend: Backend::Auto,
63 device: None,
64 no_mmap: false,
65 }
66 }
67}
68
69pub(crate) struct ModelInner {
71 pub(crate) ptr: *mut sys::transcribe_model,
72 pub(crate) compute_lock: Mutex<bool>,
79}
80
81impl ModelInner {
82 pub(crate) fn with_compute<R>(
86 &self,
87 refuse_if_streaming: Option<&str>,
88 f: impl FnOnce(&mut bool) -> R,
89 ) -> Result<R> {
90 let mut lease = self.compute_lock.lock().unwrap_or_else(|e| e.into_inner());
91 if let Some(msg) = refuse_if_streaming {
92 if *lease {
93 return Err(Error::Busy(msg.into()));
94 }
95 }
96 Ok(f(&mut lease))
97 }
98}
99
100unsafe impl Send for ModelInner {}
104unsafe impl Sync for ModelInner {}
105
106impl Drop for ModelInner {
107 fn drop(&mut self) {
108 unsafe { sys::transcribe_model_free(self.ptr) };
110 }
111}
112
113#[derive(Clone)]
115pub struct Model {
116 pub(crate) inner: Arc<ModelInner>,
117}
118
119impl std::fmt::Debug for Model {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 f.debug_struct("Model")
122 .field("arch", &self.arch())
123 .field("variant", &self.variant())
124 .field("backend", &self.backend())
125 .finish()
126 }
127}
128
129impl Model {
130 pub fn load(path: impl AsRef<Path>) -> Result<Model> {
134 Model::load_with(path, &ModelOptions::default())
135 }
136
137 pub fn load_with(path: impl AsRef<Path>, options: &ModelOptions) -> Result<Model> {
139 version::ensure_compatible()?;
141
142 let path = path.as_ref();
143 let c_path = CString::new(path_bytes(path)?)?;
144
145 let mut params: sys::transcribe_model_load_params = unsafe { std::mem::zeroed() };
146 unsafe { sys::transcribe_model_load_params_init(&mut params) };
147 params.backend = options.backend.to_raw();
148 params.device = options
149 .device
150 .as_ref()
151 .map_or(std::ptr::null_mut(), |device| device.handle);
152 params.no_mmap = options.no_mmap;
153
154 let mut out: *mut sys::transcribe_model = std::ptr::null_mut();
155 let status = unsafe { sys::transcribe_model_load_file(c_path.as_ptr(), ¶ms, &mut out) };
156 check_model_load(status, &format!("load {}", path.display()))?;
157 debug_assert!(!out.is_null());
158
159 Ok(Model {
160 inner: Arc::new(ModelInner {
161 ptr: out,
162 compute_lock: Mutex::new(false),
163 }),
164 })
165 }
166
167 pub fn session(&self) -> Result<Session> {
169 self.session_with(&SessionOptions::default())
170 }
171
172 pub fn session_with(&self, options: &SessionOptions) -> Result<Session> {
174 Session::new(self, options)
175 }
176
177 pub fn diarize_session(&self) -> Result<DiarizeSession> {
180 self.diarize_session_with(&DiarizeSessionOptions::default())
181 }
182
183 pub fn diarize_session_with(&self, options: &DiarizeSessionOptions) -> Result<DiarizeSession> {
185 DiarizeSession::new(self, options)
186 }
187
188 pub fn diarize_info(&self) -> Result<DiarizeInfo> {
191 let mut raw: sys::transcribe_diarize_info = unsafe { std::mem::zeroed() };
192 unsafe { sys::transcribe_diarize_info_init(&mut raw) };
193 check(
194 unsafe { sys::transcribe_diarize_get_info(self.inner.ptr, &mut raw) },
195 "diarize info",
196 )?;
197 let mut info = DiarizeInfo::default();
198 info.sample_rate = raw.sample_rate;
199 info.max_speakers = raw.max_speakers;
200 Ok(info)
201 }
202
203 pub fn langid_session(&self) -> Result<LangIdSession> {
206 self.langid_session_with(&LangIdSessionOptions::default())
207 }
208
209 pub fn langid_session_with(&self, options: &LangIdSessionOptions) -> Result<LangIdSession> {
211 LangIdSession::new(self, options)
212 }
213
214 pub fn langid_info(&self) -> Result<LangIdInfo> {
217 let mut raw: sys::transcribe_langid_info = unsafe { std::mem::zeroed() };
218 unsafe { sys::transcribe_langid_info_init(&mut raw) };
219 check(
220 unsafe { sys::transcribe_langid_get_info(self.inner.ptr, &mut raw) },
221 "langid info",
222 )?;
223 let mut info = LangIdInfo::default();
224 info.sample_rate = raw.sample_rate;
225 info.n_labels = raw.n_labels;
226 info.min_audio_ms = raw.min_audio_ms;
227 info.max_audio_ms = raw.max_audio_ms;
228 Ok(info)
229 }
230
231 pub fn langid_labels(&self) -> Result<Vec<(String, String)>> {
234 let n = self.langid_info()?.n_labels;
235 Ok((0..n)
236 .map(|i| unsafe {
237 (
238 owned_str(sys::transcribe_langid_label_code(self.inner.ptr, i)),
239 owned_str(sys::transcribe_langid_label_name(self.inner.ptr, i)),
240 )
241 })
242 .collect())
243 }
244
245 pub fn langid_label_index(&self, code: &str) -> Option<i32> {
248 let c = CString::new(code).ok()?;
249 let i = unsafe { sys::transcribe_langid_label_index(self.inner.ptr, c.as_ptr()) };
250 (i >= 0).then_some(i)
251 }
252
253 pub fn vad_session(&self) -> Result<VadSession> {
256 self.vad_session_with(&VadSessionOptions::default())
257 }
258
259 pub fn vad_session_with(&self, options: &VadSessionOptions) -> Result<VadSession> {
261 VadSession::new(self, options)
262 }
263
264 pub fn vad_info(&self) -> Result<VadInfo> {
267 let mut raw: sys::transcribe_vad_info = unsafe { std::mem::zeroed() };
268 unsafe { sys::transcribe_vad_info_init(&mut raw) };
269 check(
270 unsafe { sys::transcribe_vad_get_info(self.inner.ptr, &mut raw) },
271 "vad info",
272 )?;
273 let mut info = VadInfo::default();
274 info.sample_rate = raw.sample_rate;
275 info.frame_samples = raw.frame_samples;
276 Ok(info)
277 }
278
279 pub fn turn_session(&self) -> Result<TurnSession> {
282 self.turn_session_with(&TurnSessionOptions::default())
283 }
284
285 pub fn turn_session_with(&self, options: &TurnSessionOptions) -> Result<TurnSession> {
287 TurnSession::new(self, options)
288 }
289
290 pub fn turn_info(&self) -> Result<TurnInfo> {
293 let mut raw: sys::transcribe_turn_info = unsafe { std::mem::zeroed() };
294 unsafe { sys::transcribe_turn_info_init(&mut raw) };
295 check(
296 unsafe { sys::transcribe_turn_get_info(self.inner.ptr, &mut raw) },
297 "turn info",
298 )?;
299 let mut info = TurnInfo::default();
300 info.sample_rate = raw.sample_rate;
301 info.max_audio_ms = raw.max_audio_ms;
302 info.frame_samples = raw.frame_samples;
303 info.has_speech = raw.has_speech;
304 info.threshold = raw.threshold;
305 Ok(info)
306 }
307
308 pub fn roles(&self) -> Roles {
310 Roles::from_bits(unsafe { sys::transcribe_model_roles(self.inner.ptr) })
311 }
312
313 pub fn capabilities(&self) -> Result<Capabilities> {
316 let mut caps: sys::transcribe_capabilities = unsafe { std::mem::zeroed() };
317 unsafe { sys::transcribe_capabilities_init(&mut caps) };
318 check(
319 unsafe { sys::transcribe_model_get_capabilities(self.inner.ptr, &mut caps) },
320 "capabilities",
321 )?;
322
323 let mut languages = Vec::new();
324 if !caps.languages.is_null() && caps.n_languages > 0 {
325 let slice =
326 unsafe { std::slice::from_raw_parts(caps.languages, caps.n_languages as usize) };
327 for &lang in slice {
328 languages.push(owned_str(lang));
329 }
330 }
331 let mut translate_target_languages = Vec::new();
332 if !caps.translate_target_languages.is_null() && caps.n_translate_target_languages > 0 {
333 let slice = unsafe {
334 std::slice::from_raw_parts(
335 caps.translate_target_languages,
336 caps.n_translate_target_languages as usize,
337 )
338 };
339 for &lang in slice {
340 translate_target_languages.push(owned_str(lang));
341 }
342 }
343
344 Ok(Capabilities {
345 native_sample_rate: caps.native_sample_rate,
346 languages,
347 translate_target_languages,
348 max_timestamp_kind: TimestampKind::from_raw(caps.max_timestamp_kind),
349 supports_language_detect: caps.supports_language_detect,
350 supports_translate: caps.supports_translate,
351 supports_streaming: caps.supports_streaming,
352 supports_spec_decode: caps.supports_spec_decode,
353 max_audio_ms: caps.max_audio_ms,
354 })
355 }
356
357 pub fn supports(&self, feature: Feature) -> bool {
359 unsafe { sys::transcribe_model_supports(self.inner.ptr, feature.to_raw()) }
360 }
361
362 pub fn accepts_ext(&self, slot: ExtSlot, kind: u32) -> bool {
364 unsafe { sys::transcribe_model_accepts_ext_kind(self.inner.ptr, slot.to_raw(), kind) }
365 }
366
367 pub fn arch(&self) -> String {
369 owned_str(unsafe { sys::transcribe_model_arch_string(self.inner.ptr) })
370 }
371
372 pub fn variant(&self) -> String {
374 owned_str(unsafe { sys::transcribe_model_variant_string(self.inner.ptr) })
375 }
376
377 pub fn backend(&self) -> String {
380 owned_str(unsafe { sys::transcribe_model_backend(self.inner.ptr) })
381 }
382
383 pub fn device(&self) -> Result<Device> {
388 let handle = unsafe { sys::transcribe_model_device(self.inner.ptr) };
389 if handle.is_null() {
390 return Err(crate::Error::Backend(
391 "model has no resolved device".to_string(),
392 ));
393 }
394 let mut raw: sys::transcribe_device_info = unsafe { std::mem::zeroed() };
395 unsafe { sys::transcribe_device_info_init(&mut raw) };
396 let status = unsafe { sys::transcribe_device_get_info(handle, &mut raw) };
397 check(status, "device_get_info")?;
398 Ok(Device::from_raw(&raw, handle, None))
399 }
400
401 pub fn tokenize(&self, text: &str) -> Result<Vec<i32>> {
405 let c_text = CString::new(text)?;
406 let mut buf = vec![0i32; text.len().max(16)];
408 loop {
409 let n = unsafe {
410 sys::transcribe_tokenize(
411 self.inner.ptr,
412 c_text.as_ptr(),
413 buf.as_mut_ptr(),
414 buf.len(),
415 )
416 };
417 if n == i32::MIN {
418 return Err(crate::error::Error::NotImplemented(
419 "model tokenizer has no encode path".to_string(),
420 ));
421 }
422 if n < 0 {
423 buf.resize((-n) as usize, 0);
424 continue;
425 }
426 buf.truncate(n as usize);
427 return Ok(buf);
428 }
429 }
430}
431
432fn check_model_load(status: sys::transcribe_status, context: &str) -> Result<()> {
433 #[cfg(feature = "dynamic-backends")]
434 {
435 if status == sys::transcribe_status::TRANSCRIBE_ERR_BACKEND
436 && crate::backend::device_count() == 0
437 {
438 let code = status.0 as i32;
439 let base = crate::error::status_string(code);
440 return Err(crate::error::Error::Backend(format!(
441 "{context}: {base} (status {code}); dynamic-backends builds \
442 require backend modules to be loaded before model load. Call \
443 transcribe_cpp::init_backends_default() when modules are \
444 bundled next to libtranscribe, or init_backends(dir) for a \
445 custom provider directory."
446 )));
447 }
448 }
449 check(status, context)
450}
451
452#[cfg(unix)]
458pub(crate) fn path_bytes(path: &Path) -> Result<Vec<u8>> {
459 use std::os::unix::ffi::OsStrExt;
460 Ok(path.as_os_str().as_bytes().to_vec())
461}
462
463#[cfg(not(unix))]
464pub(crate) fn path_bytes(path: &Path) -> Result<Vec<u8>> {
465 path.to_str().map(|s| s.as_bytes().to_vec()).ok_or_else(|| {
467 crate::error::Error::InvalidArgument(format!("non-UTF-8 path: {}", path.display()))
468 })
469}