loqui-cli 0.4.0

The loqui command: serve, speak, transcribe, manage tokens, check exposure.
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! `loqui`: local speech, served safely.

use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Args, Parser, Subcommand};
use loqui::{Downloads, Engine, KokoroVariant, TtsConfig};
use loqui_server::{Acknowledgements, Listen, Server, ServerConfig, auth, fs};

#[derive(Parser)]
#[command(name = "loqui", version, about = "Local Kokoro text-to-speech and Whisper speech-to-text, served safely.")]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Serve the OpenAI audio API. Listens on a private Unix socket unless
    /// told otherwise.
    Serve(ServeArgs),
    /// Speak text to an audio file, in process.
    Speak(SpeakArgs),
    /// Transcribe an audio file, in process.
    #[cfg(feature = "whisper")]
    Transcribe(TranscribeArgs),
    /// Show, locate or replace the generated API token.
    Token {
        #[command(subcommand)]
        action: TokenAction,
    },
    /// Explain what `serve` would expose with these options, and flag risks.
    Doctor(ServeArgs),
    /// Download model weights and every voice now, for hosts that will run
    /// with --offline.
    Fetch(EngineArgs),
    /// List the voices `speak` and `serve` accept, named voices included.
    Voices(VoicesFile),
    /// Find the blend of the stock voices that sounds most like a recording,
    /// and print it as a voices.toml line.
    Match(MatchArgs),
}

#[derive(Subcommand)]
enum TokenAction {
    /// Print the token (to stdout, for piping into a client's config).
    Show,
    /// Print where the token file is.
    Path,
    /// Replace the token. Clients using the old one stop working.
    Rotate,
}

#[derive(Args, Clone)]
struct VoicesFile {
    /// Named voices: a TOML file of `name = "blend"` lines, such as
    /// `will = "am_puck(1)+am_liam(1)+am_onyx(0.5)"` [default:
    /// $XDG_CONFIG_HOME/loqui/voices.toml, if it exists].
    #[arg(long = "voices", env = "LOQUI_VOICES_FILE")]
    path: Option<PathBuf>,
}

impl VoicesFile {
    /// The file to read, if any.
    fn path(&self) -> Option<PathBuf> {
        voices_path(self.path.as_deref(), fs::config_dir().as_deref())
    }

    /// Its `(name, spec)` pairs; none without a file.
    fn read(&self) -> Result<Vec<(String, String)>, String> {
        self.path().map_or(Ok(Vec::new()), |path| read_voices(&path))
    }
}

/// The voices file: the one named, else `voices.toml` in the config
/// directory when there is one.
fn voices_path(explicit: Option<&Path>, config_dir: Option<&Path>) -> Option<PathBuf> {
    explicit.map(Path::to_path_buf).or_else(|| config_dir.map(|d| d.join("voices.toml")).filter(|p| p.exists()))
}

/// Reads `name = "spec"` pairs. Names and specs are checked when the engine
/// is built; this only reads them.
fn read_voices(path: &Path) -> Result<Vec<(String, String)>, String> {
    let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
    let table: toml::Table = text.parse().map_err(|e| format!("{}: {e}", path.display()))?;
    table
        .into_iter()
        .map(|(name, value)| match value {
            toml::Value::String(spec) => Ok((name, spec)),
            _ => Err(format!("{}: voice {name:?} must be a string such as \"af_bella(2)+af_sky(1)\"", path.display())),
        })
        .collect()
}

#[derive(Args, Clone)]
struct EngineArgs {
    /// Where model weights are cached [default: $XDG_CACHE_HOME/loqui].
    #[arg(long, env = "LOQUI_CACHE_DIR")]
    cache_dir: Option<PathBuf>,
    /// Never download; use only cached weights.
    #[arg(long)]
    offline: bool,
    /// Kokoro precision: fp32 (reference), fp16, or quantized.
    #[arg(long, default_value = "fp32", value_parser = parse_variant)]
    kokoro: KokoroVariant,
    /// Run models on a GPU: cuda or cuda:N. Needs a `cuda` build.
    #[arg(long)]
    gpu: Option<String>,
    /// CPU threads for each model; 0 means the default [default: one per CPU
    /// this process may use, at most 4 for Whisper].
    #[arg(long, env = "LOQUI_THREADS")]
    threads: Option<u16>,
    /// Whisper model for transcription (large-v3-turbo, small.en, ...).
    #[cfg(feature = "whisper")]
    #[arg(long, default_value = "large-v3-turbo")]
    stt_model: String,
    /// Disable transcription.
    #[cfg(feature = "whisper")]
    #[arg(long)]
    no_stt: bool,
    /// Unload Whisper after this many idle seconds (0 keeps it loaded).
    #[cfg(feature = "whisper")]
    #[arg(long, default_value_t = 600)]
    stt_idle_secs: u64,
    /// Load models at startup rather than on first request.
    #[arg(long)]
    preload: bool,
    #[command(flatten)]
    voices: VoicesFile,
}

impl EngineArgs {
    /// Kokoro's settings.
    fn tts(&self, gpu: Option<i32>) -> TtsConfig {
        TtsConfig {
            variant: self.kokoro,
            device: gpu.map_or(loqui_kokoro::Device::Cpu, loqui_kokoro::Device::Cuda),
            threads: self.threads.map(usize::from),
            ..TtsConfig::default()
        }
    }

    /// The speaker model's settings.
    fn speaker(&self) -> loqui::SpeakerConfig {
        loqui::SpeakerConfig { threads: self.threads.map(usize::from), ..loqui::SpeakerConfig::default() }
    }

    /// Whisper's settings.
    #[cfg(feature = "whisper")]
    fn stt(&self, gpu: Option<i32>) -> loqui::SttConfig {
        loqui::SttConfig {
            model: self.stt_model.clone(),
            device: gpu.map_or(loqui::SttDevice::Cpu, loqui::SttDevice::Gpu),
            threads: self.threads,
            idle_ttl: (self.stt_idle_secs > 0).then(|| std::time::Duration::from_secs(self.stt_idle_secs)),
        }
    }
}

#[derive(Args, Clone)]
struct ServeArgs {
    /// unix[:PATH] (default), loopback:PORT, tcp:ADDRESS:PORT or all:PORT.
    #[arg(long, env = "LOQUI_LISTEN", default_value = "unix")]
    listen: String,
    /// Required with --listen all:PORT.
    #[arg(long)]
    i_understand_this_exposes_all_interfaces: bool,
    /// Allow a non-loopback listener without TLS (trusted LAN, VPN, or a TLS
    /// proxy in front).
    #[arg(long)]
    insecure_plaintext_network: bool,
    /// Tokens to accept, one per line [default: LOQUI_TOKEN, else a
    /// generated token].
    #[arg(long, env = "LOQUI_TOKEN_FILE")]
    token_file: Option<PathBuf>,
    /// Require a token on the Unix socket too.
    #[arg(long)]
    require_token: bool,
    /// Also accept these Host names (e.g. a DNS name for a LAN address).
    #[arg(long = "allowed-host")]
    allowed_hosts: Vec<String>,
    /// Serve /health without a token on network listeners.
    #[arg(long)]
    public_health: bool,
    #[arg(long, requires = "tls_key")]
    tls_cert: Option<PathBuf>,
    #[arg(long, requires = "tls_cert")]
    tls_key: Option<PathBuf>,
    /// Longest input text, in characters.
    #[arg(long, default_value_t = 4096)]
    max_input_chars: usize,
    /// Longest uploaded audio, in seconds.
    #[arg(long, default_value_t = 1800)]
    max_audio_secs: u64,
    /// Requests that may wait per model before the server answers 503.
    #[arg(long, default_value_t = 8)]
    max_queue: usize,
    #[command(flatten)]
    engine: EngineArgs,
}

#[derive(Args)]
struct SpeakArgs {
    text: String,
    #[arg(short, long, default_value = "speech.wav")]
    output: PathBuf,
    #[arg(long, default_value = "af_heart")]
    voice: String,
    #[arg(long, default_value_t = 1.0)]
    speed: f32,
    /// wav, flac, opus or pcm; mp3 in builds with the `mp3` feature.
    #[arg(long, default_value = "wav")]
    format: String,
    #[command(flatten)]
    engine: EngineArgs,
}

#[cfg(feature = "whisper")]
#[derive(Args)]
struct TranscribeArgs {
    file: PathBuf,
    #[arg(long)]
    language: Option<String>,
    #[command(flatten)]
    engine: EngineArgs,
}

#[derive(Args)]
struct MatchArgs {
    /// The recording: WAV, FLAC, MP3, AAC, Ogg or WebM, with at least 3 s of
    /// speech. The first 30 s are used.
    file: PathBuf,
    /// The name the voices.toml line gives the blend.
    #[arg(long, default_value = "matched")]
    name: String,
    /// How many of the nearest voices to mix (1 to 6).
    #[arg(long, default_value_t = 4)]
    max_voices: usize,
    /// How many blends to try (1 to 200); each is one short synthesis.
    #[arg(long, default_value_t = 36)]
    evaluations: usize,
    /// The accent the blend speaks with: auto, us or gb.
    #[arg(long, default_value = "auto", value_parser = parse_accent)]
    accent: loqui::Accent,
    /// What the recording says. Speaking the same words sharpens the
    /// comparison and sets a matching speed.
    #[arg(long)]
    transcript: Option<String>,
    /// Do not transcribe the recording for its words when --transcript is
    /// not given.
    #[cfg(feature = "whisper")]
    #[arg(long)]
    no_transcribe: bool,
    #[command(flatten)]
    engine: EngineArgs,
}

fn parse_accent(s: &str) -> Result<loqui::Accent, String> {
    match s {
        "auto" => Ok(loqui::Accent::Auto),
        "us" | "american" => Ok(loqui::Accent::American),
        "gb" | "british" => Ok(loqui::Accent::British),
        other => Err(format!("unknown accent {other:?}; use auto, us or gb")),
    }
}

fn parse_variant(s: &str) -> Result<KokoroVariant, String> {
    match s {
        "fp32" => Ok(KokoroVariant::Fp32),
        "fp16" => Ok(KokoroVariant::Fp16),
        "quantized" | "q8" => Ok(KokoroVariant::Quantized),
        other => Err(format!("unknown Kokoro variant {other:?}; use fp32, fp16 or quantized")),
    }
}

fn gpu_ordinal(gpu: &Option<String>) -> Result<Option<i32>, String> {
    match gpu.as_deref() {
        None => Ok(None),
        Some("cuda") => Ok(Some(0)),
        Some(s) => s.strip_prefix("cuda:").and_then(|n| n.parse().ok()).map(Some).ok_or_else(|| format!("--gpu {s:?}: use cuda or cuda:N")),
    }
}

/// The optional models a command needs, beside Kokoro.
#[derive(Clone, Copy, Default)]
struct Needs {
    stt: bool,
    speaker: bool,
}

fn build_engine(args: &EngineArgs, needs: Needs, max_input_chars: usize, max_audio_secs: u64) -> Result<Engine, String> {
    let gpu = gpu_ordinal(&args.gpu)?;
    let mut builder = Engine::builder()
        .downloads(if args.offline { Downloads::Deny } else { Downloads::Allow })
        .max_input_chars(max_input_chars)
        .max_audio_secs(max_audio_secs)
        .preload(args.preload)
        .tts(Some(args.tts(gpu)));
    if let Some(dir) = &args.cache_dir {
        builder = builder.cache_dir(dir);
    }
    for (name, spec) in args.voices.read()? {
        builder = builder.voice(name, spec);
    }
    if needs.speaker {
        builder = builder.speaker(Some(args.speaker()));
    }
    #[cfg(feature = "whisper")]
    if needs.stt && !args.no_stt {
        builder = builder.stt(Some(args.stt(gpu)));
    }
    #[cfg(not(feature = "whisper"))]
    let _ = needs.stt;
    builder.build().map_err(|e| e.to_string())
}

fn server_config(args: &ServeArgs) -> Result<ServerConfig, String> {
    Ok(ServerConfig {
        listen: args.listen.parse::<Listen>().map_err(|e| e.to_string())?,
        acknowledgements: Acknowledgements {
            all_interfaces: args.i_understand_this_exposes_all_interfaces,
            plaintext_network: args.insecure_plaintext_network,
        },
        token_file: args.token_file.clone(),
        require_token_on_unix: args.require_token,
        allowed_hosts: args.allowed_hosts.clone(),
        public_health: args.public_health,
        tls_cert: args.tls_cert.clone(),
        tls_key: args.tls_key.clone(),
        max_queue: Some(args.max_queue),
        ..ServerConfig::default()
    })
}

async fn shutdown_signal() {
    let ctrl_c = async {
        let _ = tokio::signal::ctrl_c().await;
    };
    #[cfg(unix)]
    let term = async {
        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
            Ok(mut s) => {
                s.recv().await;
            }
            Err(_) => std::future::pending::<()>().await,
        }
    };
    #[cfg(not(unix))]
    let term = std::future::pending::<()>();
    tokio::select! {
        () = ctrl_c => {}
        () = term => {}
    }
    tracing::info!("shutting down");
}

async fn serve(args: ServeArgs) -> Result<(), String> {
    let config = server_config(&args)?;
    let engine = build_engine(&args.engine, Needs { stt: true, ..Needs::default() }, args.max_input_chars, args.max_audio_secs)?;
    let server = Server::bind(config, engine).await.map_err(|e| e.to_string())?;
    tracing::info!(address = %server.address(), token = %server.token_source(), "loqui listening");
    if server.listen().is_network() && args.insecure_plaintext_network && args.tls_cert.is_none() {
        tracing::warn!("serving a network address without TLS; tokens and audio cross the network in plaintext");
    }
    server.run(shutdown_signal()).await.map_err(|e| e.to_string())
}

fn doctor(args: &ServeArgs) -> Result<(), String> {
    let config = server_config(args)?;
    let mut problems = 0;
    let mut say = |ok: bool, line: String| {
        println!("{} {line}", if ok { "ok  " } else { "WARN" });
        if !ok {
            problems += 1;
        }
    };
    let tls = config.tls_cert.is_some();
    match config.listen.check(config.acknowledgements, tls) {
        Ok(()) => say(true, format!("listener {} is allowed", config.listen)),
        Err(e) => say(false, format!("serve would refuse to start: {e}")),
    }
    let reach = match &config.listen {
        Listen::Unix(_) => "processes running as this user, on this host".to_owned(),
        Listen::Loopback(p) => format!("any process of any user on this host, via 127.0.0.1:{p}, with a token"),
        Listen::Interface(a) => format!("anything that can route to {a}, with a token"),
        Listen::AllInterfaces(p) => format!("anything that can reach any address of this host on port {p}, with a token"),
    };
    say(!config.listen.is_network(), format!("reachable by: {reach}"));
    if config.listen.is_unix() {
        match config.listen {
            Listen::Unix(Some(ref p)) => say(true, format!("socket: {}", p.display())),
            _ => match fs::default_socket_path() {
                Some(p) => say(true, format!("socket: {}", p.display())),
                None => say(false, "XDG_RUNTIME_DIR is unset: pass --listen unix:/path".into()),
            },
        }
        say(
            true,
            format!(
                "token on the socket: {}",
                if config.require_token_on_unix { "required" } else { "not required (peer uid is checked)" }
            ),
        );
    }
    if std::env::var_os("LOQUI_TOKEN").is_some() {
        say(false, "LOQUI_TOKEN is set; other processes of this user can read it from /proc. Prefer --token-file".into());
    }
    match (&config.token_file, fs::default_token_path()) {
        (Some(p), _) => match auth::check_private_file(p) {
            Ok(()) => say(true, format!("token file {} is private", p.display())),
            Err(e) => say(false, e.to_string()),
        },
        (None, Some(p)) if p.exists() => match auth::check_private_file(&p) {
            Ok(()) => say(true, format!("generated token {} is private", p.display())),
            Err(e) => say(false, e.to_string()),
        },
        (None, Some(p)) => say(true, format!("a token will be generated at {}", p.display())),
        (None, None) => say(false, "no config directory for a generated token: set HOME or pass --token-file".into()),
    }
    if config.public_health && config.listen.is_network() {
        say(false, "/health is public on a network listener (reveals only that loqui is running)".into());
    }
    let cache = args.engine.cache_dir.clone().or_else(loqui::default_cache_dir);
    say(cache.is_some(), format!("model cache: {}", cache.map_or("none".into(), |c| c.display().to_string())));
    // The engine `serve` would build: a configuration it would refuse, such
    // as a bad voices file, stops it, so say so here.
    match build_engine(&EngineArgs { preload: false, ..args.engine.clone() }, Needs { stt: true, ..Needs::default() }, 4096, 0) {
        Ok(engine) => {
            if let Some(path) = args.engine.voices.path() {
                let named = engine.voices().map_or(0, |v| v.iter().filter(|v| v.blend.is_some()).count());
                say(true, format!("{named} named voice(s) from {}", path.display()));
            }
            let missing = engine.missing();
            let megabytes = missing.iter().map(|f| f.bytes).sum::<u64>().div_ceil(1_000_000);
            match (missing.len(), args.engine.offline) {
                (0, _) => say(true, "every model file is cached".into()),
                (n, true) => {
                    say(false, format!("{n} model file(s) ({megabytes} MB) are not cached and --offline is set: run `loqui fetch`"))
                }
                (n, false) => say(true, format!("{n} model file(s) ({megabytes} MB) download on first use, or now with `loqui fetch`")),
            }
        }
        Err(e) => say(false, format!("serve would refuse to start: {e}")),
    }
    if problems == 0 { Ok(()) } else { Err(format!("{problems} warning(s)")) }
}

fn token(action: TokenAction) -> Result<(), String> {
    let path = fs::default_token_path().ok_or("no config directory: set HOME")?;
    match action {
        TokenAction::Path => println!("{}", path.display()),
        TokenAction::Show => {
            if !path.exists() {
                auth::generate_file(&path).map_err(|e| e.to_string())?;
            }
            auth::check_private_file(&path).map_err(|e| e.to_string())?;
            let text = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
            let first = text.lines().map(str::trim).find(|l| !l.is_empty() && !l.starts_with('#')).ok_or("the token file is empty")?;
            println!("{first}");
        }
        TokenAction::Rotate => {
            auth::rotate(&path).map_err(|e| e.to_string())?;
            eprintln!("rotated {}; restart `loqui serve` and update clients", path.display());
        }
    }
    Ok(())
}

fn speak(args: SpeakArgs) -> Result<(), String> {
    let engine = build_engine(&args.engine, Needs::default(), 4096, 0)?;
    let format = loqui::Format::parse(&args.format).map_err(|e| e.to_string())?;
    let request = loqui::SpeakRequest { text: args.text, voice: args.voice, speed: args.speed, format };
    let speech = engine.speak(&request).map_err(|e| e.to_string())?;
    std::fs::write(&args.output, &speech.audio).map_err(|e| format!("{}: {e}", args.output.display()))?;
    eprintln!("{:.1}s of speech written to {}", speech.duration_secs, args.output.display());
    Ok(())
}

#[cfg(feature = "whisper")]
fn transcribe(args: TranscribeArgs) -> Result<(), String> {
    let engine = build_engine(&args.engine, Needs { stt: true, ..Needs::default() }, 4096, 7200)?;
    let audio = std::fs::read(&args.file).map_err(|e| format!("{}: {e}", args.file.display()))?;
    let request = loqui::TranscribeRequest { audio, language: args.language, ..Default::default() };
    let result = engine.transcribe(&request).map_err(|e| e.to_string())?;
    println!("{}", result.text);
    Ok(())
}

fn voices(file: VoicesFile) -> Result<(), String> {
    let mut builder = Engine::builder();
    for (name, spec) in file.read()? {
        builder = builder.voice(name, spec);
    }
    // Lazy: nothing is loaded or fetched to list voices.
    let voices = builder.build().and_then(|engine| engine.voices()).map_err(|e| e.to_string())?;
    let width = voices.iter().map(|v| v.id.len()).max().unwrap_or(0);
    for v in voices {
        let line = format!("{:width$}  {}  {:7}  {}", v.id, v.language, v.gender, v.blend.unwrap_or_default());
        println!("{}", line.trim_end());
    }
    Ok(())
}

fn fetch(args: EngineArgs) -> Result<(), String> {
    // Fetching verifies every digest but loads nothing, so preparing a cache
    // never holds a model in memory.
    let engine = build_engine(&EngineArgs { preload: false, ..args }, Needs { stt: true, speaker: true }, 4096, 0)?;
    engine.fetch().map_err(|e| e.to_string())?;
    for m in engine.models() {
        eprintln!("{} ready", m.id);
    }
    engine.fetch_voices().map_err(|e| e.to_string())?;
    eprintln!("{} voices ready", loqui_kokoro::ENGLISH_VOICES.len());
    Ok(())
}

/// A name voices.toml accepts: lowercase letters, digits and `_`, and not
/// shaped like a Kokoro voice (`af_custom`).
fn check_voice_name(name: &str) -> Result<(), String> {
    let charset = !name.is_empty() && name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
    let kokoro_shaped = matches!(name.as_bytes(), [_, b'f' | b'm', b'_', ..]);
    if !charset || kokoro_shaped {
        return Err(format!("--name {name:?}: use lowercase letters, digits and _, not a Kokoro-shaped name like af_custom"));
    }
    Ok(())
}

fn match_voice(args: MatchArgs) -> Result<(), String> {
    check_voice_name(&args.name)?;
    let audio = std::fs::read(&args.file).map_err(|e| format!("{}: {e}", args.file.display()))?;
    #[cfg(feature = "whisper")]
    let transcribe = args.transcript.is_none() && !args.no_transcribe;
    #[cfg(not(feature = "whisper"))]
    let transcribe = false;
    let engine = build_engine(&args.engine, Needs { stt: transcribe, speaker: true }, 4096, 1800)?;
    // Only a build with Whisper fills it in.
    #[cfg_attr(not(feature = "whisper"), allow(unused_mut))]
    let mut transcript = args.transcript;
    #[cfg(feature = "whisper")]
    if transcribe && engine.stt_model_id().is_some() {
        eprintln!("transcribing {} for its words...", args.file.display());
        match engine.transcribe(&loqui::TranscribeRequest { audio: audio.clone(), ..Default::default() }) {
            Ok(t) => transcript = Some(t.text),
            Err(e) => eprintln!("could not transcribe ({e}); matching on reference sentences instead"),
        }
    }
    let mut request = loqui::MatchRequest::new(audio);
    request.transcript = transcript;
    request.max_voices = args.max_voices;
    request.evaluations = args.evaluations;
    request.accent = args.accent;
    let mut progress = |p: &loqui::MatchProgress| {
        match p {
            loqui::MatchProgress::Preparing { done, total } => eprint!("\rpreparing the stock voices: {done}/{total}  "),
            loqui::MatchProgress::Evaluated { evaluations, budget, best_similarity } => {
                eprint!("\rtrying blends: {evaluations}/{budget}, best similarity {best_similarity:.3}  ")
            }
            _ => {}
        }
        ControlFlow::Continue(())
    };
    let found = engine.match_voice(&request, &mut progress).map_err(|e| e.to_string())?;
    eprintln!();
    let speed = found.speed.filter(|s| (s - 1.0).abs() >= 0.025).map_or(String::new(), |s| format!("; speak it at --speed {s:.2}"));
    println!(
        "# similarity {:.2}, closest single voice {} at {:.2}; the closest blend available, not a copy{speed}",
        found.similarity, found.closest_voice, found.closest_similarity
    );
    println!("{} = \"{}\"", args.name, found.spec);
    Ok(())
}

fn main() -> ExitCode {
    tracing_subscriber::fmt()
        // whisper.cpp narrates every model load at info; keep it to warnings
        // unless RUST_LOG asks for more.
        .with_env_filter(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info,whisper_rs=warn".into()))
        .with_writer(std::io::stderr)
        .init();
    let cli = Cli::parse();
    let result = match cli.command {
        Command::Serve(args) => match tokio::runtime::Runtime::new() {
            Ok(rt) => rt.block_on(serve(args)),
            Err(e) => Err(e.to_string()),
        },
        Command::Speak(args) => speak(args),
        #[cfg(feature = "whisper")]
        Command::Transcribe(args) => transcribe(args),
        Command::Token { action } => token(action),
        Command::Doctor(args) => doctor(&args),
        Command::Fetch(args) => fetch(args),
        Command::Voices(file) => voices(file),
        Command::Match(args) => match_voice(args),
    };
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("loqui: {e}");
            ExitCode::FAILURE
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// clap checks its own rules (unique flags, valid defaults) only in
    /// debug builds and only when a command is parsed; this checks them all
    /// at once, so a clash fails here rather than in someone's terminal.
    #[test]
    fn the_command_line_is_well_formed() {
        use clap::CommandFactory;
        Cli::command().debug_assert();
    }

    /// Every command that runs a model, with the arguments it requires.
    fn engine_commands() -> Vec<Vec<&'static str>> {
        let mut commands = vec![vec!["serve"], vec!["doctor"], vec!["speak", "hi"], vec!["match", "a.wav"], vec!["fetch"]];
        #[cfg(feature = "whisper")]
        commands.push(vec!["transcribe", "a.wav"]);
        commands
    }

    fn engine_args(command: Command) -> EngineArgs {
        match command {
            Command::Serve(args) | Command::Doctor(args) => args.engine,
            Command::Speak(args) => args.engine,
            #[cfg(feature = "whisper")]
            Command::Transcribe(args) => args.engine,
            Command::Match(args) => args.engine,
            Command::Fetch(args) => args,
            Command::Token { .. } | Command::Voices(_) => panic!("this command runs no model"),
        }
    }

    #[test]
    fn every_command_that_runs_a_model_takes_threads() {
        for command in engine_commands() {
            let argv = ["loqui"].into_iter().chain(command.iter().copied()).chain(["--threads", "3"]);
            let args = engine_args(Cli::try_parse_from(argv).unwrap_or_else(|e| panic!("{command:?}: {e}")).command);
            assert_eq!(args.tts(None).threads, Some(3), "{command:?}");
            assert_eq!(args.speaker().threads, Some(3), "{command:?}");
            #[cfg(feature = "whisper")]
            assert_eq!(args.stt(None).threads, Some(3), "{command:?}");
        }
    }

    /// Setting the variable would race the other tests (and `set_var` is
    /// unsafe), so this checks that clap reads it, and that nothing replaces
    /// an unset count with one of its own.
    #[test]
    fn threads_come_from_loqui_threads_and_default_to_unset() {
        use clap::CommandFactory;
        let cli = Cli::command();
        for command in engine_commands() {
            let name = command[0];
            let threads = cli.find_subcommand(name).and_then(|c| c.get_arguments().find(|a| a.get_id() == "threads"));
            let threads = threads.unwrap_or_else(|| panic!("{name} has no --threads"));
            assert_eq!(threads.get_env(), Some(std::ffi::OsStr::new("LOQUI_THREADS")), "{name}");
            assert!(threads.get_default_values().is_empty(), "{name}");
        }
    }

    #[test]
    fn a_match_name_is_one_voices_toml_accepts() {
        assert!(check_voice_name("me").is_ok());
        assert!(check_voice_name("warm_2").is_ok());
        for bad in ["", "Me", "my voice", "af_me", "bm_x"] {
            assert!(check_voice_name(bad).is_err(), "{bad:?}");
        }
    }

    /// A scratch directory, removed on drop.
    struct TempDir(PathBuf);

    impl TempDir {
        fn new(name: &str) -> Self {
            let dir = std::env::temp_dir().join(format!("loqui-cli-{name}-{}", std::process::id()));
            let _ = std::fs::remove_dir_all(&dir);
            std::fs::create_dir_all(&dir).unwrap();
            Self(dir)
        }

        fn file(&self, name: &str, text: &str) -> PathBuf {
            let path = self.0.join(name);
            std::fs::write(&path, text).unwrap();
            path
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    #[test]
    fn voices_files_are_name_spec_pairs() {
        let dir = TempDir::new("voices-ok");
        let path = dir.file("voices.toml", "# my voices\nwill = \"am_puck(1)+am_liam(1)+am_onyx(0.5)\"\nnova = \"nova(3)+af_sky\"\n");
        let mut voices = read_voices(&path).unwrap();
        voices.sort();
        assert_eq!(voices, [("nova".into(), "nova(3)+af_sky".into()), ("will".into(), "am_puck(1)+am_liam(1)+am_onyx(0.5)".into())]);
    }

    #[test]
    fn voices_files_say_what_is_wrong_and_where() {
        let dir = TempDir::new("voices-bad");
        let table = read_voices(&dir.file("table.toml", "[will]\nblend = \"am_puck\"\n")).unwrap_err();
        assert!(table.contains("table.toml") && table.contains("\"will\" must be a string"), "{table}");
        let syntax = read_voices(&dir.file("syntax.toml", "will = am_puck\n")).unwrap_err();
        assert!(syntax.contains("syntax.toml") && syntax.contains("line 1"), "{syntax}");
        let missing = read_voices(&dir.0.join("absent.toml")).unwrap_err();
        assert!(missing.contains("absent.toml"), "{missing}");
    }

    #[test]
    fn the_default_voices_file_is_used_only_if_it_exists() {
        let dir = TempDir::new("voices-default");
        let explicit = dir.0.join("mine.toml");
        assert_eq!(voices_path(Some(&explicit), Some(&dir.0)), Some(explicit.clone()), "named files are used even if absent");
        assert_eq!(voices_path(None, Some(&dir.0)), None);
        assert_eq!(voices_path(None, None), None);
        let default = dir.file("voices.toml", "");
        assert_eq!(voices_path(None, Some(&dir.0)), Some(default));
    }
}