oi-kit-inference-cli 0.1.0

Command-line interface for running local models with oi-kit-inference
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! CLI entry point for turn-based audio tasks and full-duplex conversation.

pub(crate) mod pcm;

use std::{
    io::{self, Write},
    path::PathBuf,
    time::Instant,
};

use anyhow::{bail, ensure, Context, Result};
use clap::{Args as ClapArgs, Subcommand};
use oi_kit_inference::api::{
    audio::{AudioTask, AudioTaskOutput, MediaGraphMechanisms, PreparedAudioTask},
    realtime::{
        prepare_realtime_model, RealtimeArtifactRequest, RealtimeArtifactSource,
        RealtimeAssetDirectories, RealtimeBackendFactory,
    },
};

use crate::{resolve_model, CachedGgufRole, CliBackend, CliDevice};

#[derive(Debug, ClapArgs)]
pub struct Args {
    /// Select the backend used for audio execution.
    #[arg(long, global = true, value_enum)]
    backend: Option<CliBackend>,
    /// Report audio timing statistics to stderr.
    #[arg(long, global = true)]
    timing: bool,
    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Stream an utterance into a transcript.
    Transcribe(PcmTurnArgs),
    /// Translate an utterance into text.
    Translate(TranslateArgs),
    /// Synthesize speech from text.
    Speak(SpeakArgs),
    /// Generate a spoken response to one utterance.
    Respond(RespondArgs),
    /// Run a full-duplex conversation using system audio or a WAV.
    Realtime(Box<crate::realtime::Args>),
}

#[derive(Debug, ClapArgs)]
struct PcmTurnArgs {
    #[command(flatten)]
    model: ModelArgs,
    #[command(flatten)]
    input: InputArgs,
}

#[derive(Debug, ClapArgs)]
struct TranslateArgs {
    #[command(flatten)]
    audio: PcmTurnArgs,
    /// Source language for translation.
    #[arg(long, value_parser = nonblank)]
    source_language: String,
    /// Target language for translation.
    #[arg(long, value_parser = nonblank)]
    language: String,
}

#[derive(Debug, ClapArgs)]
struct SpeakArgs {
    #[command(flatten)]
    model: ModelArgs,
    /// Text to synthesize.
    #[arg(long, value_parser = nonblank)]
    text: String,
    #[command(flatten)]
    output: OutputArgs,
}

#[derive(Debug, ClapArgs)]
struct RespondArgs {
    #[command(flatten)]
    audio: PcmTurnArgs,
    /// Optional instruction accompanying the spoken request.
    #[arg(long)]
    text: Option<String>,
    #[command(flatten)]
    output: OutputArgs,
}

#[derive(Debug, ClapArgs)]
struct ModelArgs {
    #[command(flatten)]
    prepared_cache: crate::common::PreparedCacheArgs,
    /// Local model path or cached Hugging Face model identifier.
    #[arg(long)]
    model: String,
    /// Cached model revision.
    #[arg(long)]
    revision: Option<String>,
    /// Local projector GGUF for a split checkpoint.
    #[arg(long, requires = "assets")]
    projector: Option<PathBuf>,
    /// Local model asset directory, required for split GGUF.
    #[arg(long)]
    assets: Option<PathBuf>,
    /// Execution device: cpu, gpu:N, metal:N, or cuda:N.
    #[arg(long)]
    device: Option<CliDevice>,
    /// Maximum committed text tokens and speech frames in the response.
    #[arg(long, default_value_t = 256, value_parser = clap::value_parser!(u32).range(1..))]
    max_slots: u32,
    /// Response sampling seed.
    #[arg(long, default_value_t = 0)]
    seed: u64,
}

#[derive(Debug, ClapArgs)]
#[cfg_attr(feature = "system-audio", group(skip))]
#[cfg_attr(feature = "system-audio", command(group(
    clap::ArgGroup::new("audio_input").args(["input", "microphone_seconds"]).required(true)
)))]
struct InputArgs {
    /// Input mono WAV at the model's required sample rate.
    #[arg(long)]
    #[cfg_attr(not(feature = "system-audio"), arg(required = true))]
    input: Option<PathBuf>,
    /// Capture this many seconds from a microphone.
    #[cfg(feature = "system-audio")]
    #[arg(long, value_parser = positive_seconds)]
    microphone_seconds: Option<f64>,
    /// Microphone device name.
    #[cfg(feature = "system-audio")]
    #[arg(long, requires = "microphone_seconds")]
    input_device: Option<String>,
}

#[derive(Debug, ClapArgs)]
#[cfg_attr(feature = "system-audio", group(skip))]
#[cfg_attr(feature = "system-audio", command(group(
    clap::ArgGroup::new("audio_output").args(["output", "play"]).required(true).multiple(true)
)))]
struct OutputArgs {
    /// Write synthesized PCM to a new WAV file.
    #[arg(long)]
    #[cfg_attr(not(feature = "system-audio"), arg(required = true))]
    output: Option<PathBuf>,
    /// Play synthesized PCM on the system output.
    #[cfg(feature = "system-audio")]
    #[arg(long)]
    play: bool,
    /// Speaker device name.
    #[cfg(feature = "system-audio")]
    #[arg(long, requires = "play")]
    output_device: Option<String>,
}

fn nonblank(value: &str) -> Result<String, &'static str> {
    if value.trim().is_empty() {
        Err("value must not be blank")
    } else {
        Ok(value.to_owned())
    }
}

#[cfg(feature = "system-audio")]
fn positive_seconds(value: &str) -> Result<f64, &'static str> {
    match value.parse::<f64>() {
        Ok(seconds) if seconds.is_finite() && seconds > 0.0 => Ok(seconds),
        _ => Err("duration must be finite and positive"),
    }
}

pub fn run(args: Args, total_started: Instant) -> Result<()> {
    let Args {
        backend,
        timing,
        command,
    } = args;
    match backend.unwrap_or_else(CliBackend::default_available) {
        #[cfg(feature = "mlx")]
        CliBackend::Mlx => run_with_factory(
            |_| Ok(oi_kit_inference::backends::MlxBackendFactory::default()),
            command,
            timing,
            total_started,
        ),
        #[cfg(not(feature = "mlx"))]
        CliBackend::Mlx => bail!("this build does not enable the MLX backend"),
        #[cfg(feature = "candle")]
        CliBackend::Candle => run_with_factory(
            |device| {
                let device = crate::candle_device(device)?;
                Ok(oi_kit_inference::backends::CandleBackendFactory::for_device(&device)?)
            },
            command,
            timing,
            total_started,
        ),
        #[cfg(not(feature = "candle"))]
        CliBackend::Candle => bail!("this build does not enable the Candle backend"),
    }
}

fn run_with_factory<F>(
    create_factory: impl FnOnce(Option<crate::CliDevice>) -> Result<F>,
    command: Command,
    timing: bool,
    total_started: Instant,
) -> Result<()>
where
    F: oi_kit_inference::api::BackendInspection
        + oi_kit_inference_core::BackendHardware
        + RealtimeBackendFactory<Mechanisms: MediaGraphMechanisms>,
{
    match command {
        Command::Transcribe(args) => run_turn(
            &create_factory(args.model.device)?,
            AudioTask::Transcribe,
            args.model,
            Some(args.input),
            None,
            timing,
            total_started,
        ),
        Command::Translate(args) => run_turn(
            &create_factory(args.audio.model.device)?,
            AudioTask::Translate {
                source_language: &args.source_language,
                language: &args.language,
            },
            args.audio.model,
            Some(args.audio.input),
            None,
            timing,
            total_started,
        ),
        Command::Speak(args) => run_turn(
            &create_factory(args.model.device)?,
            AudioTask::Speak { text: &args.text },
            args.model,
            None,
            Some(args.output),
            timing,
            total_started,
        ),
        Command::Respond(args) => run_turn(
            &create_factory(args.audio.model.device)?,
            AudioTask::Respond {
                instruction: args.text.as_deref().unwrap_or(""),
            },
            args.audio.model,
            Some(args.audio.input),
            Some(args.output),
            timing,
            total_started,
        ),
        Command::Realtime(args) => {
            crate::realtime::run(create_factory, *args, timing, total_started)
        }
    }
}

fn run_turn(
    factory: &(impl oi_kit_inference_core::BackendHardware
          + RealtimeBackendFactory<Mechanisms: MediaGraphMechanisms>),
    task: AudioTask<'_>,
    args: ModelArgs,
    input: Option<InputArgs>,
    output: Option<OutputArgs>,
    timing: bool,
    total_started: Instant,
) -> Result<()> {
    let load_started = timing.then(Instant::now);
    let model = resolve_model(
        &args.model,
        args.revision.as_deref(),
        CachedGgufRole::Target,
    )?
    .path;
    let source = match &args.projector {
        Some(projector) => RealtimeArtifactSource::AudioGguf {
            backbone: model,
            projector: projector.clone(),
        },
        None => {
            ensure!(
                !model
                    .extension()
                    .is_some_and(|ext| ext.eq_ignore_ascii_case("gguf")),
                "a split audio GGUF requires --projector and --assets"
            );
            RealtimeArtifactSource::SafeTensors { path: model }
        }
    };
    let artifact = prepare_realtime_model(&RealtimeArtifactRequest {
        source,
        assets: RealtimeAssetDirectories {
            model: args.assets.clone(),
            text_backbone: None,
        },
        prepared_checkpoint_cache: Some(args.prepared_cache.policy()),
    })?;
    let prepared =
        PreparedAudioTask::new(&artifact, task, args.max_slots as usize, args.seed, factory)
            .map_err(anyhow::Error::from_boxed)?;
    let input_rate = prepared.input_sample_rate();
    let output_rate = prepared.output_sample_rate();
    let mut wav_input = input
        .as_ref()
        .and_then(|input| input.input.as_deref())
        .map(|path| pcm::open_wav(path, input_rate.context("model has no PCM input")?))
        .transpose()?;
    if let Some(input) = &wav_input {
        ensure!(input.sample_count() > 0, "audio input is empty");
    }
    let device = crate::resolve_device(&crate::discover_devices(factory)?, args.device)?;
    let mut session = prepared.load(&device).map_err(anyhow::Error::from_boxed)?;
    let load_elapsed = load_started.map(|start| start.elapsed());
    if let Some(elapsed) = load_elapsed {
        eprintln!("model loaded in {:.3} s", elapsed.as_secs_f64());
    }
    let task_started = timing.then(Instant::now);
    let mut first_output = None;
    let mut observe_output = |nonempty: bool| {
        if nonempty && first_output.is_none() {
            first_output = task_started.map(|start| start.elapsed());
        }
    };
    let mut stdout = io::stdout().lock();
    let mut publish_input = |samples: &[f32]| -> Result<()> {
        let text = session.push(samples).map_err(anyhow::Error::from_boxed)?;
        observe_output(!text.is_empty());
        stdout.write_all(text.as_bytes())?;
        stdout.flush()?;
        Ok(())
    };
    if let Some(input) = &mut wav_input {
        let mut buffer = [0.0; 640];
        loop {
            let count = input.read_samples(&mut buffer)?;
            if count == 0 {
                break;
            }
            publish_input(&buffer[..count])?;
        }
    }
    #[cfg(feature = "system-audio")]
    if let Some(input) = &input {
        if let Some(seconds) = input.microphone_seconds {
            capture(
                input.input_device.as_deref(),
                input_rate.context("model has no microphone input")?,
                seconds,
                publish_input,
            )?;
        }
    }
    if input.is_some() {
        session.finish_input().map_err(anyhow::Error::from_boxed)?;
    }

    let mut sink = pcm::PcmOutput {
        wav: output
            .as_ref()
            .and_then(|output| output.output.as_deref())
            .map(|path| pcm::create_wav(path, output_rate.context("model has no PCM output")?))
            .transpose()?,
        #[cfg(feature = "system-audio")]
        speaker: if let Some(output) = output.filter(|output| output.play) {
            Some(
                oi_kit_inference_media::audio::system::SystemAudioOutput::new(
                    output.output_device.as_deref(),
                    output_rate.context("model has no speaker output")?,
                    2000,
                )?,
            )
        } else {
            None
        },
    };
    let mut wrote_response_text = false;
    while let Some(output) = session.next_output().map_err(anyhow::Error::from_boxed)? {
        match output {
            AudioTaskOutput::Text(text) => {
                wrote_response_text |= !text.is_empty();
                observe_output(!text.is_empty());
                stdout.write_all(text.as_bytes())?;
                stdout.flush()?;
            }
            AudioTaskOutput::Pcm(samples) => {
                if output_rate.is_none() {
                    bail!("selected text task emitted PCM");
                }
                observe_output(!samples.is_empty());
                sink.write(&samples)?;
            }
        }
    }
    if let Some(wav) = sink.wav {
        pcm::finish_wav(wav)?;
    }
    #[cfg(feature = "system-audio")]
    if let Some(speaker) = &mut sink.speaker {
        speaker.finish()?;
    }
    if output_rate.is_none() || wrote_response_text {
        writeln!(stdout)?;
    }
    if let (Some(load), Some(task)) = (load_elapsed, task_started) {
        let task_elapsed = task.elapsed();
        let total = total_started.elapsed();
        eprintln!("load_time: {:.3} s", load.as_secs_f64());
        eprintln!("audio_task_time: {:.3} s", task_elapsed.as_secs_f64());
        match first_output {
            Some(elapsed) => eprintln!("time_to_first_output: {:.3} s", elapsed.as_secs_f64()),
            None => eprintln!("time_to_first_output: n/a"),
        }
        eprintln!("total_execution_time: {:.3} s", total.as_secs_f64());
    }
    Ok(())
}

#[cfg(feature = "system-audio")]
fn capture(
    device: Option<&str>,
    rate: u32,
    seconds: f64,
    mut publish: impl FnMut(&[f32]) -> Result<()>,
) -> Result<()> {
    use oi_kit_inference_media::audio::{processing::NoiseSuppression, system::SystemAudioInput};
    use std::time::Duration;

    let samples = (seconds * f64::from(rate)).round();
    ensure!(
        samples >= 1.0 && samples < usize::MAX as f64,
        "microphone sample count is out of range"
    );
    let mut remaining = samples as usize;
    let mut input = SystemAudioInput::new(device, rate, 2000, NoiseSuppression::Off)?;
    input.start()?;
    let mut buffer = [0.0; 640];
    let mut last_sample = Instant::now();
    while remaining != 0 {
        let capacity = buffer.len().min(remaining);
        match input.read(&mut buffer[..capacity])? {
            Some(0) => bail!("microphone closed before capture completed"),
            Some(count) => {
                remaining -= count;
                last_sample = Instant::now();
                publish(&buffer[..count])?;
            }
            None => {
                ensure!(
                    last_sample.elapsed() < Duration::from_secs(5),
                    "microphone stopped delivering audio"
                );
                std::thread::sleep(Duration::from_millis(5));
            }
        }
    }
    input.stop()?;
    Ok(())
}