-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathparakeet.rs
More file actions
1665 lines (1568 loc) · 61.6 KB
/
Copy pathparakeet.rs
File metadata and controls
1665 lines (1568 loc) · 61.6 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
use std::collections::{BTreeMap, HashSet};
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::Once;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError};
use std::thread;
use std::time::Instant;
use color_eyre::eyre::{Result, WrapErr, eyre};
use transcribe_cpp::{
Backend, ExtSlot, Model, ModelOptions, RunExtension, RunOptions, TimestampKind, Transcript,
WhisperRunOptions, sys::TRANSCRIBE_EXT_KIND_WHISPER_RUN,
};
use crate::context::ContextSnapshot;
use crate::dictation::{DictationClip, DictationProtocol, pad_for_parakeet};
use crate::dictation_processor::ProcessingObservation;
use crate::history::{History, HistoryDraft, HistoryKind};
use crate::meeting::{self, TranscriptEntry, TranscriptPublication};
use crate::paste::{PasteMode, Paster};
use crate::suppression::InputActivity;
#[cfg(test)]
use crate::text_replacements::ReplacementSet;
use crate::transcription::{OfflineGgufSession, Transcriber, WarmTranscriber};
use crate::transcription_models::{
TranscriptionModelId, TranscriptionSelection, model_path, validate,
};
pub struct Parakeet {
session: OfflineGgufSession,
options: RunOptions,
name: String,
selection: Option<TranscriptionSelection>,
max_audio_samples: Option<usize>,
}
static TRANSCRIBE_LOGGING: Once = Once::new();
const TRANSCRIPTION_SAMPLES_PER_MS: usize = 16;
const MAX_PENDING_OUTPUTS: usize = 16;
pub enum WorkerEvent {
ModelFailed(String),
Completed {
job_id: DictationJobId,
target: TranscriptionTarget,
result: Result<String, String>,
processing: Option<ProcessingObservation>,
},
Stage {
job_id: DictationJobId,
stage: DictationJobStage,
},
Cancelled {
job_id: DictationJobId,
},
Pasted {
kind: PasteKind,
result: Result<String, String>,
},
}
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct DictationJobId(u64);
impl DictationJobId {
pub const fn value(self) -> u64 {
self.0
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DictationJobStage {
Transcribing,
Processing,
}
#[derive(Clone, Copy, Debug)]
pub enum PasteKind {
LastTranscript,
MeetingDelta,
}
#[derive(Clone, Copy, Debug)]
pub enum TranscriptionTarget {
Paste,
Send,
VoiceAction,
Service,
}
struct InferenceJob {
job_id: DictationJobId,
control: Arc<JobControl>,
submitted_at: Instant,
clip: DictationClip,
target: TranscriptionTarget,
protocol: Option<Arc<DictationProtocol>>,
context: ContextSnapshot,
selection: TranscriptionSelection,
}
enum InferenceCommand {
Reload(TranscriptionSelection),
Transcribe(Box<InferenceJob>),
}
struct ProcessorJob {
job_id: DictationJobId,
control: Arc<JobControl>,
target: TranscriptionTarget,
text: String,
context: ContextSnapshot,
total_started: Instant,
queue_ms: u128,
audio_ms: u64,
prepare_ms: u128,
inference_ms: u128,
}
struct CompletedTranscript {
text: String,
/// Corrected local transcript before mode processing.
raw: String,
application: Option<String>,
total_started: Instant,
queue_ms: u128,
audio_ms: u64,
prepare_ms: u128,
inference_ms: u128,
processing: Option<ProcessingObservation>,
}
enum OutputJob {
PreparePaste,
Completed {
job_id: DictationJobId,
control: Arc<JobControl>,
target: TranscriptionTarget,
result: Box<Result<CompletedTranscript, String>>,
},
Cancelled {
job_id: DictationJobId,
},
Paste {
sequence: u64,
kind: PasteKind,
},
}
impl OutputJob {
fn sequence(&self) -> u64 {
match self {
Self::PreparePaste => u64::MAX,
Self::Completed { job_id, .. } | Self::Cancelled { job_id } => job_id.0,
Self::Paste { sequence, .. } => *sequence,
}
}
}
#[derive(Default)]
struct JobControl {
cancelled: AtomicBool,
output_started: Mutex<bool>,
}
impl JobControl {
fn cancel(&self) -> bool {
let output_started = self
.output_started
.lock()
.unwrap_or_else(|error| error.into_inner());
if *output_started {
return false;
}
!self.cancelled.swap(true, Ordering::AcqRel)
}
fn is_cancelled(&self) -> bool {
self.cancelled.load(Ordering::Acquire)
}
fn begin_output(&self) -> bool {
let mut output_started = self
.output_started
.lock()
.unwrap_or_else(|error| error.into_inner());
if self.is_cancelled() {
return false;
}
*output_started = true;
true
}
}
#[derive(Default)]
struct OrderedOutputs {
waiting: BTreeMap<u64, OutputJob>,
next_sequence: u64,
}
impl OrderedOutputs {
fn push(&mut self, job: OutputJob) -> Vec<OutputJob> {
if job.sequence() < self.next_sequence {
return Vec::new();
}
self.waiting.insert(job.sequence(), job);
let mut ready = Vec::new();
while let Some(job) = self.waiting.remove(&self.next_sequence) {
ready.push(job);
self.next_sequence += 1;
}
ready
}
}
pub struct DictationWorker {
inference_jobs: Option<SyncSender<InferenceCommand>>,
output_jobs: Option<SyncSender<OutputJob>>,
events: Receiver<WorkerEvent>,
state: Arc<Mutex<WorkerState>>,
inference_worker: Option<thread::JoinHandle<()>>,
processor_workers: Vec<thread::JoinHandle<()>>,
output_worker: Option<thread::JoinHandle<()>>,
}
struct WorkerState {
next_sequence: u64,
jobs: BTreeMap<DictationJobId, Arc<JobControl>>,
pending_pastes: usize,
}
impl WorkerState {
fn next_output_sequence(&self) -> Result<u64, &'static str> {
// Count accepted work even after it leaves a channel for ordered buffering.
if self.jobs.len() + self.pending_pastes >= MAX_PENDING_OUTPUTS {
return Err("dictation queue is full");
}
Ok(self.next_sequence)
}
fn cancel_latest(&self) -> Option<DictationJobId> {
self.jobs
.iter()
.rev()
.find_map(|(&job_id, control)| control.cancel().then_some(job_id))
}
}
impl DictationWorker {
pub fn start(
activity: InputActivity,
transformations: Arc<crate::personal_commands::TransformationClient>,
history: Option<History>,
) -> Self {
const PROCESSOR_WORKERS: usize = 2;
let (inference_jobs, inference_receiver) = mpsc::sync_channel::<InferenceCommand>(2);
let (processor_jobs, processor_receiver) = mpsc::sync_channel::<ProcessorJob>(4);
let (output_jobs, output_receiver) = mpsc::sync_channel::<OutputJob>(8);
let (event_sender, events) = mpsc::channel();
let state = Arc::new(Mutex::new(WorkerState {
next_sequence: 0,
jobs: BTreeMap::new(),
pending_pastes: 0,
}));
let output_state = state.clone();
let output_events = event_sender.clone();
let output_worker = thread::spawn(move || {
let mut paster = Paster::new(activity);
let mut last_transcript = None;
let mut meeting_cursor = MeetingPasteCursor::default();
let mut ordered = OrderedOutputs::default();
while let Ok(job) = output_receiver.recv() {
if matches!(job, OutputJob::PreparePaste) {
paster.prepare();
continue;
}
for job in ordered.push(job) {
let event = finish_output(
job,
&mut |text, mode, commit| paster.paste(text, mode, commit),
&mut last_transcript,
&mut meeting_cursor,
history.as_ref(),
);
let mut state = output_state
.lock()
.unwrap_or_else(|error| error.into_inner());
match &event {
WorkerEvent::Completed { job_id, .. }
| WorkerEvent::Cancelled { job_id } => {
state.jobs.remove(job_id);
}
WorkerEvent::Pasted { .. } => {
state.pending_pastes = state.pending_pastes.saturating_sub(1);
}
WorkerEvent::ModelFailed(_) | WorkerEvent::Stage { .. } => {}
}
drop(state);
if output_events.send(event).is_err() {
return;
}
}
}
});
let processor_receiver = Arc::new(Mutex::new(processor_receiver));
let mut processor_workers = Vec::with_capacity(PROCESSOR_WORKERS);
for _ in 0..PROCESSOR_WORKERS {
let processor_receiver = processor_receiver.clone();
let processor_output = output_jobs.clone();
let processor_events = event_sender.clone();
let transformations = transformations.clone();
processor_workers.push(thread::spawn(move || {
loop {
let job = {
processor_receiver
.lock()
.unwrap_or_else(|error| error.into_inner())
.recv()
};
let Ok(job) = job else { break };
if job.control.is_cancelled() {
let _ = processor_output.send(OutputJob::Cancelled { job_id: job.job_id });
continue;
}
let profiles = crate::config::dictation_profiles();
if matches!(job.target, TranscriptionTarget::VoiceAction)
|| profiles.processes(&job.context)
{
let _ = processor_events.send(WorkerEvent::Stage {
job_id: job.job_id,
stage: DictationJobStage::Processing,
});
}
let mut processed = if matches!(job.target, TranscriptionTarget::VoiceAction) {
profiles.process_voice_action_cancellable(
&job.text,
job.context.selected_text.as_deref(),
&job.context,
&job.control.cancelled,
)
} else {
profiles.process_cancellable(
&job.text,
&job.context,
&job.control.cancelled,
)
};
if !processed.transformations.is_empty() && !job.control.is_cancelled() {
let started = Instant::now();
match transformations.transform(
&processed.transformations,
&processed.text,
&job.context,
&job.control.cancelled,
) {
Ok(text) => {
processed.text = text;
let observation = processed.observation.get_or_insert_with(|| {
ProcessingObservation {
profile: "Custom transformations".into(),
latency_ms: 0,
fallback: None,
}
});
observation.latency_ms = observation
.latency_ms
.saturating_add(started.elapsed().as_millis() as u64);
}
Err(error) => {
let observation = processed.observation.get_or_insert_with(|| {
ProcessingObservation {
profile: "Custom transformations".into(),
latency_ms: 0,
fallback: None,
}
});
observation.latency_ms = observation
.latency_ms
.saturating_add(started.elapsed().as_millis() as u64);
observation.fallback = Some(error);
}
}
}
if job.control.is_cancelled() {
let _ = processor_output.send(OutputJob::Cancelled { job_id: job.job_id });
continue;
}
if let Some(observation) = &processed.observation
&& let Some(error) = &observation.fallback
{
if matches!(job.target, TranscriptionTarget::VoiceAction) {
tracing::warn!(%error, "voice action processing failed");
} else {
tracing::warn!(
profile = observation.profile,
%error,
"dictation processing fell back to the previous pipeline output"
);
}
}
if processor_output
.send(OutputJob::Completed {
job_id: job.job_id,
control: job.control,
target: job.target,
result: Box::new(Ok(CompletedTranscript {
text: processed.text,
raw: job.text,
application: job.context.application,
total_started: job.total_started,
queue_ms: job.queue_ms,
audio_ms: job.audio_ms,
prepare_ms: job.prepare_ms,
inference_ms: job.inference_ms,
processing: processed.observation,
})),
})
.is_err()
{
break;
}
}
}));
}
let inference_events = event_sender.clone();
let inference_output = output_jobs.clone();
let inference_worker = thread::spawn(move || {
prioritize_inference_thread();
let mut transcriber = match WarmTranscriber::load() {
Ok(transcriber) => {
tracing::info!("transcription model loaded");
transcriber
}
Err(error) => {
let _ = inference_events.send(WorkerEvent::ModelFailed(error.to_string()));
WarmTranscriber::default()
}
};
while let Ok(command) = inference_receiver.recv() {
let job = match command {
InferenceCommand::Reload(selection) => {
if let Err(error) = transcriber.activate(&selection) {
let _ =
inference_events.send(WorkerEvent::ModelFailed(error.to_string()));
}
continue;
}
InferenceCommand::Transcribe(job) => *job,
};
if job.control.is_cancelled() {
let _ = inference_output.send(OutputJob::Cancelled { job_id: job.job_id });
continue;
}
let _ = inference_events.send(WorkerEvent::Stage {
job_id: job.job_id,
stage: DictationJobStage::Transcribing,
});
let transcriber = match transcriber.activate(&job.selection) {
Ok(transcriber) => transcriber,
Err(error) => {
let _ = inference_output.send(OutputJob::Completed {
job_id: job.job_id,
control: job.control,
target: job.target,
result: Box::new(Err(error.to_string())),
});
continue;
}
};
let total_started = job.submitted_at;
let queue_ms = total_started.elapsed().as_millis();
let audio_ms = job.clip.duration_ms();
let prepare_started = Instant::now();
let clip_samples = job.clip.into_transcription_samples();
crate::dictation_diagnostics::persist(&clip_samples);
let samples = transcriber.prepare_samples(clip_samples);
let prepare_ms = prepare_started.elapsed().as_millis();
let inference_started = Instant::now();
let result = match (transcriber, job.protocol.as_deref()) {
(Transcriber::Gguf(model), Some(protocol)) => {
model.transcribe_voice(&samples, protocol)
}
(transcriber, _) => transcriber.transcribe(&samples),
}
.map(|text| {
let corrected = if matches!(job.target, TranscriptionTarget::Service) {
text.clone()
} else {
prepare_transcript(&text, job.protocol.as_deref())
};
tracing::debug!(
raw_transcript = text,
corrected_transcript = corrected,
"prepared local transcript"
);
corrected
})
.map_err(|error| error.to_string());
let inference_ms = inference_started.elapsed().as_millis();
if job.control.is_cancelled() {
let _ = inference_output.send(OutputJob::Cancelled { job_id: job.job_id });
continue;
}
match result {
Ok(text)
if matches!(
job.target,
TranscriptionTarget::Paste
| TranscriptionTarget::Send
| TranscriptionTarget::VoiceAction
) && !text.trim().is_empty() =>
{
if processor_jobs
.send(ProcessorJob {
job_id: job.job_id,
control: job.control,
target: job.target,
text,
context: job.context,
total_started,
queue_ms,
audio_ms,
prepare_ms,
inference_ms,
})
.is_err()
{
break;
}
}
result => {
let application = job.context.application;
let result = result.map(|text| CompletedTranscript {
raw: text.clone(),
text,
application,
total_started,
queue_ms,
audio_ms,
prepare_ms,
inference_ms,
processing: None,
});
if inference_output
.send(OutputJob::Completed {
job_id: job.job_id,
control: job.control,
target: job.target,
result: Box::new(result),
})
.is_err()
{
break;
}
}
}
}
});
Self {
inference_jobs: Some(inference_jobs),
output_jobs: Some(output_jobs),
events,
state,
inference_worker: Some(inference_worker),
processor_workers,
output_worker: Some(output_worker),
}
}
pub fn transcribe(
&self,
clip: DictationClip,
target: TranscriptionTarget,
protocol: Option<Arc<DictationProtocol>>,
context: ContextSnapshot,
) -> Result<DictationJobId, &'static str> {
let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
let job_id = DictationJobId(state.next_output_sequence()?);
let control = Arc::new(JobControl::default());
let (_, selection) = crate::app_settings::transcription_selection();
self.inference_jobs
.as_ref()
.ok_or("dictation worker is unavailable")?
.try_send(InferenceCommand::Transcribe(Box::new(InferenceJob {
job_id,
control: control.clone(),
submitted_at: Instant::now(),
clip,
target,
protocol,
context,
selection,
})))
.map(|()| {
state.next_sequence += 1;
state.jobs.insert(job_id, control);
job_id
})
.map_err(queue_error)
}
pub fn prepare_paste(&self) {
let state = self.state.lock().unwrap_or_else(|error| error.into_inner());
if !state.jobs.is_empty() || state.pending_pastes > 0 {
return;
}
drop(state);
let Some(output_jobs) = &self.output_jobs else {
return;
};
let _ = output_jobs.try_send(OutputJob::PreparePaste);
}
pub fn reload(&self, selection: TranscriptionSelection) -> Result<(), &'static str> {
self.inference_jobs
.as_ref()
.ok_or("dictation worker is unavailable")?
.try_send(InferenceCommand::Reload(selection))
.map_err(queue_error)
}
pub fn paste_last(&self) -> Result<(), &'static str> {
self.submit_paste(PasteKind::LastTranscript)
}
pub fn paste_meeting(&self) -> Result<(), &'static str> {
self.submit_paste(PasteKind::MeetingDelta)
}
fn submit_paste(&self, kind: PasteKind) -> Result<(), &'static str> {
let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
let sequence = state.next_output_sequence()?;
self.output_jobs
.as_ref()
.ok_or("dictation worker is unavailable")?
.try_send(OutputJob::Paste { sequence, kind })
.map(|()| {
state.next_sequence += 1;
state.pending_pastes += 1;
})
.map_err(queue_error)
}
pub fn try_recv(&self) -> Option<WorkerEvent> {
self.events.try_recv().ok()
}
pub fn is_busy(&self) -> bool {
let state = self.state.lock().unwrap_or_else(|error| error.into_inner());
!state.jobs.is_empty() || state.pending_pastes > 0
}
pub fn pending_count(&self) -> usize {
self.state
.lock()
.unwrap_or_else(|error| error.into_inner())
.jobs
.len()
}
pub fn cancel_latest(&self) -> Option<DictationJobId> {
let state = self.state.lock().unwrap_or_else(|error| error.into_inner());
let job_id = state.cancel_latest()?;
drop(state);
let _ = self
.output_jobs
.as_ref()?
.try_send(OutputJob::Cancelled { job_id });
Some(job_id)
}
fn shutdown(&mut self) {
self.inference_jobs.take();
join_worker(self.inference_worker.take(), "dictation inference");
for worker in self.processor_workers.drain(..) {
join_worker(Some(worker), "dictation processing");
}
self.output_jobs.take();
join_worker(self.output_worker.take(), "dictation output");
}
}
impl Drop for DictationWorker {
fn drop(&mut self) {
self.shutdown();
}
}
fn join_worker(worker: Option<thread::JoinHandle<()>>, name: &str) {
if let Some(worker) = worker
&& worker.join().is_err()
{
tracing::error!(worker = name, "worker panicked during shutdown");
}
}
#[cfg(target_os = "macos")]
pub(crate) fn prioritize_inference_thread() {
const QOS_CLASS_USER_INITIATED: u32 = 0x19;
unsafe extern "C" {
fn pthread_set_qos_class_self_np(qos_class: u32, relative_priority: i32) -> i32;
}
// SAFETY: This configures only the calling worker thread using the public
// macOS pthread QoS API. Relative priority zero is valid for this class.
let status = unsafe { pthread_set_qos_class_self_np(QOS_CLASS_USER_INITIATED, 0) };
if status == 0 {
tracing::info!("dictation inference worker uses user-initiated QoS");
} else {
tracing::warn!(status, "could not raise dictation inference worker QoS");
}
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn prioritize_inference_thread() {}
fn queue_error(error: TrySendError<impl Sized>) -> &'static str {
match error {
TrySendError::Full(_) => "dictation queue is full",
TrySendError::Disconnected(_) => "dictation worker is unavailable",
}
}
fn finish_output(
job: OutputJob,
paste: &mut impl FnMut(&str, PasteMode, &dyn Fn() -> bool) -> Result<()>,
last_transcript: &mut Option<String>,
meeting_cursor: &mut MeetingPasteCursor,
history: Option<&History>,
) -> WorkerEvent {
match job {
OutputJob::PreparePaste => unreachable!("paste preparation bypasses ordered output"),
OutputJob::Completed {
job_id,
control,
target,
result,
} if !control.is_cancelled() => {
let result = *result;
let processing = result
.as_ref()
.ok()
.and_then(|result| result.processing.clone());
let result = result.and_then(|completed| {
if matches!(target, TranscriptionTarget::VoiceAction)
&& let Some(error) = completed
.processing
.as_ref()
.and_then(|processing| processing.fallback.clone())
{
return Err(error);
}
if control.is_cancelled() {
return Err("voice action was cancelled".into());
}
let paste_started = Instant::now();
if !completed.text.trim().is_empty() {
let commit = || control.begin_output();
match target {
TranscriptionTarget::Paste => {
paste(&completed.text, PasteMode::Continue, &commit)
}
TranscriptionTarget::Send => {
paste(&completed.text, PasteMode::Send, &commit)
}
TranscriptionTarget::VoiceAction => {
paste(&completed.text, PasteMode::Standalone, &commit)
}
TranscriptionTarget::Service => commit()
.then_some(())
.ok_or_else(|| eyre!("dictation was cancelled")),
}
.map_err(|error| error.to_string())?;
if matches!(
target,
TranscriptionTarget::Paste | TranscriptionTarget::Send
) {
*last_transcript = Some(completed.text.clone());
}
if let Some(history) = history {
record_history(history, target, &completed);
}
}
tracing::info!(
audio_ms = completed.audio_ms,
queue_ms = completed.queue_ms,
prepare_ms = completed.prepare_ms,
inference_ms = completed.inference_ms,
paste_ms = paste_started.elapsed().as_millis(),
total_ms = completed.total_started.elapsed().as_millis(),
"dictation pipeline completed"
);
Ok(completed.text)
});
if control.is_cancelled() {
WorkerEvent::Cancelled { job_id }
} else {
WorkerEvent::Completed {
job_id,
target,
result,
processing,
}
}
}
OutputJob::Completed { job_id, .. } | OutputJob::Cancelled { job_id } => {
WorkerEvent::Cancelled { job_id }
}
OutputJob::Paste { kind, .. } => {
let result = match kind {
PasteKind::LastTranscript => last_transcript
.as_deref()
.ok_or_else(|| "no previous transcript is available".to_string())
.and_then(|text| {
paste(text, PasteMode::Continue, &|| true)
.map_err(|error| error.to_string())?;
Ok(text.to_string())
}),
PasteKind::MeetingDelta => {
paste_meeting_delta(paste, meeting_cursor).map_err(|error| error.to_string())
}
};
WorkerEvent::Pasted { kind, result }
}
}
}
/// Record one successfully pasted result. History failures must never fail
/// the paste that already happened.
fn record_history(history: &History, target: TranscriptionTarget, completed: &CompletedTranscript) {
let kind = match target {
TranscriptionTarget::Paste => HistoryKind::Dictation,
TranscriptionTarget::Send => HistoryKind::Send,
TranscriptionTarget::VoiceAction => HistoryKind::VoiceAction,
TranscriptionTarget::Service => return,
};
let draft = HistoryDraft {
kind,
raw_text: completed.raw.clone(),
final_text: completed.text.clone(),
application: completed.application.clone(),
processing: completed.processing.as_ref().map(|processing| {
crate::history::HistoryProcessing {
profile: processing.profile.clone(),
latency_ms: processing.latency_ms,
fallback: processing.fallback.clone(),
}
}),
audio_ms: completed.audio_ms,
inference_ms: completed.inference_ms as u64,
total_ms: completed.total_started.elapsed().as_millis() as u64,
};
if let Err(error) = history.record(draft) {
tracing::warn!(%error, "could not record dictation history");
}
}
fn prepare_transcript(text: &str, protocol: Option<&DictationProtocol>) -> String {
strip_transcript_protocol(text, protocol)
}
#[cfg(test)]
fn prepare_transcript_with(
text: &str,
protocol: Option<&DictationProtocol>,
replacements: &ReplacementSet,
) -> String {
replacements.replace(&strip_transcript_protocol(text, protocol))
}
fn strip_transcript_protocol(text: &str, protocol: Option<&DictationProtocol>) -> String {
protocol.map_or_else(|| text.trim().to_string(), |protocol| protocol.strip(text))
}
#[derive(Default)]
struct MeetingPasteCursor {
meeting_id: Option<String>,
publication: Option<TranscriptPublication>,
seen: HashSet<TranscriptEntry>,
}
fn paste_meeting_delta(
paste: &mut impl FnMut(&str, PasteMode, &dyn Fn() -> bool) -> Result<()>,
cursor: &mut MeetingPasteCursor,
) -> Result<String> {
let meetings = meeting::list()?;
let selected = meeting::active_or_latest(&meetings)
.ok_or_else(|| eyre!("no meeting transcript is available"))?;
// Live and final ASR use different segment boundaries, so switching a
// cursor between them could repeat or skip an overlapping segment.
let same_meeting = cursor.meeting_id.as_deref() == Some(&selected.id);
let empty = HashSet::new();
let (publication, seen) = if same_meeting {
(cursor.publication, &cursor.seen)
} else {
(None, &empty)
};
let transcript = meeting::completed_transcript(&selected.id, publication)?;
let (text, pasted_entries) = prepare_meeting_delta(&transcript.entries, seen)?;
paste(&text, PasteMode::Standalone, &|| true)?;
if !same_meeting {
cursor.seen.clear();
}
cursor.meeting_id = Some(selected.id.clone());
cursor.publication = Some(transcript.publication);
cursor.seen.extend(pasted_entries);
Ok(text)
}
fn prepare_meeting_delta(
entries: &[TranscriptEntry],
seen: &HashSet<TranscriptEntry>,
) -> Result<(String, Vec<TranscriptEntry>)> {
let new_entries = entries
.iter()
.filter(|entry| !seen.contains(*entry))
.cloned()
.collect::<Vec<_>>();
if new_entries.is_empty() {
return Err(eyre!("no new completed meeting transcript is available"));
}
let text = meeting::coalesce_transcript(new_entries.iter().cloned())
.into_iter()
.map(|entry| format!("{}: {}", entry.source.label(), entry.text))
.collect::<Vec<_>>()
.join("\n\n");
Ok((text, new_entries))
}
pub(crate) fn default_model_path() -> Result<std::path::PathBuf> {
model_path(crate::transcription_models::definition(
crate::transcription_models::TranscriptionModelId::default(),
))
}
impl Parakeet {
#[cfg(test)]
pub fn load() -> Result<Self> {
let (_, selection) = crate::app_settings::transcription_selection();
Self::load_selection(&selection)
}
pub fn load_selection(selection: &TranscriptionSelection) -> Result<Self> {
let definition = validate(selection)?;
if !crate::transcription_models::is_installed(definition, &selection.language) {
return Err(eyre!("{} is not installed", definition.name));
}
let path = model_path(definition)?;
let mut parakeet = Self::load_from(&path, true, Some(selection))?;
let prewarm_started = Instant::now();
let mut silence = Vec::new();
pad_for_parakeet(&mut silence);
parakeet
.transcribe(&silence)
.wrap_err("could not prewarm transcription model")?;
tracing::info!(
prewarm_ms = prewarm_started.elapsed().as_millis(),
"prewarmed transcription model"
);
Ok(parakeet)
}
pub(crate) fn load_for_benchmark(model_path: &std::path::Path) -> Result<Self> {
Self::load_from(model_path, false, None)
}
fn load_from(
model_path: &std::path::Path,
diagnostics: bool,
selection: Option<&TranscriptionSelection>,
) -> Result<Self> {
if diagnostics {
TRANSCRIBE_LOGGING.call_once(transcribe_cpp::init_logging);
} else {
transcribe_cpp::disable_logging();
}
let model = Model::load_with(
model_path,
&ModelOptions {
backend: Backend::Metal,
gpu_device: 0,
},
)
.wrap_err_with(|| {
format!(
"could not load transcription model from {}",
model_path.display()
)
})?;
let device = model.device()?;
if device.kind != "metal" {
return Err(eyre!(
"transcription model selected {} ({}) instead of Metal",
device.kind,
device.name
));