mod display;
mod events;
mod host;
mod load;
#[cfg(feature = "system-audio")]
mod ptt;
mod run;
use super::{common::output_file, resolve_model, CachedGgufRole, CliDevice};
use anyhow::{ensure, Context, Result};
use clap::{Args as ClapArgs, ValueEnum};
use oi_kit_inference::api::realtime::RealtimeArtifactSource;
use crate::audio::pcm;
use oi_kit_inference_architectures::voicechat::quantization::SpeechQuantizationPolicy;
use std::{
fs::File,
io::{BufWriter, Read, Write},
path::{Path, PathBuf},
sync::{atomic::AtomicUsize, Arc},
time::Instant,
};
#[derive(Debug, Clone, Copy, ValueEnum)]
enum QuantizedComponent {
Backbone,
FunctionHead,
Tts,
}
#[cfg(feature = "system-audio")]
#[derive(Debug, Clone, Copy, ValueEnum)]
enum PushToTalk {
Toggle,
Hold,
}
#[cfg(feature = "system-audio")]
#[derive(Debug, Default, Clone, Copy, ValueEnum)]
enum NoiseSuppression {
#[default]
Off,
Low,
Moderate,
High,
VeryHigh,
}
#[cfg(feature = "system-audio")]
impl NoiseSuppression {
fn processing(self) -> oi_kit_inference_media::audio::processing::NoiseSuppression {
use oi_kit_inference_media::audio::processing::NoiseSuppression as Level;
match self {
Self::Off => Level::Off,
Self::Low => Level::Low,
Self::Moderate => Level::Moderate,
Self::High => Level::High,
Self::VeryHigh => Level::VeryHigh,
}
}
}
fn admission_level(value: &str) -> std::result::Result<f32, String> {
let level: f32 = value
.parse()
.map_err(|_| "expected a dBFS level".to_owned())?;
if level.is_finite() && (-100.0..=0.0).contains(&level) {
Ok(level)
} else {
Err("speech threshold must be finite and in -100..=0 dBFS".into())
}
}
#[derive(Debug, ClapArgs)]
#[command(group(clap::ArgGroup::new("bounded_residency")
.args(["layerwise_host", "dense_disk_stream"])
.requires_all(["backbone_device_bytes", "backbone_host_bytes", "speech_device_bytes", "speech_host_bytes"])))]
pub struct Args {
#[command(flatten)]
common: crate::common::CommonOptions,
#[arg(long)]
config: Option<PathBuf>,
#[arg(long)]
official_assets: Option<String>,
#[arg(long)]
base_assets: Option<String>,
#[cfg(feature = "system-audio")]
#[arg(long)]
list_audio_devices: bool,
#[arg(long)]
#[cfg_attr(
feature = "system-audio",
arg(help = "Mono 16 kHz WAV input. Omit to use the microphone.")
)]
#[cfg_attr(not(feature = "system-audio"), arg(required = true))]
input: Option<PathBuf>,
#[arg(long)]
record_input: Option<PathBuf>,
#[arg(long)]
no_transcription: bool,
#[arg(long)]
output: Option<PathBuf>,
#[arg(long)]
events: Option<PathBuf>,
#[arg(long)]
script: Option<PathBuf>,
#[cfg(feature = "system-audio")]
#[arg(long, conflicts_with = "input")]
input_device: Option<String>,
#[cfg(feature = "system-audio")]
#[arg(long, conflicts_with = "no_playback")]
output_device: Option<String>,
#[arg(long)]
#[cfg_attr(not(feature = "system-audio"), arg(required = true))]
no_playback: bool,
#[cfg(feature = "system-audio")]
#[arg(long, conflicts_with_all = ["input", "no_playback"])]
no_echo_cancellation: bool,
#[cfg(feature = "system-audio")]
#[arg(long, value_enum, num_args = 0..=1, default_missing_value = "toggle", conflicts_with = "input")]
push_to_talk: Option<PushToTalk>,
#[cfg(feature = "system-audio")]
#[arg(long, default_value = "space", requires = "push_to_talk")]
ptt_key: String,
#[cfg(feature = "system-audio")]
#[arg(long, value_enum, num_args = 0..=1, default_missing_value = "moderate", default_value = "off", conflicts_with = "input")]
noise_suppression: NoiseSuppression,
#[arg(long)]
speech_admission: bool,
#[arg(long, default_value = "-40", allow_hyphen_values = true, value_parser = admission_level, requires = "speech_admission")]
speech_threshold_dbfs: f32,
#[arg(long, default_value_t = 6, value_parser = clap::value_parser!(u32).range(0..=40), requires = "speech_admission")]
speech_hysteresis_db: u32,
#[arg(long, default_value_t = 80, value_parser = clap::value_parser!(u32).range(10..=1000), requires = "speech_admission")]
speech_min_ms: u32,
#[arg(long, default_value_t = 160, value_parser = clap::value_parser!(u32).range(0..=1000), requires = "speech_admission")]
speech_preroll_ms: u32,
#[arg(long, default_value_t = 300, value_parser = clap::value_parser!(u32).range(0..=2000), requires = "speech_admission")]
speech_hangover_ms: u32,
#[arg(long, requires_all = ["input", "no_playback"])]
offline: bool,
#[arg(long)]
seconds: Option<f64>,
#[cfg(feature = "system-audio")]
#[arg(long, default_value_t = 2000, value_parser = clap::value_parser!(u32).range(160..=10000))]
audio_buffer_ms: u32,
#[arg(
long,
value_enum,
value_delimiter = ',',
default_value = "backbone,function-head,tts",
requires = "quantize"
)]
quantize_components: Vec<QuantizedComponent>,
#[arg(long, value_enum)]
speech_weights: Option<load::SpeechFloatChoice>,
#[arg(long, value_enum)]
speech_compute: Option<load::SpeechFloatChoice>,
#[arg(long)]
system_prompt: Option<String>,
#[arg(long)]
backbone_device_bytes: Option<u64>,
#[arg(long)]
backbone_host_bytes: Option<u64>,
#[arg(long)]
speech_device_bytes: Option<u64>,
#[arg(long)]
speech_host_bytes: Option<u64>,
#[arg(long)]
max_frames: Option<u64>,
#[arg(long)]
max_model_steps: Option<u64>,
#[arg(long)]
interruption_speech_frames: Option<u64>,
#[arg(long, default_value_t = 640)]
chunk_samples: usize,
#[arg(long, default_value_t = 200)]
tail_frames: u64,
#[arg(long, default_value_t = 100000)]
max_steps: u64,
}
fn json<T: serde::de::DeserializeOwned>(path: &Path, limit: u64) -> Result<T> {
let mut bytes = Vec::new();
File::open(path)?.take(limit + 1).read_to_end(&mut bytes)?;
ensure!(
bytes.len() as u64 <= limit,
"{} exceeds {limit} bytes",
path.display()
);
serde_json::from_slice(&bytes).with_context(|| format!("parsing {}", path.display()))
}
fn source(path: PathBuf) -> RealtimeArtifactSource {
if path
.extension()
.is_some_and(|e| e.eq_ignore_ascii_case("gguf"))
{
RealtimeArtifactSource::Gguf { path }
} else {
RealtimeArtifactSource::SafeTensors { path }
}
}
fn configuration(args: &Args) -> Result<load::Config> {
let mut config = if let Some(path) = &args.config {
let mut config: load::Config = json(path, 1_048_576)?;
config.resolve_paths(path.parent().unwrap_or_else(|| Path::new(".")));
config
} else {
let model = args
.common
.model
.as_deref()
.context("provide --model or --config")?;
let path = resolve_model(
model,
args.common.revision.as_deref(),
CachedGgufRole::Target,
)?
.path;
let official = args.official_assets.as_deref().unwrap_or(model);
let base = args.base_assets.as_deref().context("provide --base-assets (base tokenizer/configuration directory or cached repository ID)")?;
serde_json::from_value(serde_json::json!({
"official_assets":resolve_model(official, None, CachedGgufRole::Target)?.path,
"base_assets":resolve_model(base, None, CachedGgufRole::Target)?.path,
"source":source(path), "system_prompt":"You are a helpful assistant.", "tools":[],
"device_parameter_bytes":68719476736_u64, "host_parameter_bytes":68719476736_u64,
"max_branch_bytes":8589934592_u64, "max_total_copy_bytes":1099511627776_u64
}))?
};
if let Some(model) = &args.common.model {
config.source = source(
resolve_model(
model,
args.common.revision.as_deref(),
CachedGgufRole::Target,
)?
.path,
);
}
if let Some(official) = &args.official_assets {
config.official_assets = resolve_model(official, None, CachedGgufRole::Target)?.path;
}
if let Some(base) = &args.base_assets {
config.base_assets = resolve_model(base, None, CachedGgufRole::Target)?.path;
}
if args.common.prepared_cache.is_explicit() || config.prepared_checkpoint_cache.is_none() {
config.prepared_checkpoint_cache = Some(args.common.prepared_cache.policy());
}
if let Some(seed) = args.common.seed {
config.seed = seed;
}
macro_rules! set { ($($field:ident),*) => { $(if let Some(value) = &args.$field { config.$field = value.clone(); })* }; }
set!(
speech_weights,
speech_compute,
system_prompt,
max_frames,
max_model_steps
);
if let Some(value) = args.interruption_speech_frames {
config.interruption_speech_frames = Some(value);
}
if let Some(value) = args.common.device_budget_bytes {
config.device_parameter_bytes = value;
}
if let Some(value) = args.common.host_budget_bytes {
config.host_parameter_bytes = value;
}
if args.common.layerwise_host || args.common.dense_disk_stream {
config.parameter_residency = if args.common.layerwise_host {
load::ParameterResidency::Host {
backbone_device_bytes: args
.backbone_device_bytes
.context("bounded speech residency requires --backbone-device-bytes")?,
backbone_host_bytes: args
.backbone_host_bytes
.context("bounded speech residency requires --backbone-host-bytes")?,
speech_device_bytes: args
.speech_device_bytes
.context("bounded speech residency requires --speech-device-bytes")?,
speech_host_bytes: args
.speech_host_bytes
.context("bounded speech residency requires --speech-host-bytes")?,
depth: args.common.device_layer_window,
}
} else {
load::ParameterResidency::Disk {
backbone_device_bytes: args
.backbone_device_bytes
.context("bounded speech residency requires --backbone-device-bytes")?,
backbone_host_bytes: args
.backbone_host_bytes
.context("bounded speech residency requires --backbone-host-bytes")?,
speech_device_bytes: args
.speech_device_bytes
.context("bounded speech residency requires --speech-device-bytes")?,
speech_host_bytes: args
.speech_host_bytes
.context("bounded speech residency requires --speech-host-bytes")?,
}
};
}
config.validate()?;
Ok(config)
}
fn quantization(args: &Args) -> Result<SpeechQuantizationPolicy> {
let selected = args.common.weight_quantization()?;
let mut policy = SpeechQuantizationPolicy::default();
for component in &args.quantize_components {
match component {
QuantizedComponent::Backbone => policy.backbone = selected,
QuantizedComponent::FunctionHead => policy.function_head = selected,
QuantizedComponent::Tts => policy.tts = selected,
}
}
Ok(policy)
}
pub fn run<F>(
create_factory: impl FnOnce(Option<CliDevice>) -> Result<F>,
args: Args,
timing: bool,
total_started: Instant,
) -> Result<()>
where
F: oi_kit_inference::api::BackendInspection
+ oi_kit_inference_core::BackendHardware
+ oi_kit_inference::api::realtime::RealtimeBackendFactory,
{
#[cfg(feature = "system-audio")]
if args.list_audio_devices {
for device in oi_kit_inference_media::audio::system::devices()? {
println!(
"{}\tinput={}\toutput={}",
device.name, device.input, device.output
);
}
return Ok(());
}
#[cfg(feature = "system-audio")]
if let Some(mode) = args.push_to_talk {
ptt::validate(mode, &args.ptt_key)?;
}
args.common.validate()?;
ensure!(
args.chunk_samples > 0 && args.chunk_samples <= 1_048_576 && args.max_steps > 0,
"invalid chunk or step limit"
);
ensure!(
args.seconds.is_none_or(|v| v.is_finite() && v > 0.0),
"--seconds must be finite and positive"
);
let reserved_frames = args
.tail_frames
.checked_add(2)
.context("response tail frame count overflow")?;
let policy = quantization(&args)?;
let config = configuration(&args)?;
ensure!(
config.max_frames > reserved_frames,
"--max-frames must exceed the response tail plus two frames"
);
let scripts = args
.script
.as_ref()
.map(|p| json::<Vec<run::ScriptedToolResponse>>(p, 4_194_304))
.transpose()?
.unwrap_or_default();
run::validate_scripts(&scripts)?;
let input = args
.input
.as_ref()
.map(|p| pcm::open_wav(p, 16_000))
.transpose()?;
if let Some(input) = &input {
ensure!(
input
.sample_count()
.div_ceil(1280)
.checked_add(args.tail_frames)
.is_some_and(|frames| frames <= config.max_frames),
"input plus response tail exceeds --max-frames"
);
}
let paths = args.output_destinations()?;
for path in &paths {
ensure!(
!path.try_exists()?,
"output already exists: {}",
path.display()
);
}
ensure!(
paths.iter().collect::<std::collections::HashSet<_>>().len() == paths.len(),
"speech, input recording and events must have different paths"
);
let requested_device = args.common.device.or_else(|| match config.device {
load::Device::Cpu if args.config.is_some() => Some(CliDevice::Cpu),
load::Device::Cpu => None,
load::Device::Gpu => Some(CliDevice::Gpu(0)),
});
let factory = create_factory(requested_device)?;
let device = crate::resolve_device(&crate::discover_devices(&factory)?, requested_device)?;
let sampling =
oi_kit_inference_architectures::voicechat::agent_sampling::AgentSamplingPolicy::new(
args.common.temperature.unwrap_or(0.0),
args.common.top_p.unwrap_or(1.0),
args.common.repeat_penalty.unwrap_or(1.0),
usize::try_from(config.max_model_steps)?,
)?;
args.common.apply_allocator_cache_limit(&factory)?;
let started = Instant::now();
let mut session = load::load(
&factory,
&config,
policy,
&device,
args.common.cached_shards,
sampling,
)?;
let load_elapsed = started.elapsed();
eprintln!(
"loaded in {:.3} s on {}",
load_elapsed.as_secs_f64(),
device.device()
);
let stop = Arc::new(AtomicUsize::new(0));
#[cfg(feature = "system-audio")]
{
let signal = stop.clone();
ctrlc::set_handler(move || {
signal.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
})?;
}
let waveform = args
.output
.as_ref()
.map(|p| pcm::create_wav(p, 22_050))
.transpose()?;
let input_recording = args
.record_input
.as_ref()
.map(|p| pcm::create_wav(p, 16_000))
.transpose()?;
let mut io = host::HostIo::new(
input,
waveform,
input_recording,
&args,
stop,
(config.max_frames - reserved_frames) as f64 * 0.08,
)?;
let event_file: Box<dyn Write> = args
.events
.as_ref()
.map(|p| output_file(p).map(|f| Box::new(BufWriter::new(f)) as Box<dyn Write>))
.transpose()?
.unwrap_or_else(|| Box::new(std::io::sink()));
#[cfg(feature = "system-audio")]
let push_to_talk = args.push_to_talk.is_some();
#[cfg(not(feature = "system-audio"))]
let push_to_talk = false;
let mut events = events::Events::new(
event_file,
config.max_frames,
!args.no_transcription,
push_to_talk,
)?;
let options = run::RunOptions {
chunk_samples: args.chunk_samples,
tail_frames: args.tail_frames,
max_steps: args.max_steps,
};
eprintln!(
"{}; Ctrl-C closes input and drains the response, a second Ctrl-C cancels{}",
if args.input.is_none() {
"microphone ready"
} else {
"WAV input ready"
},
if push_to_talk { "\r" } else { "" }
);
let conversation_started = timing.then(Instant::now);
let result = run::run_io(session.as_mut(), &mut io, &mut events, options, scripts);
let event_finish = events.flush();
let finalize = io.finish(result.is_ok());
let conversation_elapsed = conversation_started.map(|start| start.elapsed());
let total_elapsed = total_started.elapsed();
events.summary();
result?;
finalize?;
event_finish?;
if let Some(elapsed) = conversation_elapsed {
eprintln!("load_time: {:.3} s", load_elapsed.as_secs_f64());
eprintln!("conversation_time: {:.3} s", elapsed.as_secs_f64());
eprintln!("total_execution_time: {:.3} s", total_elapsed.as_secs_f64());
}
Ok(())
}
impl Args {
fn output_destinations(&self) -> Result<Vec<PathBuf>> {
[&self.output, &self.events, &self.record_input]
.into_iter()
.flatten()
.map(|path| destination(path))
.collect()
}
}
fn destination(path: &Path) -> Result<PathBuf> {
let parent = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
Ok(parent
.canonicalize()?
.join(path.file_name().context("output requires a file name")?))
}