Repository navigation
Expand file tree
/
Copy pathtranscript.rs
More file actions
3962 lines (3769 loc) · 139 KB
/
Copy pathtranscript.rs
File metadata and controls
3962 lines (3769 loc) · 139 KB
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Meeting transcription. Each track streams through a 16 kHz resampler into
//! short pause-aware chunks that are transcribed at utility QoS whenever
//! dictation is idle: during the recording (rolling, which is also what the
//! Meetings pane and every in-call copy show) or from the WAV after Stop.
//! Hard cuts overlap and are deduplicated at the seam. The joined transcript
//! drops microphone utterances that echo the remote audio, and a Markdown
//! copy is published to the user's meeting folder.
use std::collections::VecDeque;
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TryRecvError};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use color_eyre::eyre::{Result, WrapErr, eyre};
use hound::WavReader;
use serde::{Deserialize, Serialize};
use crate::dictation::StreamingResampler;
#[cfg(target_os = "macos")]
use crate::transcription::Transcriber;
#[cfg(not(target_os = "macos"))]
use crate::transcription::local_transcriber::LocalTranscriber as Transcriber;
use crate::transcription::models::TranscriptionSelection;
use crate::transcription::pause_segmenter::PauseSegmenter;
use crate::transcription::transcript::{Transcript, TranscriptSegment};
use super::echo::{EchoEnvelope, Signal};
use super::{
AudioPacket, MeetingManifest, MeetingSource, TranscriptEntry, coalesce_transcript,
format_duration, set_owner_only, sync_directory,
};
const RATE: usize = 16_000;
const FRAME: usize = RATE / 50;
/// Pause cuts closer than this to the chunk start are ignored.
const CHUNK_MIN: usize = RATE * 3;
/// The first pause after this length ends a chunk. Short chunks keep the
/// in-call transcript a few seconds behind the call.
const CHUNK_TARGET: usize = RATE * 6;
/// Without a pause, a chunk is cut here and the next one overlaps it.
const CHUNK_MAX: usize = RATE * 10;
const CHUNK_OVERLAP: usize = RATE * 2;
const MIN_TAIL: usize = RATE * 3 / 10;
/// A chunk with no 20 ms frame this loud is silence and is not transcribed.
const SILENT_DB: f32 = -60.0;
/// About five minutes of one-second blocks for both sources.
const ROLLING_QUEUE_CAPACITY: usize = 600;
/// Chunks slower than this are logged.
const SLOW_CHUNK: Duration = Duration::from_secs(5);
/// A source whose untranscribed backlog exceeds this skips its oldest chunks;
/// the final transcript then rebuilds it from the WAV.
const MAX_PENDING_AUDIO: usize = RATE * 120;
const DICTATION_WAIT: Duration = Duration::from_secs(20);
/// Pause before retrying a chunk that dictation preempted.
const PREEMPTED_RETRY: Duration = Duration::from_millis(250);
const ECHO_WINDOW_MS: u64 = 1_500;
/// Word-level segments closer than this are judged together.
const UTTERANCE_GAP_MS: u64 = 700;
/// Entries with at least this many words are also judged on their own.
const SENTENCE_WORDS: usize = 3;
const ECHO_SIMILARITY: f32 = 0.6;
/// A pause this long between timed words starts a new sentence.
const SENTENCE_PAUSE_MS: i64 = 600;
const SEAM_MAX_WORDS: usize = 12;
/// How far apart two chunks may place the same word and still splice on it.
const SEAM_ANCHOR_MS: i64 = 300;
/// How far the system source's capture may trail the microphone's before
/// microphone text stops waiting for it.
const SYSTEM_STALL_MS: u64 = 5_000;
pub(super) const ROLLING_FILE: &str = "transcript.rolling.ndjson";
#[derive(Debug)]
pub(super) struct Chunk {
/// 16 kHz offset of `samples[0]` within the track.
start: usize,
/// Leading samples shared with the previous chunk.
overlap: usize,
/// Trailing samples the next chunk transcribes again.
tail: usize,
samples: Vec<f32>,
}
impl Chunk {
fn is_silent(&self) -> bool {
let threshold = 10_f32.powf(SILENT_DB / 10.0);
self.samples.chunks(FRAME).all(|frame| {
frame.iter().map(|sample| sample * sample).sum::<f32>() / (frame.len() as f32)
< threshold
})
}
}
/// Splits a 16 kHz track into chunks that end at pauses when possible.
#[derive(Default)]
pub(super) struct Chunker {
buffer: Vec<f32>,
buffer_start: usize,
chunk_start: usize,
overlap: usize,
segmenter: PauseSegmenter,
pauses: VecDeque<usize>,
}
impl Chunker {
pub(super) fn push(&mut self, samples: &[f32]) -> Vec<Chunk> {
for frame in samples.chunks(FRAME) {
if let Some(cut) = self.segmenter.push(frame) {
self.pauses.push_back(cut);
}
}
self.buffer.extend_from_slice(samples);
std::iter::from_fn(|| self.next_chunk()).collect()
}
pub(super) fn finish(self) -> Option<Chunk> {
self.rest(MIN_TAIL)
}
/// The audio not yet in a chunk, as one last chunk, when at least
/// `min_tail` samples follow the previous chunk; leaves the chunker as
/// it was.
fn rest(&self, min_tail: usize) -> Option<Chunk> {
let begin = self.chunk_start - self.overlap;
(self.end() >= self.chunk_start + min_tail.max(1)).then(|| Chunk {
start: begin,
overlap: self.overlap,
tail: 0,
samples: self.buffer[begin - self.buffer_start..].to_vec(),
})
}
fn end(&self) -> usize {
self.buffer_start + self.buffer.len()
}
fn next_chunk(&mut self) -> Option<Chunk> {
let start = self.chunk_start;
let end = self.end();
self.pauses.retain(|&cut| cut >= start + CHUNK_MIN);
let limit = start + CHUNK_MAX;
let preferred = self
.pauses
.iter()
.copied()
.find(|&cut| cut >= start + CHUNK_TARGET && cut <= limit.min(end));
let (cut, next_overlap) = match preferred {
Some(cut) => (cut, 0),
None if end >= limit => self
.pauses
.iter()
.copied()
.rfind(|&cut| cut <= limit)
.map_or((limit, CHUNK_OVERLAP), |cut| (cut, 0)),
None => return None,
};
let begin = start - self.overlap;
let chunk = Chunk {
start: begin,
overlap: self.overlap,
tail: next_overlap,
samples: self.buffer[begin - self.buffer_start..cut - self.buffer_start].to_vec(),
};
let keep_from = cut - next_overlap;
self.buffer.drain(..keep_from - self.buffer_start);
self.buffer_start = keep_from;
self.chunk_start = cut;
self.overlap = next_overlap;
Some(chunk)
}
}
/// Transcribes a chunk unless the speech detector finds no speech in it.
/// Models invent text for silence and noise, so a speechless chunk becomes an
/// empty transcript; accepting it still advances the track's coverage.
fn transcribe_speech(
samples: &[f32],
transcribe: impl FnOnce() -> Result<Transcript>,
) -> Result<Transcript> {
if speechless(samples) {
return Ok(Transcript::default());
}
transcribe()
}
/// Whether the speech detector heard no speech in `samples`, so they skip the
/// model.
fn speechless(samples: &[f32]) -> bool {
let speechless = crate::transcription::speech_detector::contains_speech(samples) == Some(false);
if speechless {
tracing::debug!(
audio_ms = samples_ms(samples.len()),
"skipped meeting chunk without detected speech"
);
}
speechless
}
/// One source's entries in capture-clock milliseconds.
#[derive(Clone)]
pub(super) struct TrackTranscript {
source: MeetingSource,
origin_ms: u64,
entries: Vec<TranscriptEntry>,
/// Timed words, in capture-clock milliseconds, of a sentence the next
/// chunk can still change: one that runs into its overlap.
words: Vec<TranscriptSegment>,
/// Capture-clock time before which entries are final: the next chunk's
/// seam replaces only entries that start after it.
settled_ms: u64,
/// Where a flush for a copy cut this track: a sentence always ends
/// there, so the copy's last sentence and the rest of it, published
/// later, are separate entries the paste cursor tells apart.
breaks: Vec<i64>,
}
impl TrackTranscript {
fn new(source: MeetingSource, origin_ms: u64) -> Self {
Self {
source,
origin_ms,
entries: Vec::new(),
words: Vec::new(),
settled_ms: origin_ms,
breaks: Vec::new(),
}
}
fn accept(&mut self, chunk: &Chunk, transcript: Transcript) {
let chunk_ms = self.origin_ms + samples_ms(chunk.start);
let duration_ms = samples_ms(chunk.samples.len());
let next_seam = chunk_ms + duration_ms - samples_ms(chunk.tail) / 2;
self.settled_ms = self.settled_ms.max(next_seam);
let untimed = !transcript.segments.is_empty() || !transcript.text.trim().is_empty();
if !transcript.words.is_empty() || (!untimed && !self.words.is_empty()) {
self.accept_words(chunk, chunk_ms, duration_ms, transcript.words);
self.publish_sentences(next_seam, chunk.tail == 0);
return;
}
// A model without word timings (Apple Speech) took over mid-track.
self.finish();
let segments = transcript.segments;
let segmented = !segments.is_empty();
let mut incoming: Vec<TranscriptEntry> = if segmented {
segments
.into_iter()
.filter_map(|segment| {
let text = segment.text.trim().to_string();
let start = (segment.start_ms.max(0) as u64).min(duration_ms);
let end = (segment.end_ms.max(0) as u64).min(duration_ms);
(!text.is_empty() && end > start).then(|| TranscriptEntry {
source: self.source,
start_ms: chunk_ms + start,
end_ms: chunk_ms + end,
text,
})
})
.collect()
} else {
let text = transcript.text.trim();
(!text.is_empty())
.then(|| TranscriptEntry {
source: self.source,
start_ms: chunk_ms,
end_ms: chunk_ms + duration_ms,
text: text.into(),
})
.into_iter()
.collect()
};
if chunk.overlap > 0 {
if segmented {
let seam = chunk_ms + samples_ms(chunk.overlap) / 2;
self.entries.retain(|entry| entry.start_ms < seam);
incoming.retain(|entry| entry.start_ms >= seam);
}
if let (Some(previous), Some(first)) = (self.entries.last(), incoming.first_mut()) {
first.text = strip_repeated_prefix(&previous.text, &first.text);
}
incoming.retain(|entry| !entry.text.is_empty());
}
self.entries.extend(incoming);
}
/// Joins a chunk's timed words at the seam word by word, so a sentence
/// that runs across a hard cut keeps every word from one side or the
/// other.
fn accept_words(
&mut self,
chunk: &Chunk,
chunk_ms: u64,
duration_ms: u64,
words: Vec<TranscriptSegment>,
) {
let mut incoming = words
.into_iter()
.filter_map(|word| {
let text = word.text.trim().to_string();
let start = (word.start_ms.max(0) as u64).min(duration_ms);
let end = (word.end_ms.max(0) as u64).clamp(start, duration_ms);
(!text.is_empty()).then(|| TranscriptSegment {
start_ms: (chunk_ms + start) as i64,
end_ms: (chunk_ms + end) as i64,
text,
})
})
.collect::<Vec<_>>();
if chunk.overlap > 0
&& let Some((kept, skipped)) =
seam_anchor(&self.words, &incoming, chunk_ms, samples_ms(chunk.overlap))
{
self.words.truncate(kept);
incoming.drain(..skipped);
} else if chunk.overlap > 0 {
let seam = (chunk_ms + samples_ms(chunk.overlap) / 2) as i64;
self.words.retain(|word| word.start_ms < seam);
incoming.retain(|word| word.start_ms >= seam);
let previous = if self.words.is_empty() {
self.entries
.last()
.map(|entry| entry.text.split_whitespace().map(normalize_word).collect())
.unwrap_or_default()
} else {
self.words
.iter()
.map(|word| normalize_word(&word.text))
.collect::<Vec<_>>()
};
let next = incoming
.iter()
.map(|word| normalize_word(&word.text))
.collect::<Vec<_>>();
incoming.drain(..repeated_prefix(&previous, &next));
}
self.words.extend(incoming);
}
/// Publishes every pending word, as when no chunk follows.
fn finish(&mut self) {
if let Some(end) = self.words.iter().map(|word| word.end_ms).max() {
self.settled_ms = self.settled_ms.max(end as u64 + 1);
}
self.publish_sentences(self.settled_ms, true);
}
/// Moves sentences no later chunk can change into the entries: every
/// sentence when nothing overlaps the next chunk, else those wholly
/// before `seam_ms` and closed by punctuation or a later sentence.
fn publish_sentences(&mut self, seam_ms: u64, all: bool) {
let seam_ms = seam_ms as i64;
let groups = sentence_groups(&self.words, &self.breaks);
let published = if all {
groups.len()
} else {
groups
.iter()
.enumerate()
.take_while(|(index, group)| {
let before_seam = |word: &TranscriptSegment| word.start_ms < seam_ms;
self.words[group.start..group.end].iter().all(before_seam)
&& (self.words[group.end - 1].text.ends_with(['.', '?', '!'])
|| groups
.get(index + 1)
.is_some_and(|next| before_seam(&self.words[next.start])))
})
.count()
};
let end = groups
.get(published)
.map_or(self.words.len(), |group| group.start);
let mut words = self.words.drain(..end).collect::<Vec<_>>();
if let Some(last) = words.last() {
let last = word_middle(last);
self.breaks.retain(|&cut| cut > last);
}
for group in groups.into_iter().take(published) {
let group = words.drain(..group.len()).collect::<Vec<_>>();
self.entries.push(TranscriptEntry {
source: self.source,
start_ms: group[0].start_ms as u64,
end_ms: group
.iter()
.map(|word| word.end_ms)
.max()
.unwrap_or_default() as u64,
text: group
.iter()
.map(|word| word.text.as_str())
.collect::<Vec<_>>()
.join(" "),
});
}
}
}
/// The middle of a word. Word boundaries move by tens of milliseconds when
/// a later chunk hears more context, so a cut is placed by word middles.
fn word_middle(word: &TranscriptSegment) -> i64 {
(word.start_ms + word.end_ms) / 2
}
/// Word ranges of each sentence in `words`: a sentence ends after sentence
/// punctuation, before a pause, or at one of `breaks` (the end of the last
/// word a copy took), between the words whose middles lie either side of it.
fn sentence_groups(words: &[TranscriptSegment], breaks: &[i64]) -> Vec<std::ops::Range<usize>> {
let mut groups: Vec<std::ops::Range<usize>> = Vec::new();
for (index, word) in words.iter().enumerate() {
match groups.last_mut() {
Some(group)
if !words[group.end - 1].text.ends_with(['.', '?', '!'])
&& !breaks.iter().any(|&cut| {
word_middle(&words[group.end - 1]) < cut && cut <= word_middle(word)
})
&& word.start_ms.saturating_sub(
words[group.clone()]
.iter()
.map(|word| word.end_ms)
.max()
.unwrap_or_default(),
) < SENTENCE_PAUSE_MS =>
{
group.end = index + 1;
}
_ => groups.push(index..index + 1),
}
}
groups
}
/// A word both chunks heard inside their overlap, at nearly the same time,
/// closest to the overlap's middle: the earlier chunk keeps it and the words
/// before it, the later chunk supplies what follows. Returns how many pending
/// words to keep and how many incoming words to skip. Splicing at a shared
/// word neither drops nor repeats a word whose timestamp shifts across the
/// middle between the two chunks.
fn seam_anchor(
previous: &[TranscriptSegment],
incoming: &[TranscriptSegment],
overlap_start_ms: u64,
overlap_ms: u64,
) -> Option<(usize, usize)> {
let start = overlap_start_ms as i64;
let end = start + overlap_ms as i64;
let middle = start + overlap_ms as i64 / 2;
let in_overlap = |word: &TranscriptSegment| word.start_ms >= start && word.start_ms < end;
let mut best: Option<(i64, usize, usize)> = None;
for (kept, old) in previous
.iter()
.enumerate()
.filter(|(_, word)| in_overlap(word))
{
let old_text = normalize_word(&old.text);
if old_text.is_empty() {
continue;
}
for (skipped, new) in incoming
.iter()
.enumerate()
.filter(|(_, word)| in_overlap(word))
{
if (old.start_ms - new.start_ms).abs() <= SEAM_ANCHOR_MS
&& normalize_word(&new.text) == old_text
{
let distance = (old.start_ms - middle).abs();
if best.is_none_or(|(best, _, _)| distance < best) {
best = Some((distance, kept + 1, skipped + 1));
}
}
}
}
best.map(|(_, kept, skipped)| (kept, skipped))
}
/// Removes words at the start of `next` that repeat the end of `previous`.
fn strip_repeated_prefix(previous: &str, next: &str) -> String {
let previous_words = previous
.split_whitespace()
.map(normalize_word)
.collect::<Vec<_>>();
let next_words = next.split_whitespace().collect::<Vec<_>>();
let normalized_next = next_words
.iter()
.map(|word| normalize_word(word))
.collect::<Vec<_>>();
next_words[repeated_prefix(&previous_words, &normalized_next)..].join(" ")
}
/// How many words (two to twelve) at the start of `next` repeat the end of
/// `previous`.
fn repeated_prefix(previous: &[String], next: &[String]) -> usize {
let longest = previous.len().min(next.len()).min(SEAM_MAX_WORDS);
(2..=longest)
.rev()
.find(|&count| previous[previous.len() - count..] == next[..count])
.unwrap_or(0)
}
fn normalize_word(word: &str) -> String {
word.chars()
.filter(|character| character.is_alphanumeric())
.flat_map(char::to_lowercase)
.collect()
}
fn tokens(text: &str) -> Vec<String> {
text.split(|character: char| !character.is_alphanumeric())
.filter(|token| !token.is_empty())
.map(str::to_lowercase)
.collect()
}
fn tokens_match(left: &str, right: &str) -> bool {
if left == right {
return true;
}
let left = left.chars().collect::<Vec<_>>();
let right = right.chars().collect::<Vec<_>>();
if left.len() < 3 || right.len() < 3 {
return false;
}
let distance = edit_distance(&left, &right);
1.0 - distance as f32 / left.len().max(right.len()) as f32 >= ECHO_SIMILARITY
}
fn edit_distance(left: &[char], right: &[char]) -> usize {
let mut previous = (0..=right.len()).collect::<Vec<_>>();
let mut current = vec![0; right.len() + 1];
for (row, left_char) in left.iter().enumerate() {
current[0] = row + 1;
for (column, right_char) in right.iter().enumerate() {
let substitution = previous[column] + usize::from(left_char != right_char);
current[column + 1] = substitution
.min(previous[column + 1] + 1)
.min(current[column] + 1);
}
std::mem::swap(&mut previous, &mut current);
}
previous[right.len()]
}
/// Drops microphone utterances that echo remote speech, which happens when
/// the call plays through speakers. An utterance is echo when the signal
/// says delayed system audio explains it, or when its words repeat
/// overlapping remote speech unless the signal shows local speech
/// (double-talk). `signal` classifies a microphone time span. Returns the
/// dropped count.
pub(super) fn suppress_echo(
entries: Vec<TranscriptEntry>,
signal: impl Fn(u64, u64) -> Option<Signal>,
) -> (Vec<TranscriptEntry>, u64) {
let system = entries
.iter()
.filter(|entry| entry.source == MeetingSource::System)
.collect::<Vec<_>>();
let mut microphone = entries
.iter()
.enumerate()
.filter(|(_, entry)| entry.source == MeetingSource::Microphone)
.collect::<Vec<_>>();
microphone.sort_by_key(|(_, entry)| entry.start_ms);
let mut utterances: Vec<Vec<(usize, &TranscriptEntry)>> = Vec::new();
for (index, entry) in microphone {
match utterances.last_mut() {
Some(utterance)
if entry
.start_ms
.saturating_sub(utterance.last().unwrap().1.end_ms)
<= UTTERANCE_GAP_MS =>
{
utterance.push((index, entry));
}
_ => utterances.push(vec![(index, entry)]),
}
}
let is_echo = |spoken: &[String], start_ms: u64, end_ms: u64, judge_words: bool| match signal(
start_ms, end_ms,
) {
Some(Signal::Bleed) => true,
Some(Signal::Local) => false,
None => judge_words && echo_score(spoken, start_ms, end_ms, &system) >= ECHO_SIMILARITY,
};
let mut dropped = vec![false; entries.len()];
let mut dropped_utterances = 0;
for utterance in utterances {
let spoken = utterance
.iter()
.flat_map(|(_, entry)| tokens(&entry.text))
.collect::<Vec<_>>();
let end = utterance
.iter()
.map(|(_, entry)| entry.end_ms)
.max()
.unwrap_or_default();
if is_echo(&spoken, utterance[0].1.start_ms, end, true) {
dropped_utterances += 1;
// Bleed can run straight into the user's own sentence; a sentence
// the signal shows is local survives its echoing neighbours.
for (index, entry) in utterance {
dropped[index] = tokens(&entry.text).len() < SENTENCE_WORDS
|| signal(entry.start_ms, entry.end_ms) != Some(Signal::Local);
}
continue;
}
if utterance.len() == 1 {
continue;
}
for (index, entry) in utterance {
let spoken = tokens(&entry.text);
if is_echo(
&spoken,
entry.start_ms,
entry.end_ms,
spoken.len() >= SENTENCE_WORDS,
) {
dropped_utterances += 1;
dropped[index] = true;
}
}
}
let kept = entries
.into_iter()
.zip(dropped)
.filter_map(|(entry, dropped)| (!dropped).then_some(entry))
.collect();
(kept, dropped_utterances)
}
/// The share of `spoken` that remote speech within the echo window contains.
fn echo_score(spoken: &[String], start_ms: u64, end_ms: u64, remote: &[&TranscriptEntry]) -> f32 {
let start = start_ms.saturating_sub(ECHO_WINDOW_MS);
let end = end_ms + ECHO_WINDOW_MS;
let remote = remote
.iter()
.filter(|entry| entry.start_ms < end && start < entry.end_ms)
.flat_map(|entry| tokens(&entry.text))
.collect::<Vec<_>>();
if remote.is_empty() || spoken.is_empty() {
return 0.0;
}
let matched = spoken
.iter()
.filter(|token| remote.iter().any(|remote| tokens_match(token, remote)))
.count();
matched as f32 / spoken.len() as f32
}
/// Removes echo from both sources' entries, then moves them onto the
/// meeting timeline. Entries and the envelope share the capture clock.
fn join_entries(
mut entries: Vec<TranscriptEntry>,
origin_ms: u64,
envelope: &EchoEnvelope,
) -> (Vec<TranscriptEntry>, u64) {
entries.sort_by_key(|entry| entry.start_ms);
let (mut entries, dropped) = suppress_echo(entries, |start, end| envelope.assess(start, end));
for entry in &mut entries {
entry.start_ms = entry.start_ms.saturating_sub(origin_ms);
entry.end_ms = entry.end_ms.saturating_sub(origin_ms);
}
(entries, dropped)
}
fn samples_ms(samples: usize) -> u64 {
samples as u64 * 1_000 / RATE as u64
}
fn source_index(source: MeetingSource) -> usize {
match source {
MeetingSource::System => 0,
MeetingSource::Microphone => 1,
}
}
fn wait_for_dictation() {
let started = Instant::now();
while crate::transcription::engine::dictation_busy()
&& !crate::desktop::process_exit::quitting()
&& started.elapsed() < DICTATION_WAIT
{
thread::sleep(Duration::from_millis(50));
}
}
/// Transcribes meeting chunks. In the app this borrows the dictation
/// engine's loaded model between dictations, at utility QoS, so a meeting
/// never loads a second copy. A process without an engine, such as the CLI,
/// loads its own.
pub(super) struct ChunkModel {
selection: TranscriptionSelection,
owned: Option<Transcriber>,
unavailable: bool,
}
enum Chunked {
Done(Transcript),
/// A dictation request or live stream came first; retry once it is idle.
Preempted,
/// No model could be loaded.
Unavailable(color_eyre::Report),
}
impl ChunkModel {
pub(super) fn new(selection: TranscriptionSelection) -> Self {
Self {
selection,
owned: None,
unavailable: false,
}
}
/// Fails with the chunk's own transcription error. A chunk without
/// detected speech returns an empty transcript without the model.
fn transcribe(&mut self, samples: &[f32]) -> Result<Chunked> {
// Quitting drops the dictation engine; a model loaded now would
// outlast the drain.
if crate::desktop::process_exit::quitting() {
return Ok(Chunked::Unavailable(eyre!("Hex is quitting")));
}
if speechless(samples) {
return Ok(Chunked::Done(Transcript::default()));
}
let engine = crate::transcription::engine::TranscriptionEngine::shared();
if let Some(engine) = &engine
&& let Some(result) = Self::transcribe_shared(engine, samples)
{
self.owned = None;
return result;
}
// In the app, follow dictation's current choice, such as Apple Speech.
let selection = if engine.is_some() {
crate::app_settings::transcription_selection().1
} else {
self.selection.clone()
};
drop(engine);
if self
.owned
.as_ref()
.is_some_and(|model| !model.matches_selection(&selection))
{
self.owned = None;
self.unavailable = false;
}
if self.unavailable {
return Ok(Chunked::Unavailable(eyre!(
"meeting transcriber is unavailable"
)));
}
if crate::desktop::process_exit::quitting() {
return Ok(Chunked::Unavailable(eyre!("Hex is quitting")));
}
let model = match load_model(&mut self.owned, &selection) {
Ok(model) => model,
Err(error) => {
self.unavailable = true;
return Ok(Chunked::Unavailable(error));
}
};
model
.transcribe_segments(samples.to_vec())
.map(Chunked::Done)
}
/// `None` when the engine has no GGUF model loaded.
fn transcribe_shared(
engine: &crate::transcription::engine::TranscriptionEngine,
samples: &[f32],
) -> Option<Result<Chunked>> {
let samples = samples.to_vec();
enum Shared {
Busy,
NoModel,
Ran(Result<Transcript>),
}
let ran = engine.background(move |model| {
// A capture that began after the meeting checked comes first.
if crate::transcription::engine::dictation_busy() {
return Shared::Busy;
}
match engine_model(model) {
Some(transcriber) => Shared::Ran(
crate::transcription::background_priority::at_background_priority(|| {
transcriber.transcribe_segments(samples)
}),
),
None => Shared::NoModel,
}
});
match ran {
Ok(None | Some(Shared::Busy)) => Some(Ok(Chunked::Preempted)),
Ok(Some(Shared::Ran(result))) => Some(result.map(Chunked::Done)),
Ok(Some(Shared::NoModel)) | Err(_) => None,
}
}
/// Transcribes `samples`, waiting out dictation as often as it preempts.
fn transcribe_blocking(&mut self, samples: &[f32]) -> Result<Transcript> {
loop {
wait_for_dictation();
match self.transcribe(samples)? {
Chunked::Done(transcript) => return Ok(transcript),
Chunked::Preempted => thread::sleep(PREEMPTED_RETRY),
Chunked::Unavailable(error) => return Err(error),
}
}
}
}
/// The engine's model when meetings can share it. Apple Speech runs outside
/// this process, so a meeting keeps its own rather than queue dictation
/// behind it.
#[cfg(target_os = "macos")]
fn engine_model(model: &mut crate::transcription::engine::Model) -> Option<&mut Transcriber> {
match model.active() {
Some(transcriber @ Transcriber::Gguf(_)) => Some(transcriber),
_ => None,
}
}
#[cfg(not(target_os = "macos"))]
fn engine_model(model: &mut crate::transcription::engine::Model) -> Option<&mut Transcriber> {
Some(model)
}
/// What the rolling worker transcribes chunks with: [`ChunkModel`], or a
/// fake in tests.
trait ChunkTranscriber {
/// `chunk.start` is the chunk's 16 kHz offset in its track.
fn transcribe_chunk(&mut self, chunk: &Chunk) -> Result<Chunked>;
}
impl ChunkTranscriber for ChunkModel {
fn transcribe_chunk(&mut self, chunk: &Chunk) -> Result<Chunked> {
self.transcribe(&chunk.samples)
}
}
fn load_model<'a>(
model: &'a mut Option<Transcriber>,
selection: &TranscriptionSelection,
) -> Result<&'a mut Transcriber> {
if model.is_none() {
#[cfg(test)]
tests::MODEL_LOADS.fetch_add(1, Ordering::SeqCst);
#[cfg(target_os = "macos")]
let loaded = Transcriber::load_selection(selection)?;
#[cfg(not(target_os = "macos"))]
let loaded = Transcriber::load(selection)?;
*model = Some(loaded);
}
model
.as_mut()
.ok_or_else(|| eyre!("meeting transcriber is unavailable"))
}
struct RollingTrack {
resampler: Option<StreamingResampler>,
sample_rate: u32,
chunker: Chunker,
/// 16 kHz track offset where the current chunker began, after any gap.
base: usize,
transcript: TrackTranscript,
/// 16 kHz samples of the track so far, gaps included.
fed: usize,
/// Track position, in source samples, expected of the next packet.
next_position: u64,
/// Untranscribed 16 kHz samples queued for this track.
pending: usize,
failed: bool,
}
impl RollingTrack {
fn push(
&mut self,
index: usize,
samples: &[f32],
envelope: &mut EchoEnvelope,
pending: &mut VecDeque<(usize, Chunk)>,
) {
envelope.push(
self.transcript.source,
self.transcript.origin_ms + samples_ms(self.fed),
samples,
RATE as u32,
);
self.fed += samples.len();
for mut chunk in self.chunker.push(samples) {
chunk.start += self.base;
self.pending += chunk.samples.len();
pending.push_back((index, chunk));
}
}
/// Queues the rest of the audio, as at Stop or before a gap.
fn end(
&mut self,
index: usize,
envelope: &mut EchoEnvelope,
pending: &mut VecDeque<(usize, Chunk)>,
) {
let tail = self
.resampler
.take()
.map(StreamingResampler::finish)
.unwrap_or_default();
self.push(index, &tail, envelope, pending);
if let Some(mut chunk) = std::mem::take(&mut self.chunker).finish() {
chunk.start += self.base;
self.pending += chunk.samples.len();
pending.push_back((index, chunk));
}
}
}
/// Transcribes short chunks while the meeting is still recording. Its
/// snapshot is the in-call transcript, and the final transcript reuses it
/// shortly after Stop.
pub(super) struct Rolling {
sender: Option<SyncSender<RollingInput>>,
flushes: Option<Receiver<FlushRequest>>,
flusher: RollingFlusher,
incomplete: Arc<[AtomicBool; 2]>,
worker: JoinHandle<RollingOutcome>,
}
/// What the capture writer sends the rolling worker, in capture order.
enum RollingInput {
Audio(AudioPacket),
/// Transcribe everything sent before this, for a copy.
Flush(FlushRequest),
}
struct FlushRequest {
deadline: Instant,
reply: SyncSender<Vec<TranscriptEntry>>,
}
pub(super) struct RollingFeed {
sender: SyncSender<RollingInput>,
flushes: Receiver<FlushRequest>,
incomplete: Arc<[AtomicBool; 2]>,
/// Per-source audio gathered into blocks of about a second, so the
/// bounded queue holds minutes of audio rather than ScreenCaptureKit's
/// many small packets.
blocks: [Option<AudioPacket>; 2],
}
impl RollingFeed {
/// Forwards without blocking. A full queue skips that block: the source
/// continues after the gap, and the final pass rebuilds it from its WAV.
pub(super) fn offer(&mut self, packet: &AudioPacket) {
let index = source_index(packet.source);
if self.blocks[index].as_ref().is_some_and(|block| {
block.sample_rate != packet.sample_rate
|| block.position + block.samples.len() as u64 != packet.position
}) {
self.send(index);
}
let block = self.blocks[index].get_or_insert_with(|| AudioPacket {
source: packet.source,
pts_us: packet.pts_us,
arrival_us: packet.arrival_us,
position: packet.position,
sample_rate: packet.sample_rate,
samples: Vec::with_capacity(packet.sample_rate as usize),
});
block.samples.extend_from_slice(&packet.samples);
if block.samples.len() >= block.sample_rate as usize {
self.send(index);
}
self.forward_copies();
}
/// Sends partial blocks and any copies waiting; call once capture ends.
pub(super) fn flush(&mut self) {
self.send_blocks();
self.forward_copies();
}
fn send_blocks(&mut self) {
self.send(0);
self.send(1);
}
/// Forwards waiting copies behind the partial blocks, so each covers
/// every sample received so far.
fn forward_copies(&mut self) {
while let Ok(request) = self.flushes.try_recv() {
self.send_blocks();
if self.sender.try_send(RollingInput::Flush(request)).is_err() {
tracing::warn!(
"rolling meeting transcription is behind; a copy gets what is ready"
);
}
}