Repository navigation
Expand file tree
/
Copy pathparakeet.rs
More file actions
2055 lines (1926 loc) · 73.5 KB
/
Copy pathparakeet.rs
File metadata and controls
2055 lines (1926 loc) · 73.5 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;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::Once;
use std::sync::atomic::{AtomicBool, AtomicUsize, 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, Model, ModelOptions, RunOptions, TimestampKind, Transcript};
use crate::context::ContextSnapshot;
use crate::dictation::{DictationClip, pad_for_parakeet};
use crate::dictation_processor::ProcessingObservation;
use crate::gguf_session::OfflineGgufSession;
use crate::history::{History, HistoryDraft, HistoryKind};
use crate::meeting;
use crate::paste::{PasteMode, Paster};
use crate::suppression::InputActivity;
use crate::transcription::WarmTranscriber;
use crate::transcription_engine::{PendingTranscript, TranscriptionEngine};
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>,
stream: Option<transcribe_cpp::StreamOptions>,
_weights: procwatch::Lease,
}
/// Loaded model weights, estimated from the model file size (they live in Metal buffers).
static MODEL_WEIGHTS: procwatch::Gauge = procwatch::Gauge::new("speech.model_weights");
static TRANSCRIBE_LOGGING: Once = Once::new();
#[cfg(hex_capture)]
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,
/// Dictate without processing: pasted as heard, skipping the Output
/// pane's steps.
RawPaste,
Service,
/// `hex dictation stop --print`: processed as a paste, then handed to
/// the waiting command instead of pasted.
Print,
/// A printing stop of a raw dictation: the transcript as heard.
RawPrint,
}
struct InferenceJob {
job_id: DictationJobId,
control: Arc<JobControl>,
submitted_at: Instant,
transcript: PendingTranscript,
audio_ms: u64,
prepare_ms: u128,
target: TranscriptionTarget,
context: ContextSnapshot,
}
struct ProcessorJob {
job_id: DictationJobId,
control: Arc<JobControl>,
target: TranscriptionTarget,
text: String,
context: ContextSnapshot,
timings: JobTimings,
}
/// Pipeline timings carried from inference through output for the final log.
#[derive(Clone, Copy)]
struct JobTimings {
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>,
timings: JobTimings,
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>,
/// A programmatic dictation's job: its owner app cancels it through the
/// API, so Escape never does.
owner_cancels: bool,
/// A printing stop's reply; dropping the job unanswered tells it the
/// dictation was cancelled or failed.
print: Mutex<Option<crate::control::PrintReply>>,
}
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)
}
/// Whether [`JobControl::cancel`] would cancel it now.
fn cancellable(&self) -> bool {
let output_started = self
.output_started
.lock()
.unwrap_or_else(|error| error.into_inner());
!*output_started && !self.is_cancelled()
}
fn is_cancelled(&self) -> bool {
self.cancelled.load(Ordering::Acquire)
}
fn answer_print(&self, transcript: crate::control::PrintedTranscript) {
if let Some(reply) = self
.print
.lock()
.unwrap_or_else(|error| error.into_inner())
.take()
{
reply.send(transcript);
}
}
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 {
engine: Option<Arc<TranscriptionEngine>>,
inference_jobs: Option<SyncSender<InferenceJob>>,
output_jobs: Option<SyncSender<OutputJob>>,
events: Receiver<WorkerEvent>,
event_sender: mpsc::Sender<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()
.filter(|(_, control)| !control.owner_cancels)
.find_map(|(&job_id, control)| control.cancel().then_some(job_id))
}
fn has_escape_cancellable_job(&self) -> bool {
self.jobs
.values()
.any(|control| !control.owner_cancels && control.cancellable())
}
}
impl DictationWorker {
pub fn start(
activity: InputActivity,
transformations: Arc<crate::personal_commands::TransformationClient>,
history: Option<History>,
) -> Self {
const PROCESSOR_WORKERS: usize = 2;
// Admission caps accepted jobs, so a submitted job always has a slot.
let (inference_jobs, inference_receiver) =
mpsc::sync_channel::<InferenceJob>(MAX_PENDING_OUTPUTS);
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 engine = match TranscriptionEngine::start(WarmTranscriber::default()) {
Ok(engine) => {
let events = event_sender.clone();
let _ = engine.run(move |model| {
prioritize_inference_thread();
match WarmTranscriber::load() {
Ok(loaded) => {
tracing::info!("transcription model loaded");
*model = loaded;
}
Err(error) => {
let _ = events.send(WorkerEvent::ModelFailed(error.to_string()));
}
}
});
let engine = Arc::new(engine);
engine.share();
Some(engine)
}
Err(error) => {
let _ = event_sender.send(WorkerEvent::ModelFailed(error.to_string()));
None
}
};
let output_worker = thread::spawn({
let state = state.clone();
let events = event_sender.clone();
move || run_output_worker(output_receiver, activity, history, &state, &events)
});
let processor_receiver = Arc::new(Mutex::new(processor_receiver));
let processor_workers = (0..PROCESSOR_WORKERS)
.map(|_| {
let jobs = processor_receiver.clone();
let output = output_jobs.clone();
let events = event_sender.clone();
let transformations = transformations.clone();
thread::spawn(move || {
run_processor_worker(&jobs, &output, &events, &transformations)
})
})
.collect();
let inference_worker = thread::spawn({
let output = output_jobs.clone();
let events = event_sender.clone();
move || run_inference_worker(inference_receiver, &processor_jobs, &output, &events)
});
Self {
engine,
inference_jobs: Some(inference_jobs),
output_jobs: Some(output_jobs),
events,
event_sender,
state,
inference_worker: Some(inference_worker),
processor_workers,
output_worker: Some(output_worker),
}
}
/// Hands the clip to the engine at once, so its live stream finishes
/// before any later capture begins one; the job then waits in order.
pub fn transcribe(
&self,
clip: DictationClip,
target: TranscriptionTarget,
context: ContextSnapshot,
) -> Result<DictationJobId, &'static str> {
self.submit(clip, target, context, None)
}
/// Like a paste, but the transcript (processed unless `raw`) goes to
/// `print`.
pub fn transcribe_printed(
&self,
clip: DictationClip,
print: crate::control::PrintReply,
raw: bool,
context: ContextSnapshot,
) -> Result<DictationJobId, &'static str> {
let target = if raw {
TranscriptionTarget::RawPrint
} else {
TranscriptionTarget::Print
};
self.submit(clip, target, context, Some(print))
}
fn submit(
&self,
mut clip: DictationClip,
target: TranscriptionTarget,
context: ContextSnapshot,
print: Option<crate::control::PrintReply>,
) -> 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 (Some(engine), Some(jobs)) = (&self.engine, &self.inference_jobs) else {
return Err("dictation worker is unavailable");
};
let control = Arc::new(JobControl {
owner_cancels: matches!(target, TranscriptionTarget::Service),
print: Mutex::new(print),
..JobControl::default()
});
let (_, selection) = crate::app_settings::transcription_selection();
let submitted_at = Instant::now();
let audio_ms = clip.duration_ms();
let stream = clip.take_stream();
let _capture = clip.take_capture_marker();
let samples = clip.into_transcription_samples();
crate::dictation_diagnostics::persist(&samples);
let prepare_ms = submitted_at.elapsed().as_millis();
let offline = {
let control = control.clone();
Box::new(move |model: &mut WarmTranscriber, samples: Vec<f32>| {
if control.is_cancelled() {
return Err("dictation was cancelled".to_string());
}
let _busy = DictationInference::begin();
let transcriber = model
.activate(&selection)
.map_err(|error| error.to_string())?;
transcriber
.transcribe(samples)
.map_err(|error| error.to_string())
})
};
let transcript = engine
.finish_with(stream, samples, offline)
.map_err(|_| "dictation worker is unavailable")?;
jobs.try_send(InferenceJob {
job_id,
control: control.clone(),
submitted_at,
transcript,
audio_ms,
prepare_ms,
target,
context,
})
.map(|()| {
state.next_sequence += 1;
state.jobs.insert(job_id, control);
job_id
})
.map_err(queue_error)
}
/// The engine that streams hotkey captures while they are recorded.
pub fn engine(&self) -> Option<Arc<TranscriptionEngine>> {
self.engine.clone()
}
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);
}
/// Switches the warm model after the work already handed to the engine.
pub fn reload(&self, selection: TranscriptionSelection) -> Result<(), &'static str> {
let events = self.event_sender.clone();
self.engine
.as_ref()
.ok_or("dictation worker is unavailable")?
.run(move |model| {
let _busy = DictationInference::begin();
if let Err(error) = model.activate(&selection) {
let _ = events.send(WorkerEvent::ModelFailed(error.to_string()));
}
})
.map_err(|_| "dictation worker is unavailable")
}
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()
}
/// Whether Escape has a queued job to cancel; programmatic dictations'
/// jobs don't count.
pub fn has_escape_cancellable_job(&self) -> bool {
self.state
.lock()
.unwrap_or_else(|error| error.into_inner())
.has_escape_cancellable_job()
}
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) {
// Accepted jobs still finish: the inference worker drains its queue.
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 run_output_worker(
jobs: Receiver<OutputJob>,
activity: InputActivity,
history: Option<History>,
state: &Mutex<WorkerState>,
events: &mpsc::Sender<WorkerEvent>,
) {
let mut paster = Paster::new(activity);
let mut last_transcript = None;
let mut ordered = OrderedOutputs::default();
while let Ok(job) = jobs.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,
history.as_ref(),
);
let mut state = 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 events.send(event).is_err() {
return;
}
}
}
}
fn run_processor_worker(
jobs: &Mutex<Receiver<ProcessorJob>>,
output: &SyncSender<OutputJob>,
events: &mpsc::Sender<WorkerEvent>,
transformations: &crate::personal_commands::TransformationClient,
) {
loop {
let job = jobs
.lock()
.unwrap_or_else(|error| error.into_inner())
.recv();
let Ok(job) = job else { break };
if job.control.is_cancelled() {
let _ = output.send(OutputJob::Cancelled { job_id: job.job_id });
continue;
}
let mut processed = process_job_text(&job, crate::config::dictation_profiles, || {
let _ = events.send(WorkerEvent::Stage {
job_id: job.job_id,
stage: DictationJobStage::Processing,
});
});
processed.apply_transformations(transformations, &job.context, &job.control.cancelled);
if job.control.is_cancelled() {
let _ = output.send(OutputJob::Cancelled { job_id: job.job_id });
continue;
}
if let Some(observation) = &processed.observation
&& let Some(error) = &observation.fallback
{
tracing::warn!(
profile = observation.profile,
%error,
"dictation processing fell back to the previous pipeline output"
);
}
if 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,
timings: job.timings,
processing: processed.observation,
})),
})
.is_err()
{
break;
}
}
}
/// Select processing when the worker reaches the job; the stage precedes processing.
fn process_job_text(
job: &ProcessorJob,
profiles: impl FnOnce() -> crate::dictation_processor::Profiles,
processing: impl FnOnce(),
) -> crate::dictation_processor::Processed {
let profiles = profiles();
if profiles.processes(&job.context) {
processing();
}
profiles.process_cancellable(&job.text, &job.context, &job.control.cancelled)
}
/// The longest audio the capture path hands the model at once; longer
/// captures are transcribed in consecutive chunks with their times offset.
#[cfg(hex_capture)]
const WORD_CHUNK_SAMPLES: usize = 30 * 16_000;
/// How long a capture chunk waits for dictation to go idle before it is
/// queued anyway; the engine still never runs it inside a live stream.
#[cfg(hex_capture)]
const WORD_DICTATION_WAIT: std::time::Duration = std::time::Duration::from_secs(20);
/// Transcribes a capture's 16 kHz audio with word timestamps on the engine's
/// warm model (the `capture` experiment). Before each chunk it waits while
/// dictation is busy (from the shortcut press through inference); each chunk
/// is then a foreground request: after the dictation already sent, before
/// meeting chunks, and never inside a dictation live stream, which finishes
/// first. No second copy of the model is loaded, and only a weak reference
/// to the engine is kept between chunks. Quitting stops it between chunks.
/// Every chunk runs on `selection`.
#[cfg(hex_capture)]
pub fn transcribe_with_words(
engine: &std::sync::Weak<TranscriptionEngine>,
selection: &crate::transcription_models::TranscriptionSelection,
samples: Vec<f32>,
) -> Result<crate::transcription::Transcript> {
if samples.is_empty() {
return Ok(crate::transcription::Transcript::default());
}
transcribe_in_chunks(samples, WORD_CHUNK_SAMPLES, |chunk| {
wait_for_dictation_idle()?;
let selection = selection.clone();
let (send, transcript) = mpsc::sync_channel(1);
let offline: crate::transcription_engine::Offline = Box::new(move |model, samples| {
let _busy = DictationInference::begin();
let transcriber = model
.activate(&selection)
.map_err(|error| format!("{error:#}"))?;
let result = transcriber
.transcribe_segments(samples)
.map_err(|error| format!("{error:#}"))?;
let text = result.text.clone();
let _ = send.send(result);
Ok(text)
});
let pending = engine
.upgrade()
.ok_or_else(|| eyre!("the transcription engine stopped"))?
.foreground(chunk, offline)?;
pending.wait().map_err(|error| eyre!(error))?;
transcript
.try_recv()
.map_err(|_| eyre!("the transcription returned no words"))
})
}
#[cfg(hex_capture)]
fn wait_for_dictation_idle() -> Result<()> {
let started = Instant::now();
while dictation_busy()
&& !crate::process_exit::quitting()
&& started.elapsed() < WORD_DICTATION_WAIT
{
thread::sleep(std::time::Duration::from_millis(50));
}
if crate::process_exit::quitting() {
return Err(eyre!("Hex is quitting"));
}
Ok(())
}
/// Transcribes `samples` in chunks of at most `chunk_samples`, offsetting
/// each chunk's segment and word times by where it starts.
#[cfg(hex_capture)]
fn transcribe_in_chunks(
samples: Vec<f32>,
chunk_samples: usize,
mut transcribe: impl FnMut(Vec<f32>) -> Result<crate::transcription::Transcript>,
) -> Result<crate::transcription::Transcript> {
use crate::transcription::{Transcript, TranscriptSegment};
let shift = |spans: Vec<TranscriptSegment>, offset_ms: i64| {
spans.into_iter().filter_map(move |span| {
let text = span.text.trim();
let start_ms = span.start_ms.max(0);
(!text.is_empty()).then(|| TranscriptSegment {
start_ms: start_ms + offset_ms,
end_ms: span.end_ms.max(start_ms) + offset_ms,
text: text.to_string(),
})
})
};
let mut merged = Transcript::default();
let mut texts = Vec::new();
for (index, chunk) in samples.chunks(chunk_samples.max(1)).enumerate() {
let offset_ms = (index * chunk_samples / TRANSCRIPTION_SAMPLES_PER_MS) as i64;
let result = transcribe(chunk.to_vec())?;
let text = result.text.trim();
if !text.is_empty() {
texts.push(text.to_string());
}
merged.segments.extend(shift(result.segments, offset_ms));
merged.words.extend(shift(result.words, offset_ms));
}
merged.text = texts.join(" ");
Ok(merged)
}
/// Waits for each accepted job's transcript in submission order, then hands
/// it to processing. The engine thread runs the inference itself.
fn run_inference_worker(
jobs: Receiver<InferenceJob>,
processor_jobs: &SyncSender<ProcessorJob>,
output: &SyncSender<OutputJob>,
events: &mpsc::Sender<WorkerEvent>,
) {
while let Ok(job) = jobs.recv() {
if job.control.is_cancelled() {
let _ = output.send(OutputJob::Cancelled { job_id: job.job_id });
continue;
}
let _busy = DictationInference::begin();
let _ = events.send(WorkerEvent::Stage {
job_id: job.job_id,
stage: DictationJobStage::Transcribing,
});
let total_started = job.submitted_at;
let queue_ms = total_started.elapsed().as_millis();
let inference_started = Instant::now();
let audio_ms = job.audio_ms;
let result = job.transcript.wait().map(|transcribed| {
tracing::info!(
source = transcribed.source.label(),
finish_ms = transcribed.finish_ms,
audio_ms,
"transcribed dictation"
);
let text = transcribed.text;
let corrected = if matches!(job.target, TranscriptionTarget::Service) {
text.clone()
} else {
text.trim().to_string()
};
tracing::debug!(
raw_transcript = text,
corrected_transcript = corrected,
"prepared local transcript"
);
corrected
});
let timings = JobTimings {
total_started,
queue_ms,
audio_ms,
prepare_ms: job.prepare_ms,
inference_ms: inference_started.elapsed().as_millis(),
};
if job.control.is_cancelled() {
let _ = output.send(OutputJob::Cancelled { job_id: job.job_id });
continue;
}
let target = job.target;
match result {
Ok(text)
if matches!(
target,
TranscriptionTarget::Paste | TranscriptionTarget::Print
) && !text.trim().is_empty() =>
{
if processor_jobs
.send(ProcessorJob {
job_id: job.job_id,
control: job.control,
target,
text,
context: job.context,
timings,
})
.is_err()
{
break;
}
}
result => {
let application = job.context.application;
let result = result.map(|text| CompletedTranscript {
raw: text.clone(),
text,
application,
timings,
processing: None,
});
if output
.send(OutputJob::Completed {
job_id: job.job_id,
control: job.control,
target,
result: Box::new(result),
})
.is_err()
{
break;
}
}
}
}
}
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() {
// ggml worker pthreads start at default QoS instead of inheriting this
// class; GGUF sessions use one decoder thread so decoding stays here.
const QOS_CLASS_USER_INTERACTIVE: u32 = 0x21;
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_INTERACTIVE, 0) };
if status == 0 {
tracing::info!("dictation inference worker uses user-interactive QoS");
} else {
tracing::warn!(status, "could not raise dictation inference worker QoS");
}
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn prioritize_inference_thread() {}
static DICTATION_INFERENCE: AtomicUsize = AtomicUsize::new(0);
struct DictationInference;
impl DictationInference {
fn begin() -> Self {
DICTATION_INFERENCE.fetch_add(1, Ordering::AcqRel);
Self
}
}
impl Drop for DictationInference {
fn drop(&mut self) {
DICTATION_INFERENCE.fetch_sub(1, Ordering::AcqRel);
}
}
/// Makes [`dictation_busy`] hold until dropped, as a dictation would.
#[cfg(test)]
pub(crate) struct DictationBusyForTest {
_busy: DictationInference,
}
#[cfg(test)]
pub(crate) fn dictation_busy_for_test() -> DictationBusyForTest {
DictationBusyForTest {
_busy: DictationInference::begin(),
}
}
/// Whether dictation is capturing or running inference. Meeting
/// transcription starts no chunk while this holds. A capture counts from its
/// press: a chunk already running then finishes during the hold threshold
/// and release tail, before the clip needs the model.
pub(crate) fn dictation_busy() -> bool {
DICTATION_INFERENCE.load(Ordering::Acquire) > 0
|| crate::recording_environment::capture_active()
|| crate::recording_environment::intentional_recording_active()
}
/// Runs `work` at utility QoS on the dictation inference thread, then
/// restores its user-interactive class.
pub(crate) fn at_background_priority<R>(work: impl FnOnce() -> R) -> R {
const QOS_CLASS_USER_INTERACTIVE: u32 = 0x21;
const QOS_CLASS_UTILITY: u32 = 0x11;
unsafe extern "C" {
fn pthread_set_qos_class_self_np(qos_class: u32, relative_priority: i32) -> i32;
}
// SAFETY: These configure only the calling thread using the public macOS
// pthread QoS API. Relative priority zero is valid for both classes.
unsafe { pthread_set_qos_class_self_np(QOS_CLASS_UTILITY, 0) };
let result = work();
unsafe { pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0) };
result
}
/// Runs the calling thread at utility QoS for background transcription.
pub(crate) fn deprioritize_background_thread() {
const QOS_CLASS_UTILITY: u32 = 0x11;
unsafe extern "C" {
fn pthread_set_qos_class_self_np(qos_class: u32, relative_priority: i32) -> i32;
}
// SAFETY: This configures only the calling 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_UTILITY, 0) };
if status != 0 {
tracing::warn!(status, "could not lower background transcription QoS");
}
}
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>,
history: Option<&History>,
) -> WorkerEvent {
match job {
OutputJob::PreparePaste => unreachable!("paste preparation bypasses ordered output"),
OutputJob::Completed {
job_id,
control,
target,