aria-kit 0.1.0

Audio capture, transcription, synthesis, and voice-analysis contracts for local speech apps
Documentation
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
use std::collections::VecDeque;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};

use super::*;
use crate::audio::Recording;
use crate::audio::testing::recorded;
use crate::transcription::{
    Cadence, ChunkStream, Emitted, Hypothesis, Language, Session, Stream, TimedWord, Transcriber,
    Transcription, TranscriptionAudio,
};

struct Scripted(Mutex<VecDeque<Hypothesis>>);

impl Scripted {
    fn new(answers: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self(Mutex::new(
            answers.into_iter().map(Hypothesis::new).collect(),
        ))
    }
}

impl Transcriber for Scripted {
    fn validate_language(&self, _: &Language, _: &CancelToken) -> Result<(), TranscriptionError> {
        Ok(())
    }

    fn transcribe_with(
        &self,
        _: TranscriptionAudio<'_>,
        _: &Language,
        _: &CancelToken,
    ) -> Result<Hypothesis, TranscriptionError> {
        Ok(self
            .0
            .lock()
            .expect("script lock")
            .pop_front()
            .expect("script covers decodes"))
    }
}

struct Replace(&'static str, &'static str);

impl Layer for Replace {
    fn apply(&self, text: &mut String, _: &CancelToken) -> Result<(), TranscriptionError> {
        *text = text.replace(self.0, self.1);
        Ok(())
    }
}

#[test]
fn layers_apply_in_declaration_order_and_options_preserve_the_raw_path() {
    let (_directory, mut recording) = recorded(&[1, 2]);
    let transcription = Transcription::complete_samples(Scripted::new(["one"]))
        .with(Replace("one", "two"))
        .with(Replace("two", "three"));
    assert_eq!(
        transcription
            .transcribe(&mut recording, &Language::Automatic)
            .unwrap()
            .as_str(),
        "three"
    );

    for enabled in [false, true] {
        let (_directory, mut recording) = recorded(&[1, 2]);
        let transcription = Transcription::complete_samples(Scripted::new(["Um, hello."]))
            .with(enabled.then_some(RemoveHesitations));
        assert_eq!(
            transcription
                .transcribe(&mut recording, &Language::Automatic)
                .unwrap()
                .as_str(),
            if enabled { "Hello." } else { "Um, hello." }
        );
    }
}

#[test]
fn complete_and_streaming_sessions_apply_real_layers() {
    let vocabulary = Vocabulary::new(["Cargo.toml"]).unwrap();
    let (_directory, mut recording) = recorded(&[1, 2]);
    let transcription = Transcription::complete_samples(Scripted::new([
        "Um, open cargo dot toml. They had had enough.",
    ]))
    .with(RemoveHesitations)
    .with(&vocabulary);
    assert_eq!(
        transcription
            .transcribe(&mut recording, &Language::Automatic)
            .unwrap()
            .as_str(),
        "Open Cargo.toml. They had had enough."
    );

    let (_directory, recording) = recorded(&[1; 1600]);
    let transcription = Transcription::agreement(
        Cadence::from_millis(100, 20_000),
        Scripted::new(["Um, open cargo dot toml."]),
    )
    .with(RemoveHesitations)
    .with(vocabulary);
    let mut session = Session::over(&transcription, &Language::Automatic, recording).unwrap();
    let segment = session.next_finalized().unwrap().unwrap();
    assert_eq!(segment.as_str(), "Open Cargo.toml.");
    assert!(session.next_finalized().unwrap().is_none());
    assert_eq!(session.stop().unwrap().as_str(), segment.as_str());
}

struct WavScripted(&'static str);

impl Transcriber for WavScripted {
    fn validate_language(&self, _: &Language, _: &CancelToken) -> Result<(), TranscriptionError> {
        Ok(())
    }

    fn transcribe_with(
        &self,
        audio: TranscriptionAudio<'_>,
        _: &Language,
        _: &CancelToken,
    ) -> Result<Hypothesis, TranscriptionError> {
        let wav = audio.require_wav("scripted")?;
        assert!(wav.path().unwrap().is_file());
        Ok(Hypothesis::new(self.0))
    }
}

#[test]
fn whole_wav_layers_process_text_and_can_remove_all_speech() {
    for (input, expected) in [
        ("Um, open cargo dot toml.", Some("Open Cargo.toml.")),
        ("Um, uh.", None),
    ] {
        let (_directory, recording) = recorded(&[1, 2]);
        let transcription = Transcription::complete_wav(WavScripted(input))
            .with(RemoveHesitations)
            .with(Vocabulary::new(["Cargo.toml"]).unwrap());
        let session = Session::over(&transcription, &Language::Automatic, recording).unwrap();
        let result = session.stop();
        match expected {
            Some(text) => assert_eq!(result.unwrap().as_str(), text),
            None => assert!(matches!(result, Err(TranscriptionError::NoSpeech))),
        }
    }
}

struct NativeScripted;

impl Transcriber for NativeScripted {
    fn validate_language(&self, _: &Language, _: &CancelToken) -> Result<(), TranscriptionError> {
        Ok(())
    }

    fn transcribe_with(
        &self,
        _: TranscriptionAudio<'_>,
        _: &Language,
        _: &CancelToken,
    ) -> Result<Hypothesis, TranscriptionError> {
        panic!("native transcription must use the chunk stream")
    }

    fn open_stream(
        &self,
        _: &Language,
        _: &CancelToken,
    ) -> Result<Option<Box<dyn ChunkStream>>, TranscriptionError> {
        Ok(Some(Box::new(ScriptedStream(VecDeque::from([
            ("um car", false),
            ("go dot toml done", true),
            ("uh", false),
        ])))))
    }
}

struct ScriptedStream(VecDeque<(&'static str, bool)>);

impl ChunkStream for ScriptedStream {
    fn chunk_samples(&self) -> usize {
        1600
    }

    fn feed(&mut self, chunk: &[f32]) -> Result<Emitted, TranscriptionError> {
        assert_eq!(chunk.len(), self.chunk_samples());
        let (text, joins_previous) = self.0.pop_front().expect("script covers chunks and flush");
        Ok(Emitted {
            words: Hypothesis::new(text),
            joins_previous,
        })
    }
}

#[test]
fn native_layers_process_joined_words_and_flush_with_independent_opt_outs() {
    for (hesitations, vocabulary, expected) in [
        (false, false, vec!["um", "cargo dot toml", "done uh"]),
        (true, false, vec!["cargo dot toml", "done"]),
        (false, true, vec!["um", "Cargo.toml", "done uh"]),
        (true, true, vec!["Cargo.toml", "done"]),
    ] {
        for drain_tail in [false, true] {
            let (_directory, mut recording) = recorded(&[1; 3200]);
            let transcription = Transcription::stream(Stream::Native, NativeScripted)
                .with(hesitations.then_some(RemoveHesitations))
                .with(vocabulary.then(|| Vocabulary::new(["Cargo.toml"]).unwrap()));
            let mut operation = transcription.start(&Language::Automatic).unwrap();
            for text in expected
                .iter()
                .take(if drain_tail { expected.len() } else { 1 })
            {
                let segment = operation.next_finalized(&mut recording).unwrap().unwrap();
                assert_eq!(segment.as_str(), *text);
                let span = segment.span.unwrap();
                assert_eq!(
                    recording.span(span.clone()).len() as u64,
                    span.end - span.start
                );
                recording.release_before(operation.retained_from());
            }
            if drain_tail {
                assert!(operation.next_finalized(&mut recording).unwrap().is_none());
                assert_eq!(operation.completed().unwrap().as_str(), expected.join(" "));
            }
            assert_eq!(
                operation.finish(&mut recording).unwrap().as_str(),
                expected.join(" ")
            );
        }
    }
}

#[test]
fn vocabulary_does_not_rewrite_across_finalized_segments() {
    let (mut recording, mut capture) = Recording::open();
    let transcription = Transcription::agreement(
        Cadence::from_millis(100, 20_000),
        Scripted::new(["cargo", "cargo dot toml"]),
    )
    .with(Vocabulary::new(["Cargo.toml"]).unwrap());
    let mut operation = transcription.start(&Language::Automatic).unwrap();
    capture.push(&[0.5; 1600]);
    operation.next_update(&mut recording).unwrap();
    capture.push(&[0.5; 1600]);
    capture.finish();
    recording.fill().unwrap();
    let first = operation.next_finalized(&mut recording).unwrap().unwrap();
    let tail = operation.next_finalized(&mut recording).unwrap().unwrap();
    assert_eq!(first.as_str(), "cargo");
    assert_eq!(tail.as_str(), "dot toml");
    assert_eq!(
        operation.finish(&mut recording).unwrap().as_str(),
        "cargo dot toml"
    );
}

#[test]
fn removing_every_word_finishes_without_redecoding() {
    let (_directory, mut recording) = recorded(&[1, 2]);
    let transcription =
        Transcription::complete_samples(Scripted::new(["Um, uh, hmm."])).with(RemoveHesitations);
    let mut operation = transcription.start(&Language::Automatic).unwrap();
    assert!(operation.next_finalized(&mut recording).unwrap().is_none());
    assert!(operation.completed().is_none());
    assert!(matches!(
        operation.finish(&mut recording),
        Err(TranscriptionError::NoSpeech)
    ));
}

#[test]
fn a_suppressed_streaming_segment_does_not_end_the_stream() {
    let (mut recording, mut capture) = Recording::open();
    let transcription = Transcription::agreement(
        Cadence::from_millis(100, 20_000),
        Scripted::new(["um", "um hello"]),
    )
    .with(RemoveHesitations);
    let mut operation = transcription.start(&Language::Automatic).unwrap();
    capture.push(&[0.5; 1600]);
    assert!(matches!(
        operation.next_update(&mut recording).unwrap(),
        Some(TranscriptUpdate::Provisional(text)) if text == "um"
    ));
    capture.push(&[0.5; 1600]);
    capture.finish();
    recording.fill().unwrap();
    assert_eq!(
        operation
            .next_finalized(&mut recording)
            .unwrap()
            .unwrap()
            .as_str(),
        "hello"
    );
    assert_eq!(operation.completed().unwrap().as_str(), "hello");
    assert!(operation.next_finalized(&mut recording).unwrap().is_none());
}

#[test]
fn completion_without_a_final_segment_keeps_processed_text() {
    let (mut recording, mut capture) = Recording::open();
    let transcription = Transcription::agreement(
        Cadence::from_millis(100, 20_000),
        Scripted::new(["um hello", "um hello", "um hello"]),
    )
    .with(RemoveHesitations);
    let mut operation = transcription.start(&Language::Automatic).unwrap();
    capture.push(&[0.5; 1600]);
    operation.next_update(&mut recording).unwrap();
    capture.push(&[0.5; 1600]);
    assert_eq!(
        operation
            .next_finalized(&mut recording)
            .unwrap()
            .unwrap()
            .as_str(),
        "hello"
    );
    capture.finish();
    assert_eq!(operation.finish(&mut recording).unwrap().as_str(), "hello");
}

struct CountApplications(AtomicUsize);

impl Layer for CountApplications {
    fn apply(&self, text: &mut String, _: &CancelToken) -> Result<(), TranscriptionError> {
        self.0.fetch_add(1, Ordering::Relaxed);
        text.push('!');
        Ok(())
    }
}

#[test]
fn completion_includes_the_processed_tail_without_reapplying_layers() {
    for drain_tail in [false, true] {
        let calls = CountApplications(AtomicUsize::new(0));
        let (mut recording, mut capture) = Recording::open();
        let transcription = Transcription::agreement(
            Cadence::from_millis(100, 20_000),
            Scripted::new(["one two", "one two three"]),
        )
        .with(&calls);
        let mut operation = transcription.start(&Language::Automatic).unwrap();
        capture.push(&[0.5; 1600]);
        assert!(matches!(
            operation.next_update(&mut recording).unwrap(),
            Some(TranscriptUpdate::Provisional(text)) if text == "one two"
        ));
        capture.push(&[0.5; 1600]);
        capture.finish();
        recording.fill().unwrap();
        let first = operation.next_finalized(&mut recording).unwrap().unwrap();
        assert_eq!(first.as_str(), "one two!");
        assert_eq!(operation.completed().unwrap().as_str(), "one two! three!");
        if drain_tail {
            let tail = operation.next_finalized(&mut recording).unwrap().unwrap();
            assert_eq!(tail.as_str(), "three!");
            assert_eq!(
                [first.as_str(), tail.as_str()].join(" "),
                operation.completed().unwrap().as_str()
            );
        }
        assert_eq!(
            operation.finish(&mut recording).unwrap().as_str(),
            "one two! three!"
        );
        assert_eq!(calls.0.load(Ordering::Relaxed), 2);
    }
}

#[test]
fn processed_segments_keep_their_audio_spans_when_recording_is_released() {
    let timings = vec![
        TimedWord {
            start: 0.0,
            end: 0.025,
        },
        TimedWord {
            start: 0.025,
            end: 0.05,
        },
        TimedWord {
            start: 0.05,
            end: 0.075,
        },
    ];
    let scripted = Scripted(Mutex::new(VecDeque::from([
        Hypothesis::with_words("um one", timings[..2].to_vec()),
        Hypothesis::with_words("um one two", timings),
    ])));
    let (mut recording, mut capture) = Recording::open();
    let transcription = Transcription::agreement(Cadence::from_millis(100, 20_000), scripted)
        .with(RemoveHesitations);
    let mut operation = transcription.start(&Language::Automatic).unwrap();
    capture.push(&[0.5; 1600]);
    operation.next_update(&mut recording).unwrap();
    capture.push(&[0.5; 1600]);
    capture.finish();
    recording.fill().unwrap();
    let first = operation.next_finalized(&mut recording).unwrap().unwrap();
    assert_eq!(first.as_str(), "one");
    assert_eq!(first.span, Some(0..800));
    let retained = operation.retained_from();
    recording.release_before(retained);
    let tail = operation.next_finalized(&mut recording).unwrap().unwrap();
    assert_eq!(tail.as_str(), "two");
    assert_eq!(tail.span, Some(800..1200));
    let span = tail.span.unwrap();
    assert!(retained <= span.start);
    assert_eq!(recording.span(span).len(), 400);
}

struct StopOnTail(bool);

impl Layer for StopOnTail {
    fn apply(&self, text: &mut String, cancel: &CancelToken) -> Result<(), TranscriptionError> {
        if text == "three" {
            if self.0 {
                cancel.cancel();
            } else {
                return Err(TranscriptionError::Processing(Error::Failed(Box::new(
                    std::io::Error::other("rejected"),
                ))));
            }
        }
        Ok(())
    }
}

#[test]
fn cancellation_or_failure_in_the_tail_never_exposes_raw_completion() {
    for cancel_on_tail in [false, true] {
        let (mut recording, mut capture) = Recording::open();
        let transcription = Transcription::agreement(
            Cadence::from_millis(100, 20_000),
            Scripted::new(["one two", "one two three"]),
        )
        .with(StopOnTail(cancel_on_tail));
        let cancel = CancelToken::new();
        let mut operation = transcription
            .start_with(&Language::Automatic, &cancel)
            .unwrap();
        capture.push(&[0.5; 1600]);
        operation.next_update(&mut recording).unwrap();
        capture.push(&[0.5; 1600]);
        capture.finish();
        recording.fill().unwrap();
        let error = operation.next_finalized(&mut recording).unwrap_err();
        if cancel_on_tail {
            assert!(matches!(error, TranscriptionError::Cancelled));
        } else {
            assert!(matches!(
                error,
                TranscriptionError::Processing(Error::Failed(_))
            ));
        }
        assert!(operation.completed().is_none());
        assert!(operation.finish(&mut recording).is_err());
        assert!(operation.completed().is_none());
    }
}

#[test]
fn hesitations_preserve_sentence_punctuation() {
    for (input, expected) in [
        ("Well, um. Next.", "Well. Next."),
        ("Well, uh? Next.", "Well? Next."),
        ("Go. Um, so then", "Go. So then"),
    ] {
        let mut text = input.to_owned();
        RemoveHesitations
            .apply(&mut text, &CancelToken::never())
            .unwrap();
        assert_eq!(text, expected);
    }
}

#[test]
fn hesitations_preserve_delimiters_around_surviving_words() {
    for (input, expected) in [
        ("\"Um, hello.\"", "\"Hello.\""),
        ("(um hello)", "(hello)"),
        ("go (um uh now)", "go (now)"),
        ("go (um uh) now", "go now"),
        ("(Um) hello", "Hello"),
        ("(hello, um)", "(hello)"),
        ("[well; uh] next", "[well] next"),
        ("(um hello, uh)", "(hello)"),
        ("\"Hello. um\"", "\"Hello.\""),
    ] {
        let mut text = input.to_owned();
        RemoveHesitations
            .apply(&mut text, &CancelToken::never())
            .unwrap();
        assert_eq!(text, expected);
    }
}

#[test]
fn vocabulary_layer_rejects_personal_expansion_before_replacing_text() {
    let rules = vocabulary::PersonalRules::new(
        Vec::new(),
        vec![("x".to_owned(), "y".repeat(MAX_TEXT_BYTES + 1))],
    );
    let vocabulary = Vocabulary::compile(&[], rules).unwrap();
    let mut text = "x".to_owned();
    assert!(matches!(
        vocabulary.apply(&mut text, &CancelToken::never()),
        Err(TranscriptionError::Processing(Error::TooLarge))
    ));
    assert_eq!(text, "x");
}

struct Expand(usize);

impl Layer for Expand {
    fn apply(&self, text: &mut String, _: &CancelToken) -> Result<(), TranscriptionError> {
        *text = "x".repeat(self.0);
        Ok(())
    }
}

#[test]
fn text_bounds_cover_input_layer_output_and_accumulated_segments() {
    for (input_bytes, output_bytes) in [
        (MAX_TEXT_BYTES, MAX_TEXT_BYTES),
        (MAX_TEXT_BYTES + 1, 1),
        (1, MAX_TEXT_BYTES + 1),
    ] {
        let (_directory, mut recording) = recorded(&[1, 2]);
        let transcription =
            Transcription::complete_samples(Scripted::new(["x".repeat(input_bytes)]))
                .with(Expand(output_bytes));
        let result = transcription.transcribe(&mut recording, &Language::Automatic);
        if input_bytes <= MAX_TEXT_BYTES && output_bytes <= MAX_TEXT_BYTES {
            assert_eq!(result.unwrap().as_str().len(), output_bytes);
        } else {
            assert!(matches!(
                result,
                Err(TranscriptionError::Processing(Error::TooLarge))
            ));
        }
    }

    let (mut recording, mut capture) = Recording::open();
    let transcription = Transcription::agreement(
        Cadence::from_millis(100, 20_000),
        Scripted::new(["one", "one two"]),
    )
    .with(Expand(MAX_TEXT_BYTES / 2));
    let mut operation = transcription.start(&Language::Automatic).unwrap();
    capture.push(&[0.5; 1600]);
    operation.next_update(&mut recording).unwrap();
    capture.push(&[0.5; 1600]);
    capture.finish();
    recording.fill().unwrap();
    assert!(matches!(
        operation.next_finalized(&mut recording),
        Err(TranscriptionError::Processing(Error::TooLarge))
    ));
    assert!(operation.completed().is_none());
}