### Box::from_raw Usage Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Examples demonstrating how to reconstruct a Box from a raw pointer. ```rust let x = Box::new(5); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` ```rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ``` -------------------------------- ### Demonstrating ambiguous From implementation Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html An example of a discouraged From implementation that causes ambiguity with Pin::from. ```rust struct Foo; // A type defined in this crate. impl From> for Pin { fn from(_: Box<()>) -> Pin { Pin::new(Foo) } } ``` -------------------------------- ### Box::into_raw Usage Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Examples demonstrating how to consume a Box and manage the resulting raw pointer. ```rust let x = Box::new(String::from("Hello")); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` ```rust use std::alloc::{dealloc, Layout}; use std::ptr; let x = Box::new(String::from("Hello")); let ptr = Box::into_raw(x); unsafe { ptr::drop_in_place(ptr); dealloc(ptr as *mut u8, Layout::new::()); } ``` ```rust let x = Box::new(String::from("Hello")); let ptr = Box::into_raw(x); unsafe { drop(Box::from_raw(ptr)); } ``` -------------------------------- ### QwenCtx::set_prompt Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/struct.QwenCtx.html Sets a text prompt to guide the transcription process. ```APIDOC ## pub fn set_prompt(&mut self, prompt: &str) -> Result<(), ()> ### Description Configures an optional text prompt to guide the transcription. Passing an empty string clears the current prompt. ### Parameters - **prompt** (str) - Required - The text prompt string. ``` -------------------------------- ### Define TOKEN_AUDIO_START constant Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/config/constant.TOKEN_AUDIO_START.html Represents the audio start token as a 32-bit integer. ```rust pub const TOKEN_AUDIO_START: i32 = 151669; ``` -------------------------------- ### Define TOKEN_IM_START constant Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/config/constant.TOKEN_IM_START.html Represents the start token identifier used in the Qwen ASR configuration. ```rust pub const TOKEN_IM_START: i32 = 151644; ``` -------------------------------- ### Constructing Box from NonNull pointers Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Examples demonstrating how to recreate a Box from a NonNull pointer or manually allocate memory for a Box using the system allocator. ```rust #![feature(allocator_api)] use std::alloc::System; let x = Box::new_in(5, System); let (non_null, alloc) = Box::into_non_null_with_allocator(x); let x = unsafe { Box::from_non_null_in(non_null, alloc) }; ``` ```rust #![feature(allocator_api)] use std::alloc::{Allocator, Layout, System}; unsafe { let non_null = System.allocate(Layout::new::())?.cast::(); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null_in(non_null, System); } ``` -------------------------------- ### Convert Box to Raw Pointer with Allocator Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Demonstrates consuming a Box into a raw pointer and allocator, with examples for both automatic and manual memory cleanup. ```rust #![feature(allocator_api)] use std::alloc::System; let x = Box::new_in(String::from("Hello"), System); let (ptr, alloc) = Box::into_raw_with_allocator(x); let x = unsafe { Box::from_raw_in(ptr, alloc) }; ``` ```rust #![feature(allocator_api)] use std::alloc::{Allocator, Layout, System}; use std::ptr::{self, NonNull}; let x = Box::new_in(String::from("Hello"), System); let (ptr, alloc) = Box::into_raw_with_allocator(x); unsafe { ptr::drop_in_place(ptr); let non_null = NonNull::new_unchecked(ptr); alloc.deallocate(non_null.cast(), Layout::new::()); } ``` -------------------------------- ### Box::from_non_null Usage Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Examples demonstrating how to reconstruct a Box from a NonNull pointer using nightly features. ```rust #![feature(box_vec_non_null)] let x = Box::new(5); let non_null = Box::into_non_null(x); let x = unsafe { Box::from_non_null(non_null) }; ``` ```rust #![feature(box_vec_non_null)] use std::alloc::{alloc, Layout}; use std::ptr::NonNull; unsafe { let non_null = NonNull::new(alloc(Layout::new::()).cast::()) .expect("allocation failed"); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null(non_null); } ``` -------------------------------- ### Get first element Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Returns the first element of the slice, or None if it is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` -------------------------------- ### Convert Box to NonNull Pointer with Allocator Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Demonstrates consuming a Box into a NonNull pointer and allocator, with examples for both automatic and manual memory cleanup. ```rust #![feature(allocator_api)] use std::alloc::System; let x = Box::new_in(String::from("Hello"), System); let (non_null, alloc) = Box::into_non_null_with_allocator(x); let x = unsafe { Box::from_non_null_in(non_null, alloc) }; ``` ```rust #![feature(allocator_api)] use std::alloc::{Allocator, Layout, System}; let x = Box::new_in(String::from("Hello"), System); let (non_null, alloc) = Box::into_non_null_with_allocator(x); unsafe { non_null.drop_in_place(); alloc.deallocate(non_null.cast::(), Layout::new::()); } ``` -------------------------------- ### format_srt_from_index Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/subtitle/fn.format_srt_from_index.html Formats a collection of subtitle cues into SRT format starting from a given index. ```APIDOC ## format_srt_from_index ### Signature `pub fn format_srt_from_index(cues: &[Cue], start_index: u32) -> String` ### Description Converts a slice of `Cue` objects into a formatted SRT string. The subtitle numbering in the output begins at the provided `start_index`. ### Parameters - **cues** (&[Cue]) - A slice of subtitle cue objects to be formatted. - **start_index** (u32) - The starting integer index for the SRT subtitle blocks. ### Returns - **String** - The formatted SRT subtitle content. ``` -------------------------------- ### Get first chunk Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Returns an array reference to the first N items in the slice. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[10, 40]), u.first_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.first_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.first_chunk::<0>()); ``` -------------------------------- ### Load Qwen3-ASR Model Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/struct.QwenCtx.html Initializes a new session by loading model files from the specified directory. ```rust use qwen_asr::context::QwenCtx; let ctx = QwenCtx::load("qwen3-asr-0.6b").expect("failed to load"); ``` -------------------------------- ### Build for performance Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/index.html Use native CPU instructions for optimal performance on x86_64 architectures. ```bash RUSTFLAGS="-C target-cpu=native" cargo build --release ``` -------------------------------- ### Get last element Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Returns the last element of the slice, or None if it is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` -------------------------------- ### pub fn set_profile(enabled: bool) Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/kernels/fn.set_profile.html Sets the profiling state for the Qwen ASR kernel. ```APIDOC ## set_profile ### Description Enables or disables profiling for the Qwen ASR kernel. ### Signature `pub fn set_profile(enabled: bool)` ### Parameters - **enabled** (bool) - Required - If true, profiling is enabled; if false, it is disabled. ``` -------------------------------- ### Check if slice starts with a prefix Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Determine if a slice begins with the provided subslice. ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` ```rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` -------------------------------- ### Basic Box Pinning Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Demonstrates the creation of a pinned box. ```rust let foo = Box::new(()); let bar = Pin::from(foo); ``` -------------------------------- ### QwenCtx::load Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/struct.QwenCtx.html Loads a Qwen3-ASR model from the specified directory into a new session. ```APIDOC ## pub fn load(model_dir: &str) -> Option ### Description Loads a Qwen3-ASR model from the provided directory path. The directory must contain the necessary model files (model*.safetensors and vocab.json). ### Parameters - **model_dir** (str) - Required - The file system path to the model directory. ### Returns - **Option** - Returns the initialized QwenCtx session, or None if loading fails. ``` -------------------------------- ### Get element or subslice Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Returns a reference to an element or subslice depending on the type of index. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### Get last chunk Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Returns an array reference to the last N items in the slice. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[40, 30]), u.last_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.last_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.last_chunk::<0>()); ``` -------------------------------- ### Iterate over slice elements Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Create an iterator that yields all items in the slice from start to end. ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### QwenTokenizer::load Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/tokenizer/struct.QwenTokenizer.html Loads a tokenizer from a specified vocabulary JSON file path. ```APIDOC ## pub fn load(vocab_json_path: &str) -> Option ### Description Loads the tokenizer configuration from a JSON file. ### Parameters - **vocab_json_path** (&str) - Required - The file path to the vocabulary JSON file. ### Returns - **Option** - Returns an instance of QwenTokenizer if successful, otherwise None. ``` -------------------------------- ### qwen_asr::context::QwenCtx::load Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/index.html Loads a Qwen model into the engine state for inference. ```APIDOC ## Function: qwen_asr::context::QwenCtx::load ### Description Loads a specified Qwen model variant into the engine state. This is the entry point for initializing the inference context. ### Signature `pub fn load(model_name: &str) -> Result` ### Parameters - **model_name** (&str) - Required - The name of the model variant to load (e.g., "qwen3-asr-0.6b" or "qwen3-aligner-0.6b"). ``` -------------------------------- ### Split slice from the end Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Iterate over subslices separated by elements matching a predicate, starting from the end. ```rust let slice = [11, 22, 33, 0, 44, 55]; let mut iter = slice.rsplit(|num| *num == 0); assert_eq!(iter.next().unwrap(), &[44, 55]); assert_eq!(iter.next().unwrap(), &[11, 22, 33]); assert_eq!(iter.next(), None); ``` ```rust let v = &[0, 1, 1, 2, 3, 5, 8]; let mut it = v.rsplit(|n| *n % 2 == 0); assert_eq!(it.next().unwrap(), &[]); assert_eq!(it.next().unwrap(), &[3, 5]); assert_eq!(it.next().unwrap(), &[1, 1]); assert_eq!(it.next().unwrap(), &[]); assert_eq!(it.next(), None); ``` -------------------------------- ### pub fn transcribe_stdin(ctx: &mut QwenCtx) -> Option Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/transcribe/fn.transcribe_stdin.html Transcribes audio data provided via standard input using the specified Qwen context. ```APIDOC ## transcribe_stdin ### Description Transcribes audio data from standard input (stdin) using the provided Qwen context. ### Signature `pub fn transcribe_stdin(ctx: &mut QwenCtx) -> Option` ### Parameters - **ctx** (&mut QwenCtx) - Required - A mutable reference to the Qwen context used for the transcription process. ### Returns - **Option** - Returns the transcribed text as a String if successful, or None if the transcription fails. ``` -------------------------------- ### ProfileGuard::new Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/kernels/struct.ProfileGuard.html Creates a new instance of ProfileGuard, initializing it with a reference to a pair of AtomicU64 counters. ```APIDOC ## pub fn new(counter: &'static (AtomicU64, AtomicU64)) -> Option ### Description Creates a new `ProfileGuard` instance. This method takes a static reference to a tuple of two `AtomicU64` counters and returns an `Option`. ### Parameters - **counter** (&'static (AtomicU64, AtomicU64)) - Required - A static reference to a pair of atomic counters used for profiling. ``` -------------------------------- ### Leaking Box memory Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Examples of consuming a Box to produce a static mutable reference for long-lived data. ```rust let x = Box::new(41); let static_ref: &'static mut usize = Box::leak(x); *static_ref += 1; assert_eq!(*static_ref, 42); ``` ```rust let x = vec![1, 2, 3].into_boxed_slice(); let static_ref = Box::leak(x); static_ref[0] = 4; assert_eq!(*static_ref, [4, 2, 3]); ``` -------------------------------- ### Split slice from the end into at most n items Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Split a slice into a maximum of n items starting from the end. ```rust let v = [10, 40, 30, 20, 60, 50]; for group in v.rsplitn(2, |num| *num % 3 == 0) { println!("{group:?}"); } ``` -------------------------------- ### RopeCache::new Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/decoder/struct.RopeCache.html Creates a new instance of RopeCache. ```APIDOC ## pub fn new() -> Self ### Description Initializes a new empty RopeCache instance. ``` -------------------------------- ### pub fn load_wav(path: &str) -> Option> Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/audio/fn.load_wav.html Reads a WAV file from disk and returns f32 samples at 16 kHz mono. This function is equivalent to performing a file read followed by a WAV buffer parse. ```APIDOC ## Function: load_wav ### Description Reads a WAV file from the provided file path and returns the audio data as a vector of f32 samples. The output is normalized to 16 kHz mono format. ### Signature `pub fn load_wav(path: &str) -> Option>` ### Parameters - **path** (&str) - The file system path to the WAV file to be loaded. ### Returns - **Option>** - Returns `Some(Vec)` containing the audio samples if the file is successfully read and parsed, otherwise returns `None`. ``` -------------------------------- ### Iterate over chunks from the end with rchunks Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Returns an iterator over non-overlapping chunks of a specified size, starting from the end of the slice. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` -------------------------------- ### Create a Box from a value Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Demonstrates creating a boxed value and verifying it using assert_eq!. ```rust let x = 5; let boxed = Box::new(5); assert_eq!(Box::from(x), boxed); ``` -------------------------------- ### Iterate over overlapping windows with array_windows Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Returns an iterator over overlapping windows of N elements, starting from the beginning of the slice. ```rust let slice = [0, 1, 2, 3]; let mut iter = slice.array_windows(); assert_eq!(iter.next().unwrap(), &[0, 1]); assert_eq!(iter.next().unwrap(), &[1, 2]); assert_eq!(iter.next().unwrap(), &[2, 3]); assert!(iter.next().is_none()); ``` -------------------------------- ### Try to clone from reference Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Allocates memory on the heap and clones the source into it, returning an error if allocation fails. Requires clone_from_ref and allocator_api features. ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] let hello: Box = Box::try_clone_from_ref("hello")?; ``` -------------------------------- ### TranscriptSegment Struct Definition Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/transcribe/struct.TranscriptSegment.html The structure definition for TranscriptSegment, containing start and end timestamps in milliseconds and the transcribed text. ```rust pub struct TranscriptSegment { pub start_ms: u64, pub end_ms: u64, pub text: String, } ``` -------------------------------- ### Decoder Load Method Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/decoder/struct.Decoder.html Initializes a new Decoder instance from model files and configuration. ```rust pub fn load( ms: &MultiSafetensors, cfg: &QwenConfig, model_dir: &str, ) -> Option ``` -------------------------------- ### StreamState::reset Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/transcribe/struct.StreamState.html Resets the internal state of the transcription session, typically used when starting a new audio window. ```APIDOC ## pub fn reset(&mut self) ### Description Resets the state for a new streaming window, clearing previous caches and history. ``` -------------------------------- ### Split slice into arrays with as_rchunks Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Splits a slice into N-element arrays starting from the end, returning a remainder and a slice of arrays. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let (remainder, chunks) = slice.as_rchunks(); assert_eq!(remainder, &['l']); assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]); ``` -------------------------------- ### pub fn format_srt(cues: &[Cue]) -> String Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/subtitle/fn.format_srt.html Converts a collection of subtitle cues into the standard SRT subtitle format. ```APIDOC ## format_srt ### Description Converts a slice of `Cue` objects into a single `String` formatted according to the SRT subtitle specification. ### Signature `pub fn format_srt(cues: &[Cue]) -> String` ### Parameters - **cues** (&[Cue]) - Required - A slice of subtitle cues to be formatted. ### Returns - **String** - The formatted SRT subtitle content. ``` -------------------------------- ### Clone from reference Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Allocates memory on the heap and clones the source into it. Requires the clone_from_ref feature. ```rust #![feature(clone_from_ref)] let hello: Box = Box::clone_from_ref("hello"); ``` -------------------------------- ### format_vtt(cues: &[Cue]) -> String Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/subtitle/fn.format_vtt.html Converts a collection of subtitle cues into the WebVTT format. ```APIDOC ## format_vtt ### Description Converts a slice of `Cue` objects into a `String` formatted according to the WebVTT specification. ### Signature `pub fn format_vtt(cues: &[Cue]) -> String` ### Parameters - **cues** (&[Cue]) - Required - A slice of subtitle cue objects to be formatted. ``` -------------------------------- ### Calculate element offset Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Determines the index of an element reference using pointer arithmetic. Returns None if the reference does not align with the start of an element. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### pub fn transcribe_audio(ctx: &mut QwenCtx, samples: &[f32]) -> Option Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/transcribe/fn.transcribe_audio.html Transcribes audio samples (f32, 16 kHz, mono, range [-1, 1]). If the audio duration exceeds the configured segment_sec, it is automatically split at low-energy boundaries. ```APIDOC ## Function: transcribe_audio ### Description Transcribes audio samples (f32, 16 kHz, mono, range [-1, 1]). When `ctx.segment_sec > 0` and the audio exceeds that duration, it is automatically split at low-energy boundaries. ### Signature `pub fn transcribe_audio(ctx: &mut QwenCtx, samples: &[f32]) -> Option` ### Parameters - **ctx** (&mut QwenCtx) - The mutable Qwen context used for transcription. - **samples** (&[f32]) - A slice of f32 audio samples (16 kHz, mono, range [-1, 1]). ### Returns - **Option** - Returns the transcribed text as a `Some(String)`, or `None` if the tokenizer or encoder fails to initialize. ``` -------------------------------- ### MultiSafetensors::open Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/safetensors/struct.MultiSafetensors.html Initializes a new MultiSafetensors instance from a directory containing model shards. ```APIDOC ## pub fn open(model_dir: &str) -> Option ### Description Opens the safetensors files located in the specified model directory. ### Parameters - **model_dir** (&str) - Required - The path to the directory containing the model shards. ### Returns - **Option** - Returns an instance of MultiSafetensors if successful, otherwise None. ``` -------------------------------- ### Check pointer range containment Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Use as_ptr_range to get a half-open range of pointers spanning the slice. This is useful for checking if a pointer belongs to the slice. ```rust let a = [1, 2, 3]; let x = &a[1] as *const _; let y = &5 as *const _; assert!(a.as_ptr_range().contains(&x)); assert!(!a.as_ptr_range().contains(&y)); ``` -------------------------------- ### Iterate over exact chunks from the end with rchunks_exact Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/enum.WeightBuf.html Returns an iterator over chunks of exactly the specified size, starting from the end, with a remainder method for leftover elements. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks_exact(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['l']); ``` -------------------------------- ### load_wav Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/audio/index.html Reads a WAV file from the specified path and returns f32 samples at 16 kHz mono. ```APIDOC ## load_wav ### Description Read a WAV file from disk and return f32 samples at 16 kHz mono. ``` -------------------------------- ### Convert Box to NonNull and back Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Demonstrates converting a Box to a NonNull pointer and restoring it using Box::from_non_null for automatic cleanup. ```rust #![feature(box_vec_non_null)] let x = Box::new(String::from("Hello")); let non_null = Box::into_non_null(x); let x = unsafe { Box::from_non_null(non_null) }; ``` -------------------------------- ### SafetensorsFile::open Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/safetensors/struct.SafetensorsFile.html Opens a safetensors file from the specified path. ```APIDOC ## pub fn open(path: &str) -> Option ### Description Opens a safetensors file located at the provided path. ### Parameters - **path** (&str) - Required - The file system path to the safetensors file. ``` -------------------------------- ### pub fn verbose() -> i32 Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/kernels/fn.verbose.html Returns the verbose status or configuration value as an integer. ```APIDOC ## Function: verbose ### Description Returns an integer representing the verbose state or configuration. ### Signature `pub fn verbose() -> i32` ### Returns - **i32** - The verbose value. ``` -------------------------------- ### Write to Box Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Demonstrates writing a value into a Box. ```rust // reuse the box for a second value let c = Box::write(uninit, 6); assert_eq!(*c, 6); ``` -------------------------------- ### Try clone from reference in allocator Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Attempts to allocate memory and clone the source, returning an error if allocation fails. ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] use std::alloc::System; let hello: Box = Box::try_clone_from_ref_in("hello", System)?; ``` -------------------------------- ### Try to create a new uninitialized Box Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Constructs a new box with uninitialized contents on the heap, returning an error if allocation fails. Requires the allocator_api feature. ```rust #![feature(allocator_api)] let mut five = Box::::try_new_uninit()?; // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` -------------------------------- ### Try to create a new Box Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Allocates memory on the heap and places the value into it, returning an error if allocation fails. Requires the allocator_api feature. ```rust #![feature(allocator_api)] let five = Box::try_new(5)?; ``` -------------------------------- ### Create a new uninitialized Box Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Constructs a new box with uninitialized contents, requiring manual initialization. ```rust let mut five = Box::::new_uninit(); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` -------------------------------- ### Create a new Box Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Allocates memory on the heap and places the value into it. ```rust let five = Box::new(5); ``` -------------------------------- ### pub fn transcribe_full Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/transcribe/fn.transcribe_full.html Performs a full transcription of audio samples using the specified Qwen context and optional aligner. ```APIDOC ## Function: transcribe_full ### Signature `pub fn transcribe_full(ctx: &mut QwenCtx, aligner: Option<&mut QwenCtx>, samples: &[f32], on_segment: Option>) -> Option` ### Description Performs a full transcription process. It takes a mutable reference to a `QwenCtx`, an optional mutable reference to an aligner context, a slice of audio samples, and an optional callback function for segments. ### Parameters - **ctx** (&mut QwenCtx) - Required - The primary Qwen context for transcription. - **aligner** (Option<&mut QwenCtx>) - Optional - An optional context used for alignment. - **samples** (&[f32]) - Required - A slice of floating-point audio samples to be transcribed. - **on_segment** (Option>) - Optional - A callback function invoked when a segment is processed. ### Returns - **Option** - Returns the transcription result if successful, otherwise None. ``` -------------------------------- ### Try to create a new zeroed Box Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Constructs a new Box with uninitialized contents filled with zero bytes on the heap, returning an error if allocation fails. Requires the allocator_api feature. ```rust #![feature(allocator_api)] let zero = Box::::try_new_zeroed()?; let zero = unsafe { zero.assume_init() }; assert_eq!(*zero, 0); ``` -------------------------------- ### Define WINDOW_SIZE constant Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/config/constant.WINDOW_SIZE.html Represents the window size configuration value as a usize constant. ```rust pub const WINDOW_SIZE: usize = 400; ``` -------------------------------- ### Encoder::load Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/encoder/struct.Encoder.html Loads the Encoder model from a MultiSafetensors source and a QwenConfig. ```APIDOC ## pub fn load(ms: &MultiSafetensors, cfg: &QwenConfig) -> Option ### Description Loads the encoder model weights and configuration from the provided MultiSafetensors instance. ### Parameters - **ms** (&MultiSafetensors) - Required - The source containing model weights. - **cfg** (&QwenConfig) - Required - The configuration object for the Qwen model. ### Returns - **Option** - Returns the initialized Encoder instance if successful, otherwise None. ``` -------------------------------- ### QwenConfig Struct Definition Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/config/struct.QwenConfig.html The primary configuration structure containing model architecture parameters. ```rust pub struct QwenConfig {Show 21 fields pub enc_d_model: usize, pub enc_layers: usize, pub enc_heads: usize, pub enc_head_dim: usize, pub enc_ffn_dim: usize, pub enc_output_dim: usize, pub enc_n_window: usize, pub enc_n_window_infer: usize, pub enc_chunk_size: usize, pub enc_conv_proj_dim: usize, pub dec_hidden: usize, pub dec_layers: usize, pub dec_heads: usize, pub dec_kv_heads: usize, pub dec_head_dim: usize, pub dec_intermediate: usize, pub vocab_size: usize, pub dec_rms_norm_eps: f32, pub dec_rope_theta: f32, pub classify_num: usize, pub timestamp_segment_time: f32, } ``` -------------------------------- ### Decoder::load Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/decoder/struct.Decoder.html Loads the decoder configuration and weights from the provided MultiSafetensors and configuration files. ```APIDOC ## pub fn load(ms: &MultiSafetensors, cfg: &QwenConfig, model_dir: &str) -> Option ### Description Loads the decoder instance using the provided MultiSafetensors container, Qwen configuration, and model directory path. ### Parameters - **ms** (&MultiSafetensors) - Required - The source container for model weights. - **cfg** (&QwenConfig) - Required - The configuration object for the Qwen model. - **model_dir** (&str) - Required - The directory path containing the model files. ### Returns - **Option** - Returns an instance of the Decoder if loading is successful, otherwise None. ``` -------------------------------- ### pub fn profile_reset() Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/kernels/fn.profile_reset.html Resets the profiling state within the qwen_asr library. ```APIDOC ## profile_reset ### Description Resets the profiling data or state within the qwen_asr library. ### Signature `pub fn profile_reset()` ``` -------------------------------- ### pub fn language_to_iso639(name: &str) -> Option<&'static str> Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/config/fn.language_to_iso639.html Converts a given language name into its ISO 639 standard code representation. ```APIDOC ## Function: language_to_iso639 ### Description Maps a language name string to its corresponding ISO 639 code. Returns None if the language name is not recognized. ### Signature `pub fn language_to_iso639(name: &str) -> Option<&'static str>` ### Parameters - **name** (&str) - The name of the language to convert. ### Returns - **Option<&'static str>** - The ISO 639 code if found, otherwise None. ``` -------------------------------- ### pub unsafe fn gelu_inplace(x: &mut [f32], n: usize) Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/kernels/avx/fn.gelu_inplace.html Performs an in-place GELU activation on a slice of f32 values using AVX2 acceleration. ```APIDOC ## Function: gelu_inplace ### Description Applies the GELU (Gaussian Error Linear Unit) activation function using a tanh approximation. This function is optimized with AVX2 instructions and modifies the input slice in-place. ### Signature `pub unsafe fn gelu_inplace(x: &mut [f32], n: usize)` ### Parameters - **x** (&mut [f32]) - The mutable slice of f32 values to be processed. - **n** (usize) - The number of elements to process within the slice. ### Safety This function is marked as `unsafe` because it performs low-level AVX2 operations. Callers must ensure that the slice `x` has a length of at least `n` and that the CPU supports the required AVX2 instruction set. ``` -------------------------------- ### pub fn enabled() -> bool Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/int8_sidecar/fn.enabled.html Checks whether the sidecar is enabled. The sidecar can be disabled by setting the environment variable QWEN_ASR_SIDECAR to 0. ```APIDOC ## Function: enabled ### Description Returns a boolean indicating whether the sidecar is enabled. The status is determined by the environment variable `QWEN_ASR_SIDECAR`. ### Signature `pub fn enabled() -> bool` ### Returns - **bool** - Returns `true` if the sidecar is enabled, `false` otherwise. ``` -------------------------------- ### pub fn linear_nobias_bf16_swiglu Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/kernels/fn.linear_nobias_bf16_swiglu.html Computes ffn_out[j] = silu(gate[j]) * up[j] using fused gate_up matvec and SwiGLU activation. ```APIDOC ## pub fn linear_nobias_bf16_swiglu(ffn_out: &mut [f32], x: &[f32], gate_up_bf16: *const u16, in_dim: usize, intermediate: usize) ### Description Fused gate_up matvec + SwiGLU for single-token decode. Computes: `ffn_out[j] = silu(gate[j]) * up[j]` where gate/up come from interleaved gate_up_fused matvec. Keeps gate_up output in L1 cache for the SwiGLU operation. ### Parameters - **ffn_out** (&mut [f32]) - Output buffer for the result. - **x** (&[f32]) - Input vector. - **gate_up_bf16** (*const u16) - Pointer to the interleaved gate and up weights in bf16 format. - **in_dim** (usize) - Input dimension. - **intermediate** (usize) - Intermediate dimension. ``` -------------------------------- ### pub fn mel_spectrogram(samples: &[f32]) -> Option<(Vec, usize)> Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/audio/fn.mel_spectrogram.html Computes a 128-bin log-mel spectrogram from 16 kHz audio samples. Returns a tuple containing the flattened spectrogram data and the number of frames, or None if the input is too short. ```APIDOC ## Function: mel_spectrogram ### Description Compute a 128-bin log-mel spectrogram from 16 kHz audio samples. ### Signature `pub fn mel_spectrogram(samples: &[f32]) -> Option<(Vec, usize)>` ### Parameters - **samples** (&[f32]) - Required - A slice of 16 kHz audio samples. ### Returns - **Option<(Vec, usize)>** - Returns `(mel_flat, n_frames)` where `mel_flat` has shape `[128, n_frames]` in row-major order. Returns `None` if the audio is too short to produce even one frame. ``` -------------------------------- ### pub unsafe fn exp_inplace(x: &mut [f32]) Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/kernels/avx/fn.exp_inplace.html Performs an in-place exponential calculation on a slice of f32 values using AVX2 acceleration. ```APIDOC ## Function: exp_inplace ### Description Performs an AVX2-accelerated exponential calculation on a mutable slice of f32 values. This function uses a fast polynomial approximation to compute the result in-place. ### Signature `pub unsafe fn exp_inplace(x: &mut [f32])` ### Parameters - **x** (&mut [f32]) - A mutable slice of 32-bit floating-point numbers to be transformed in-place. ### Safety This function is marked `unsafe` as it utilizes AVX2 instructions which require the CPU to support the AVX2 instruction set. ``` -------------------------------- ### pub fn transcribe(ctx: &mut QwenCtx, wav_path: &str) -> Option Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/transcribe/fn.transcribe.html A convenience wrapper that loads a WAV file from the specified path and performs transcription. This is equivalent to calling audio::load_wav followed by transcribe_audio. ```APIDOC ## Function: transcribe ### Signature `pub fn transcribe(ctx: &mut QwenCtx, wav_path: &str) -> Option` ### Description Convenience wrapper to load a WAV file and transcribe it. This function is equivalent to calling `audio::load_wav` followed by `transcribe_audio`. ### Parameters - **ctx** (&mut QwenCtx) - The mutable context for the Qwen ASR system. - **wav_path** (&str) - The file system path to the WAV file to be transcribed. ### Returns - **Option** - Returns the transcribed text as a `Some(String)` if successful, or `None` if the transcription fails. ``` -------------------------------- ### pub fn resample(samples: &[f32], from_rate: i32, to_rate: i32) -> Vec Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/audio/fn.resample.html Resamples audio data using a Kaiser-windowed sinc resampler. ```APIDOC ## Function: resample ### Description Kaiser-windowed sinc resampler for audio samples. ### Signature `pub fn resample(samples: &[f32], from_rate: i32, to_rate: i32) -> Vec` ### Parameters - **samples** (&[f32]) - The input audio samples. - **from_rate** (i32) - The original sample rate. - **to_rate** (i32) - The target sample rate. ### Returns - **Vec** - A vector containing the resampled audio data. ``` -------------------------------- ### StreamState::new Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/transcribe/struct.StreamState.html Creates a new, empty instance of StreamState to begin a streaming transcription session. ```APIDOC ## pub fn new() -> Self ### Description Creates a new empty streaming state for managing transcription buffers and caches. ### Returns - **Self** - A new instance of StreamState. ``` -------------------------------- ### forced_align(ctx: &mut QwenCtx, samples: &[f32], text: &str, language: &str) -> Option> Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/align/fn.forced_align.html Performs forced alignment on audio samples with a known transcript. Requires a ForcedAligner model and returns None if the model is invalid, text is empty, or encoding fails. ```APIDOC ## forced_align ### Description Perform forced alignment on audio samples with a known transcript. The function requires a ForcedAligner model (where `config.classify_num > 0`). ### Signature `pub fn forced_align(ctx: &mut QwenCtx, samples: &[f32], text: &str, language: &str) -> Option>` ### Parameters - **ctx** (&mut QwenCtx) - The Qwen context. - **samples** (&[f32]) - The audio samples to align. - **text** (&str) - The transcript text. - **language** (&str) - The language of the text. CJK languages ("Chinese", "Japanese", "Korean", "Cantonese") are split by character; others are split by whitespace. ### Returns - **Option>** - A vector of alignment results, or `None` if the model is not an aligner, the text is empty, or encoding fails. ``` -------------------------------- ### format_vtt_from_index Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/subtitle/fn.format_vtt_from_index.html Formats a collection of subtitle cues into WebVTT format. ```APIDOC ## Function: format_vtt_from_index ### Description Converts a slice of `Cue` objects into a VTT formatted string. This function allows specifying a starting index for the cues and whether to include the VTT header. ### Signature `pub fn format_vtt_from_index(cues: &[Cue], start_index: u32, include_header: bool) -> String` ### Parameters - **cues** (&[Cue]) - Required - A slice of subtitle cues to be formatted. - **start_index** (u32) - Required - The index to start formatting from. - **include_header** (bool) - Required - Whether to include the VTT header in the output string. ### Returns - **String** - The formatted VTT string. ``` -------------------------------- ### Accessing SUPPORTED_LANGUAGES constant Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/config/constant.SUPPORTED_LANGUAGES.html Displays the signature of the SUPPORTED_LANGUAGES constant available in the qwen_asr::config module. ```rust pub const SUPPORTED_LANGUAGES: &[&str]; ``` -------------------------------- ### pub fn vec_axpy_inplace(dst: &mut [f32], src: &[f32], alpha: f32, n: usize) Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/kernels/fn.vec_axpy_inplace.html Performs the operation: dst = dst + alpha * src for the first n elements. ```APIDOC ## Function: vec_axpy_inplace ### Description Performs an in-place AXPY operation (y = a*x + y) on floating-point vectors. ### Signature `pub fn vec_axpy_inplace(dst: &mut [f32], src: &[f32], alpha: f32, n: usize)` ### Parameters - **dst** (&mut [f32]) - The destination vector to be modified in-place. - **src** (&[f32]) - The source vector to be scaled and added. - **alpha** (f32) - The scalar multiplier for the source vector. - **n** (usize) - The number of elements to process. ``` -------------------------------- ### Box::into_non_null_with_allocator Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Consumes the Box, returning a wrapped NonNull pointer and the allocator. ```APIDOC ## pub fn into_non_null_with_allocator(b: Box) -> (NonNull, A) ### Description Consumes the `Box`, returning a wrapped `NonNull` pointer and the allocator. The pointer will be properly aligned. ### Usage This is an associated function, called as `Box::into_non_null_with_allocator(b)`. ``` -------------------------------- ### Perform speech transcription Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/index.html Load a model context and transcribe an audio file. ```rust use qwen_asr::context::QwenCtx; use qwen_asr::transcribe; let mut ctx = QwenCtx::load("qwen3-asr-0.6b").expect("model not found"); let text = transcribe::transcribe(&mut ctx, "audio.wav").unwrap(); println!("{text}"); ``` -------------------------------- ### Define TOKEN_AUDIO_PAD constant Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/config/constant.TOKEN_AUDIO_PAD.html Represents the audio padding token identifier as a 32-bit integer. ```rust pub const TOKEN_AUDIO_PAD: i32 = 151676; ``` -------------------------------- ### Cleanup via drop and Box::from_non_null Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html An alternative approach to cleanup by wrapping the NonNull pointer back into a Box and dropping it. ```rust #![feature(box_vec_non_null)] let x = Box::new(String::from("Hello")); let non_null = Box::into_non_null(x); unsafe { drop(Box::from_non_null(non_null)); } ``` -------------------------------- ### Box::from_raw_in Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/type.TokenCallback.html Constructs a box from a raw pointer in the given allocator. The resulting Box takes ownership of the pointer and will manage its memory and destruction. ```APIDOC ## pub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Box ### Description Constructs a box from a raw pointer in the given allocator. After calling this function, the raw pointer is owned by the resulting Box. ### Safety This function is unsafe because improper use may lead to memory problems, such as double-free errors. The raw pointer must point to a block of memory allocated by the provided allocator. ``` -------------------------------- ### pub fn optimization_flags() -> Vec<&'static str> Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/fn.optimization_flags.html Returns a list of compile-time optimization flags enabled for this build. ```APIDOC ## optimization_flags ### Description Returns a list of compile-time optimization flags enabled for this build. ### Signature `pub fn optimization_flags() -> Vec<&'static str>` ### Returns - **Vec<&'static str>** - A vector containing the compile-time optimization flags. ``` -------------------------------- ### Define QwenCtx struct Source: https://docs.rs/qwen-asr/0.9.0/qwen_asr/context/struct.QwenCtx.html The primary state container for the ASR engine, containing model configuration, buffers, and performance metrics. ```rust pub struct QwenCtx {Show 27 fields pub model: Arc, pub config: QwenConfig, pub kv_cache: KvCache, pub dec_bufs: DecoderBuffers, pub enc_bufs: EncoderBuffers, pub rope_cache: RopeCache, pub token_cb: Option, pub segment_sec: f32, pub search_sec: f32, pub stream_chunk_sec: f32, pub stream_rollback: i32, pub stream_unfixed_chunks: i32, pub stream_max_new_tokens: i32, pub past_text_conditioning: bool, pub skip_silence: bool, pub prompt: Option, pub force_language: Option, pub detected_language: Option, pub want_language_language_detection: bool, pub prompt_tokens: Option>, pub force_prompt_tokens: Option>, pub prompt_tokens_ready: bool, pub perf_total_ms: f64, pub perf_text_tokens: i32, pub perf_audio_ms: f64, pub perf_encode_ms: f64, pub perf_decode_ms: f64, } ```