-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.rs
More file actions
1230 lines (1077 loc) · 44.2 KB
/
engine.rs
File metadata and controls
1230 lines (1077 loc) · 44.2 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 anyhow::{Context, Result};
use std::path::Path;
use std::sync::{Arc, Mutex};
use tokio::runtime::Runtime;
use whisper_rs::{FullParams, SamplingStrategy, WhisperContext, WhisperContextParameters};
use super::backend::TranscriptionError;
/// Trait for transcription operations (enables testing via mocking)
///
/// This trait abstracts transcription functionality to enable dependency injection
/// and mock-based testing in components like the hotkey state machine.
///
/// Production code should use the concrete [`TranscriptionEngine`] type directly.
/// Use this trait for testing with `MockTranscriptionInterface` (via `mockall`).
#[cfg_attr(test, mockall::automock)]
#[allow(dead_code)] // Prepared for future hotkey.rs state machine tests
trait TranscriptionInterface: Send + Sync {
/// Transcribe audio samples to text
///
/// # Errors
/// Returns error if Whisper inference fails
fn transcribe(&self, audio_data: &[f32]) -> Result<String, TranscriptionError>;
}
/// Whisper transcription engine
pub struct TranscriptionEngine {
/// Whisper context (thread-safe)
#[allow(dead_code)] // Used in transcribe() method (Phase 5)
ctx: Arc<Mutex<WhisperContext>>,
/// Number of CPU threads for inference
threads: i32,
/// Beam search width
beam_size: i32,
/// Language code (None = auto-detect)
language: Option<String>,
}
impl TranscriptionEngine {
/// Determines sampling strategy based on beam size (pure, testable)
const fn get_sampling_strategy(beam_size: i32) -> SamplingStrategy {
if beam_size > 1 {
SamplingStrategy::BeamSearch {
beam_size,
patience: -1.0,
}
} else {
SamplingStrategy::Greedy { best_of: 1 }
}
}
/// Creates a new `TranscriptionEngine` by loading the model from the given path
///
/// # Errors
/// Returns error if model file doesn't exist, is invalid, or if `threads`/`beam_size` exceed `i32::MAX`
pub fn new(
model_path: &Path,
threads: usize,
beam_size: usize,
language: Option<String>,
) -> Result<Self, TranscriptionError> {
if threads == 0 {
return Err(TranscriptionError::ModelLoad {
path: model_path.display().to_string(),
source: anyhow::anyhow!("threads must be > 0"),
});
}
if beam_size == 0 {
return Err(TranscriptionError::ModelLoad {
path: model_path.display().to_string(),
source: anyhow::anyhow!("beam_size must be > 0"),
});
}
// Validate that threads and beam_size fit in i32 (required by whisper-rs API)
let threads_i32 = i32::try_from(threads).map_err(|_| TranscriptionError::ModelLoad {
path: model_path.display().to_string(),
source: anyhow::anyhow!("threads value too large (max: {})", i32::MAX),
})?;
let beam_size_i32 =
i32::try_from(beam_size).map_err(|_| TranscriptionError::ModelLoad {
path: model_path.display().to_string(),
source: anyhow::anyhow!("beam_size value too large (max: {})", i32::MAX),
})?;
tracing::info!(
path = %model_path.display(),
threads = threads,
beam_size = beam_size,
language = ?language,
"loading whisper model"
);
let path_str = model_path
.to_str()
.ok_or_else(|| TranscriptionError::ModelLoad {
path: model_path.display().to_string(),
source: anyhow::anyhow!("model path contains invalid UTF-8"),
})?;
let params = WhisperContextParameters::default();
let ctx = WhisperContext::new_with_params(path_str, params).map_err(|e| {
TranscriptionError::ModelLoad {
path: model_path.display().to_string(),
source: anyhow::anyhow!("{e:?}"),
}
})?;
tracing::info!("whisper model loaded successfully");
Ok(Self {
ctx: Arc::new(Mutex::new(ctx)),
threads: threads_i32,
beam_size: beam_size_i32,
language,
})
}
/// Transcribes audio samples (public interface)
///
/// # Errors
/// Returns error if Whisper inference fails or mutex is poisoned
#[allow(dead_code)] // Used in Phase 5
pub fn transcribe(&self, audio_data: &[f32]) -> Result<String, TranscriptionError> {
self.transcribe_impl(audio_data)
}
/// Transcribes audio samples (16kHz mono f32) to text with language auto-detection
///
/// # Errors
/// Returns error if Whisper inference fails or mutex is poisoned
#[allow(dead_code)] // Used in Phase 5
fn transcribe_impl(&self, audio_data: &[f32]) -> Result<String, TranscriptionError> {
let _span = tracing::debug_span!("transcription", samples = audio_data.len()).entered();
tracing::debug!("starting transcription");
// Create state for this transcription
let mut state = self
.ctx
.lock()
.map_err(|e| anyhow::anyhow!("mutex poisoned: {e}"))?
.create_state()
.map_err(|_| TranscriptionError::StateCreation)?;
// Configure transcription parameters with optimization settings
let strategy = Self::get_sampling_strategy(self.beam_size);
let mut params = FullParams::new(strategy);
params.set_n_threads(self.threads);
params.set_print_special(false);
params.set_print_progress(false);
params.set_print_realtime(false);
params.set_print_timestamps(false);
params.set_language(self.language.as_deref()); // Use configured language or auto-detect
params.set_translate(false);
// Run transcription
let start = std::time::Instant::now();
state
.full(params, audio_data)
.context("whisper inference failed")?;
let inference_duration = start.elapsed();
// Extract text from all segments
let mut result = String::new();
for segment in state.as_iter() {
result.push_str(&segment.to_string());
}
// Trim whitespace
let result = result.trim().to_owned();
tracing::info!(
segments = state.full_n_segments(),
text_len = result.len(),
inference_ms = inference_duration.as_millis(),
"transcription completed"
);
Ok(result)
}
}
/// Implement trait for real `TranscriptionEngine`
impl TranscriptionInterface for TranscriptionEngine {
fn transcribe(&self, audio_data: &[f32]) -> Result<String, TranscriptionError> {
self.transcribe_impl(audio_data)
}
}
/// Implement `TranscriptionBackend` trait for `TranscriptionEngine`
impl super::backend::TranscriptionBackend for TranscriptionEngine {
fn transcribe(&self, audio_data: &[f32]) -> Result<String, TranscriptionError> {
self.transcribe_impl(audio_data)
}
fn backend_name(&self) -> &'static str {
"whisper"
}
}
// SAFETY: TranscriptionEngine is thread-safe because:
// 1. WhisperContext is wrapped in Arc<Mutex<>>, ensuring exclusive access
// 2. All methods require acquiring the mutex lock before accessing the context
// 3. No shared mutable state exists outside the mutex
// 4. whisper-rs WhisperContext is documented as thread-safe when properly synchronized
#[allow(unsafe_code)]
unsafe impl Send for TranscriptionEngine {}
#[allow(unsafe_code)]
unsafe impl Sync for TranscriptionEngine {}
/// Type alias for backend map to reduce complexity
type BackendMap = std::collections::HashMap<String, Arc<dyn super::backend::TranscriptionBackend>>;
/// Manages multiple transcription backends with preloading and lazy loading
pub struct ModelManager {
/// Preloaded backends (`profile_name` -> backend)
preloaded: BackendMap,
/// Lazy loading configs for non-preloaded backends
lazy_configs: std::collections::HashMap<String, LazyBackendConfig>,
/// Backends currently being loaded (prevents concurrent load race condition)
loading: std::collections::HashSet<String>,
/// Deepgram API key (shared across Deepgram backends)
deepgram_api_key: Option<String>,
/// Shared tokio runtime for Deepgram backends
deepgram_runtime: Option<Arc<Runtime>>,
}
/// Configuration for lazy-loading a backend
enum LazyBackendConfig {
Local {
model_path: std::path::PathBuf,
threads: usize,
beam_size: usize,
language: Option<String>,
},
Deepgram {
model: String,
language: Option<String>,
smart_format: bool,
},
}
impl ModelManager {
/// Creates new `ModelManager` and preloads models where `profile.preload=true`
///
/// # Errors
/// Returns error if any preloaded model fails to load, if Deepgram config is required but missing,
/// or if internal invariant violation occurs (`deepgram_api_key` exists but `deepgram_runtime` is None)
pub fn new(
profiles: &[crate::config::TranscriptionProfile],
deepgram_config: Option<&crate::config::DeepgramConfig>,
) -> Result<Self> {
use crate::config::BackendConfig;
use std::collections::{HashMap, HashSet};
let mut preloaded = HashMap::new();
let mut lazy_configs = HashMap::new();
// Create shared Deepgram runtime if needed
let (deepgram_api_key, deepgram_runtime) = if let Some(dg_config) = deepgram_config {
let runtime = tokio::runtime::Runtime::new()
.context("failed to create tokio runtime for Deepgram")?;
(Some(dg_config.api_key.clone()), Some(Arc::new(runtime)))
} else {
(None, None)
};
for profile in profiles {
let profile_name = profile.name().to_owned();
match &profile.backend {
BackendConfig::Local {
model_type,
threads,
beam_size,
language,
} => {
let model_path = crate::config::Config::expand_path(&model_type.model_path())?;
if profile.preload {
tracing::info!("preloading local model: {}", profile_name);
let engine: Arc<dyn super::backend::TranscriptionBackend> =
Arc::new(TranscriptionEngine::new(
&model_path,
*threads,
*beam_size,
language.clone(),
)?);
preloaded.insert(profile_name, engine);
} else {
tracing::info!("deferring load for local model: {}", profile_name);
lazy_configs.insert(
profile_name.clone(),
LazyBackendConfig::Local {
model_path,
threads: *threads,
beam_size: *beam_size,
language: language.clone(),
},
);
}
}
BackendConfig::Deepgram {
model,
language,
smart_format,
} => {
let Some(ref api_key) = deepgram_api_key else {
anyhow::bail!(
"profile '{profile_name}' uses Deepgram backend but no API key configured"
);
};
if profile.preload {
tracing::info!("preloading deepgram backend: {profile_name}");
let runtime = deepgram_runtime.clone().ok_or_else(|| {
anyhow::anyhow!(
"internal error: deepgram_runtime missing when deepgram_api_key exists"
)
})?;
let backend = super::deepgram::DeepgramBackend::new(
api_key,
model.clone(),
language.clone(),
*smart_format,
runtime,
)?;
let backend: Arc<dyn super::backend::TranscriptionBackend> =
Arc::new(backend);
preloaded.insert(profile_name, backend);
} else {
tracing::info!("deferring load for deepgram backend: {profile_name}");
lazy_configs.insert(
profile_name.clone(),
LazyBackendConfig::Deepgram {
model: model.clone(),
language: language.clone(),
smart_format: *smart_format,
},
);
}
}
}
}
Ok(Self {
preloaded,
lazy_configs,
loading: HashSet::new(),
deepgram_api_key,
deepgram_runtime,
})
}
/// Gets backend for profile (preloaded or lazy loads on first use)
///
/// # Errors
/// Returns error if profile not found in config, fails to load,
/// or if internal invariant violation occurs (`deepgram_api_key` exists but `deepgram_runtime` is None)
pub fn get_or_load(
&mut self,
profile_name: &str,
) -> Result<Arc<dyn super::backend::TranscriptionBackend>> {
// Return preloaded backend if exists (fast path)
if let Some(backend) = self.preloaded.get(profile_name) {
return Ok(Arc::clone(backend));
}
// Check if currently being loaded by another thread
if self.loading.contains(profile_name) {
anyhow::bail!(
"backend is currently being loaded by another thread: {profile_name} (retry after load completes)"
);
}
// Lazy load if config exists
if let Some(config) = self.lazy_configs.remove(profile_name) {
// Mark as loading to prevent concurrent loads
self.loading.insert(profile_name.to_owned());
tracing::info!("lazy loading backend: {}", profile_name);
let load_result: Result<Arc<dyn super::backend::TranscriptionBackend>> = match config {
LazyBackendConfig::Local {
model_path,
threads,
beam_size,
language,
} => TranscriptionEngine::new(&model_path, threads, beam_size, language)
.map(|engine| Arc::new(engine) as Arc<dyn super::backend::TranscriptionBackend>)
.map_err(anyhow::Error::from),
LazyBackendConfig::Deepgram {
model,
language,
smart_format,
} => self.deepgram_api_key.as_ref().map_or_else(
|| {
Err(anyhow::Error::from(
super::backend::TranscriptionError::DeepgramConfigMissing,
))
},
|api_key| {
let runtime = self.deepgram_runtime.clone().ok_or_else(|| {
anyhow::anyhow!(
"internal error: deepgram_runtime missing when deepgram_api_key exists"
)
})?;
super::deepgram::DeepgramBackend::new(
api_key,
model,
language,
smart_format,
runtime,
)
.map(|backend| {
Arc::new(backend) as Arc<dyn super::backend::TranscriptionBackend>
})
.map_err(anyhow::Error::from)
},
),
};
// Remove from loading set before returning (cleanup in all paths)
self.loading.remove(profile_name);
// Handle load result
let backend = load_result?;
self.preloaded
.insert(profile_name.to_owned(), Arc::clone(&backend));
return Ok(backend);
}
anyhow::bail!("profile not found in configuration: {profile_name}")
}
/// Returns whether a model is currently loaded (preloaded or lazily loaded)
#[must_use]
#[allow(dead_code)] // Will be used for UI feedback
pub fn is_loaded(&self, model_name: &str) -> bool {
self.preloaded.contains_key(model_name)
}
}
#[cfg(test)]
#[allow(clippy::print_stderr)] // Test diagnostics
mod tests {
use super::*;
use std::path::PathBuf;
fn get_test_model_path() -> Option<PathBuf> {
// Check if a test model exists
let home = std::env::var("HOME").ok()?;
let path = PathBuf::from(home)
.join(".whisper-hotkey")
.join("models")
.join("ggml-tiny.bin");
if path.exists() {
Some(path)
} else {
None
}
}
#[test]
fn test_model_load_nonexistent_path() {
let nonexistent_path = Path::new("/tmp/nonexistent_model.bin");
let result = TranscriptionEngine::new(nonexistent_path, 4, 5, None);
assert!(result.is_err());
assert!(matches!(result, Err(TranscriptionError::ModelLoad { .. })));
if let Err(TranscriptionError::ModelLoad { path, .. }) = result {
assert!(path.contains("nonexistent_model.bin"));
}
}
#[test]
#[ignore = "requires actual model file"]
fn test_model_load_success() {
let Some(model_path) = get_test_model_path() else {
eprintln!("Skipping test: no model found at ~/.whisper-hotkey/models/ggml-tiny.bin");
return;
};
let engine = TranscriptionEngine::new(&model_path, 4, 5, None);
assert!(engine.is_ok(), "Failed to load model: {:?}", engine.err());
}
#[test]
#[ignore = "requires actual model file"]
fn test_transcribe_silence() {
let Some(model_path) = get_test_model_path() else {
eprintln!("Skipping test: no model found");
return;
};
let engine = TranscriptionEngine::new(&model_path, 4, 5, None).unwrap();
// 1 second of silence (16kHz)
let silence: Vec<f32> = vec![0.0; 16000];
let result = engine.transcribe(&silence);
assert!(result.is_ok());
// Silence should produce empty or minimal output
let text = result.unwrap();
assert!(
text.is_empty() || text.len() < 50,
"Expected empty or minimal output for silence, got: '{text}'"
);
}
#[test]
#[ignore = "requires actual model file"]
fn test_transcribe_empty_audio() {
let Some(model_path) = get_test_model_path() else {
eprintln!("Skipping test: no model found");
return;
};
let engine = TranscriptionEngine::new(&model_path, 4, 5, None).unwrap();
let empty: Vec<f32> = vec![];
let result = engine.transcribe(&empty);
// Empty audio might fail or return empty string
// Both are acceptable behaviors
if let Ok(text) = result {
assert!(text.is_empty() || text.len() < 50);
}
}
#[test]
#[ignore = "requires actual model file"]
#[allow(
clippy::cast_precision_loss,
clippy::cast_possible_truncation,
clippy::cast_sign_loss
)]
fn test_transcribe_short_audio() {
let Some(model_path) = get_test_model_path() else {
eprintln!("Skipping test: no model found");
return;
};
let engine = TranscriptionEngine::new(&model_path, 4, 5, None).unwrap();
// 0.5 seconds of a simple tone (440Hz sine wave)
let sample_rate = 16000.0;
let duration = 0.5;
let frequency = 440.0;
let samples = (sample_rate * duration) as usize;
let audio: Vec<f32> = (0..samples)
.map(|i| {
let t = i as f32 / sample_rate;
(2.0 * std::f32::consts::PI * frequency * t).sin() * 0.5
})
.collect();
let result = engine.transcribe(&audio);
assert!(result.is_ok());
// Tone should produce some output (might be empty or gibberish)
// Just verify it doesn't crash
}
#[test]
#[ignore = "requires actual model file"]
fn test_multiple_transcriptions() {
let Some(model_path) = get_test_model_path() else {
eprintln!("Skipping test: no model found");
return;
};
let engine = TranscriptionEngine::new(&model_path, 4, 5, None).unwrap();
// Run multiple transcriptions to verify state management works
for _ in 0..3 {
let silence: Vec<f32> = vec![0.0; 16000];
let result = engine.transcribe(&silence);
assert!(result.is_ok());
}
}
#[test]
#[ignore = "requires actual model file"]
fn test_transcribe_different_lengths() {
let Some(model_path) = get_test_model_path() else {
eprintln!("Skipping test: no model found");
return;
};
let engine = TranscriptionEngine::new(&model_path, 4, 5, None).unwrap();
// Test different audio lengths
let lengths = vec![8000, 16000, 32000, 48000]; // 0.5s, 1s, 2s, 3s
for length in lengths {
let audio: Vec<f32> = vec![0.0; length];
let result = engine.transcribe(&audio);
assert!(result.is_ok(), "Failed to transcribe {length} samples");
}
}
#[test]
#[ignore = "requires actual model file"]
fn test_long_recording_30s() {
let Some(model_path) = get_test_model_path() else {
eprintln!("Skipping test: no model found");
return;
};
let engine = TranscriptionEngine::new(&model_path, 4, 5, None).unwrap();
// 30 seconds of silence (16kHz)
let audio: Vec<f32> = vec![0.0; 16000 * 30];
let result = engine.transcribe(&audio);
assert!(result.is_ok(), "Failed to transcribe 30s audio");
}
#[test]
#[ignore = "requires actual model file"]
fn test_optimization_params() {
// NOTE: This test validates that different optimization parameters are accepted
// without crashing, but does not verify that they actually affect behavior or
// transcription quality. For performance validation, see manual tests in TESTING.md.
let Some(model_path) = get_test_model_path() else {
eprintln!("Skipping test: no model found");
return;
};
// Test with different optimization params
let engine_default = TranscriptionEngine::new(&model_path, 4, 5, None).unwrap();
let engine_fast = TranscriptionEngine::new(&model_path, 8, 1, None).unwrap();
let engine_accurate = TranscriptionEngine::new(&model_path, 4, 10, None).unwrap();
let silence: Vec<f32> = vec![0.0; 16000];
// All should work without errors
assert!(engine_default.transcribe(&silence).is_ok());
assert!(engine_fast.transcribe(&silence).is_ok());
assert!(engine_accurate.transcribe(&silence).is_ok());
}
#[test]
#[ignore = "requires actual model file"]
#[allow(clippy::cast_precision_loss)]
fn test_transcribe_noise() {
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hasher};
let Some(model_path) = get_test_model_path() else {
eprintln!("Skipping test: no model found");
return;
};
let engine = TranscriptionEngine::new(&model_path, 4, 5, None).unwrap();
// 2 seconds of random noise (16kHz)
let hasher = RandomState::new().build_hasher();
let seed = hasher.finish();
let mut rng_state = seed;
let mut noise = Vec::with_capacity(32000);
for _ in 0..32000 {
// Simple LCG for deterministic noise
rng_state = rng_state.wrapping_mul(1_103_515_245).wrapping_add(12345);
let sample = ((rng_state >> 16) as f32 / 32768.0) - 1.0;
noise.push(sample * 0.1); // Low amplitude noise
}
let result = engine.transcribe(&noise);
assert!(result.is_ok(), "Failed to transcribe noise");
// Noise should produce empty or minimal/gibberish output
let _text = result.unwrap();
// Just verify it doesn't crash - output is unpredictable for noise
}
#[test]
fn test_engine_is_send_sync() {
// Verify TranscriptionEngine can be shared across threads
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
assert_send::<TranscriptionEngine>();
assert_sync::<TranscriptionEngine>();
}
#[test]
fn test_new_with_zero_threads() {
let path = Path::new("/tmp/dummy.bin");
let result = TranscriptionEngine::new(path, 0, 5, None);
assert!(result.is_err());
assert!(matches!(result, Err(TranscriptionError::ModelLoad { .. })));
if let Err(TranscriptionError::ModelLoad { source, .. }) = result {
assert!(source.to_string().contains("threads must be > 0"));
}
}
#[test]
fn test_new_with_zero_beam_size() {
let path = Path::new("/tmp/dummy.bin");
let result = TranscriptionEngine::new(path, 4, 0, None);
assert!(result.is_err());
assert!(matches!(result, Err(TranscriptionError::ModelLoad { .. })));
if let Err(TranscriptionError::ModelLoad { source, .. }) = result {
assert!(source.to_string().contains("beam_size must be > 0"));
}
}
#[test]
fn test_new_with_valid_params() {
let path = Path::new("/tmp/nonexistent_but_valid_params.bin");
let result = TranscriptionEngine::new(path, 4, 5, Some("en".to_owned()));
// Will fail because file doesn't exist, but params are validated first
assert!(result.is_err());
assert!(matches!(result, Err(TranscriptionError::ModelLoad { .. })));
}
#[test]
fn test_thread_count_edge_cases() {
let path = Path::new("/tmp/dummy.bin");
// Test max i32 threads (i32::MAX as usize fits in i32, so validation passes)
// This tests that valid thread counts fail only on file load, not validation
let result = TranscriptionEngine::new(path, i32::MAX as usize, 5, None);
assert!(result.is_err());
assert!(matches!(result, Err(TranscriptionError::ModelLoad { .. })));
// Test overflow: usize > i32::MAX
#[cfg(target_pointer_width = "64")]
{
let result = TranscriptionEngine::new(path, (i32::MAX as usize) + 1, 5, None);
assert!(result.is_err());
assert!(matches!(result, Err(TranscriptionError::ModelLoad { .. })));
if let Err(TranscriptionError::ModelLoad { source, .. }) = result {
assert!(source.to_string().contains("threads value too large"));
}
}
}
#[test]
fn test_beam_size_edge_cases() {
let path = Path::new("/tmp/dummy.bin");
// Test max i32 beam_size (i32::MAX as usize fits in i32, so validation passes)
// This tests that valid beam sizes fail only on file load, not validation
let result = TranscriptionEngine::new(path, 4, i32::MAX as usize, None);
assert!(result.is_err());
assert!(matches!(result, Err(TranscriptionError::ModelLoad { .. })));
// Test overflow: usize > i32::MAX
#[cfg(target_pointer_width = "64")]
{
let result = TranscriptionEngine::new(path, 4, (i32::MAX as usize) + 1, None);
assert!(result.is_err());
assert!(matches!(result, Err(TranscriptionError::ModelLoad { .. })));
if let Err(TranscriptionError::ModelLoad { source, .. }) = result {
assert!(source.to_string().contains("beam_size value too large"));
}
}
}
// Phase 4: Sampling strategy tests (pure logic, fully testable)
#[test]
fn test_get_sampling_strategy_greedy() {
// beam_size = 1 should use Greedy strategy
let strategy = TranscriptionEngine::get_sampling_strategy(1);
assert!(matches!(strategy, SamplingStrategy::Greedy { best_of: 1 }));
}
#[test]
fn test_get_sampling_strategy_beam_search() {
// beam_size > 1 should use BeamSearch strategy
let strategy = TranscriptionEngine::get_sampling_strategy(5);
assert!(
matches!(
strategy,
SamplingStrategy::BeamSearch {
beam_size: 5,
patience: -1.0
}
),
"Expected BeamSearch with beam_size=5, patience=-1.0"
);
}
#[test]
fn test_get_sampling_strategy_various_beam_sizes() {
// Test different beam sizes
for beam in [1, 2, 3, 5, 8, 10] {
let strategy = TranscriptionEngine::get_sampling_strategy(beam);
if beam == 1 {
assert!(matches!(strategy, SamplingStrategy::Greedy { .. }));
} else {
assert!(
matches!(strategy, SamplingStrategy::BeamSearch { beam_size, .. } if beam_size == beam),
"Expected BeamSearch with beam_size={beam}"
);
}
}
}
#[test]
fn test_get_sampling_strategy_large_beam() {
// Test with large beam size
let strategy = TranscriptionEngine::get_sampling_strategy(100);
assert!(
matches!(
strategy,
SamplingStrategy::BeamSearch { beam_size: 100, .. }
),
"Expected BeamSearch with beam_size=100"
);
}
#[test]
fn test_get_sampling_strategy_min_beam() {
// Test boundary: beam_size = 1 is Greedy, beam_size = 2 is BeamSearch
let greedy = TranscriptionEngine::get_sampling_strategy(1);
assert!(matches!(greedy, SamplingStrategy::Greedy { .. }));
let beam = TranscriptionEngine::get_sampling_strategy(2);
assert!(matches!(beam, SamplingStrategy::BeamSearch { .. }));
}
#[test]
fn test_get_sampling_strategy_patience_always_negative_one() {
// Verify patience is always -1.0 for BeamSearch
for beam_size in [2, 5, 10, 20] {
let strategy = TranscriptionEngine::get_sampling_strategy(beam_size);
assert!(
matches!(
strategy,
SamplingStrategy::BeamSearch { patience: -1.0, .. }
),
"Expected BeamSearch with patience=-1.0 for beam_size={beam_size}"
);
}
}
#[test]
fn test_model_manager_new_empty_profiles() {
let profiles = vec![];
let manager = ModelManager::new(&profiles, None).unwrap();
assert_eq!(manager.preloaded.len(), 0);
assert_eq!(manager.lazy_configs.len(), 0);
assert_eq!(manager.loading.len(), 0);
}
#[test]
fn test_model_manager_new_preload_false() {
use crate::config::{BackendConfig, HotkeyConfig, ModelType, TranscriptionProfile};
let profiles = vec![TranscriptionProfile {
name: Some("test-model".to_owned()),
backend: BackendConfig::Local {
model_type: ModelType::BaseEn,
threads: 4,
beam_size: 1,
language: Some("en".to_owned()),
},
hotkey: HotkeyConfig::default(),
preload: false,
}];
let manager = ModelManager::new(&profiles, None).unwrap();
assert_eq!(manager.preloaded.len(), 0);
assert_eq!(manager.lazy_configs.len(), 1);
assert!(manager.lazy_configs.contains_key("test-model"));
}
#[test]
fn test_model_manager_get_or_load_model_not_found() {
let profiles = vec![];
let mut manager = ModelManager::new(&profiles, None).unwrap();
let result = manager.get_or_load("nonexistent");
assert!(result.is_err());
if let Err(err) = result {
assert!(err
.to_string()
.contains("profile not found in configuration"));
}
}
#[test]
fn test_model_manager_is_loaded_false() {
use crate::config::{BackendConfig, HotkeyConfig, ModelType, TranscriptionProfile};
let profiles = vec![TranscriptionProfile {
name: Some("test-model".to_owned()),
backend: BackendConfig::Local {
model_type: ModelType::BaseEn,
threads: 4,
beam_size: 1,
language: Some("en".to_owned()),
},
hotkey: HotkeyConfig::default(),
preload: false,
}];
let manager = ModelManager::new(&profiles, None).unwrap();
assert!(!manager.is_loaded("test-model"));
}
#[test]
fn test_model_manager_multiple_profiles_mixed_preload() {
use crate::config::{BackendConfig, HotkeyConfig, ModelType, TranscriptionProfile};
let profiles = vec![
TranscriptionProfile {
name: Some("lazy-model".to_owned()),
backend: BackendConfig::Local {
model_type: ModelType::BaseEn,
threads: 4,
beam_size: 1,
language: Some("en".to_owned()),
},
hotkey: HotkeyConfig {
modifiers: vec!["Command".to_owned()],
key: "A".to_owned(),
},
preload: false,
},
TranscriptionProfile {
name: Some("another-lazy".to_owned()),
backend: BackendConfig::Local {
model_type: ModelType::Small,
threads: 8,
beam_size: 5,
language: Some("es".to_owned()),
},
hotkey: HotkeyConfig {
modifiers: vec!["Command".to_owned()],
key: "B".to_owned(),
},
preload: false,
},
];
let manager = ModelManager::new(&profiles, None).unwrap();
assert_eq!(manager.preloaded.len(), 0);
assert_eq!(manager.lazy_configs.len(), 2);
assert!(manager.lazy_configs.contains_key("lazy-model"));
assert!(manager.lazy_configs.contains_key("another-lazy"));
}
#[test]
fn test_model_manager_lazy_config_stores_correct_values() {
use crate::config::{BackendConfig, HotkeyConfig, ModelType, TranscriptionProfile};
let profiles = vec![TranscriptionProfile {
name: Some("custom-model".to_owned()),
backend: BackendConfig::Local {
model_type: ModelType::Small,
threads: 8,
beam_size: 5,
language: Some("es".to_owned()),
},
hotkey: HotkeyConfig::default(),
preload: false,
}];
let manager = ModelManager::new(&profiles, None).unwrap();
let config = manager.lazy_configs.get("custom-model").unwrap();
assert!(
matches!(config, LazyBackendConfig::Local { .. }),
"expected Local backend config"
);
if let LazyBackendConfig::Local {
model_path,
threads,
beam_size,
language,
} = config
{
assert_eq!(*threads, 8);
assert_eq!(*beam_size, 5);
assert_eq!(*language, Some("es".to_owned()));
assert!(model_path.to_string_lossy().contains("small"));
}
}
#[test]
#[ignore = "requires actual model file"]
fn test_model_manager_get_or_load_lazy() {
use crate::config::{BackendConfig, HotkeyConfig, ModelType, TranscriptionProfile};
let profiles = vec![TranscriptionProfile {
name: Some("test-model".to_owned()),
backend: BackendConfig::Local {
model_type: ModelType::BaseEn,
threads: 4,
beam_size: 1,
language: Some("en".to_owned()),
},