-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.rs
More file actions
2948 lines (2627 loc) · 90.9 KB
/
config.rs
File metadata and controls
2948 lines (2627 loc) · 90.9 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 serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
/// Whisper model type variants
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModelType {
/// Tiny model (multilingual)
Tiny,
/// Tiny model (English-only)
TinyEn,
/// Base model (multilingual)
Base,
/// Base model (English-only)
BaseEn,
/// Small model (multilingual)
Small,
/// Small model (English-only)
SmallEn,
/// Medium model (multilingual)
Medium,
/// Medium model (English-only)
MediumEn,
/// Large model (multilingual)
Large,
/// Large model v1 (multilingual)
LargeV1,
/// Large model v2 (multilingual)
LargeV2,
/// Large model v3 (multilingual)
LargeV3,
}
// Custom serde to serialize as "base.en" instead of "BaseEn"
impl Serialize for ModelType {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for ModelType {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Self::from_str(&s).map_err(serde::de::Error::custom)
}
}
impl ModelType {
/// Get model name as string (e.g., "base.en")
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Tiny => "tiny",
Self::TinyEn => "tiny.en",
Self::Base => "base",
Self::BaseEn => "base.en",
Self::Small => "small",
Self::SmallEn => "small.en",
Self::Medium => "medium",
Self::MediumEn => "medium.en",
Self::Large => "large",
Self::LargeV1 => "large-v1",
Self::LargeV2 => "large-v2",
Self::LargeV3 => "large-v3",
}
}
/// Parse model type from string (e.g., "base.en" -> `BaseEn`)
fn from_str(s: &str) -> Result<Self, String> {
match s {
"tiny" => Ok(Self::Tiny),
"tiny.en" => Ok(Self::TinyEn),
"base" => Ok(Self::Base),
"base.en" => Ok(Self::BaseEn),
"small" => Ok(Self::Small),
"small.en" => Ok(Self::SmallEn),
"medium" => Ok(Self::Medium),
"medium.en" => Ok(Self::MediumEn),
"large" => Ok(Self::Large),
"large-v1" => Ok(Self::LargeV1),
"large-v2" => Ok(Self::LargeV2),
"large-v3" => Ok(Self::LargeV3),
_ => Err(format!("unknown model type: {s}")),
}
}
/// Get model name for `HuggingFace` download (same as `as_str`)
#[must_use]
pub const fn model_name(self) -> &'static str {
self.as_str()
}
/// Get default path for model (as string with ~ for home)
#[must_use]
pub fn model_path(self) -> String {
format!("~/.whisper-hotkey/models/ggml-{}.bin", self.as_str())
}
}
#[allow(clippy::derivable_impls)] // We want Small as default, not Tiny (first variant)
impl Default for ModelType {
fn default() -> Self {
Self::Small // Small is a good balance of speed/accuracy
}
}
/// Deepgram API configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DeepgramConfig {
/// API key for Deepgram service
pub api_key: String,
}
/// Backend configuration for transcription
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "backend", rename_all = "lowercase")]
pub enum BackendConfig {
/// Local Whisper model (offline, free)
Local {
/// Model type (e.g., "small", "base.en")
model_type: ModelType,
/// Number of CPU threads for inference
#[serde(default = "default_threads")]
threads: usize,
/// Beam search width (higher = slower but more accurate)
#[serde(default = "default_beam_size")]
beam_size: usize,
/// Language code (None = auto-detect)
#[serde(default = "default_language")]
language: Option<String>,
},
/// Deepgram cloud API (online, paid, faster)
Deepgram {
/// Model name (e.g., "whisper-large", "nova-3")
model: String,
/// Language code (None = auto-detect)
#[serde(default)]
language: Option<String>,
/// Enable Deepgram's smart formatting (punctuation, etc.)
#[serde(default = "default_smart_format")]
smart_format: bool,
},
}
const fn default_smart_format() -> bool {
true
}
// Helper functions for skip_serializing_if
fn is_default_hotkey(val: &HotkeyConfig) -> bool {
val.modifiers.len() == 2
&& val.modifiers[0] == "Control"
&& val.modifiers[1] == "Option"
&& val.key == "Z"
}
fn is_default_audio(val: &AudioConfig) -> bool {
val.buffer_size == AudioConfig::default().buffer_size
&& val.sample_rate == AudioConfig::default().sample_rate
}
fn is_default_model(val: &ModelConfig) -> bool {
val.model_type == ModelType::Small
&& val.preload
&& val.threads == 4
&& val.beam_size == 1
&& val.language.as_deref() == Some("en")
}
fn is_default_telemetry(val: &TelemetryConfig) -> bool {
val.enabled && val.log_path == "~/.whisper-hotkey/crash.log"
}
fn is_default_recording(val: &RecordingConfig) -> bool {
let default = RecordingConfig::default();
val.enabled == default.enabled
&& val.retention_days == default.retention_days
&& val.max_count == default.max_count
&& val.cleanup_interval_hours == default.cleanup_interval_hours
}
#[allow(clippy::float_cmp)]
fn is_default_aliases(val: &AliasesConfig) -> bool {
val.enabled && val.threshold == 0.8 && val.entries.is_empty()
}
fn is_default_profiles(val: &[TranscriptionProfile]) -> bool {
if val.len() != 1 {
return false;
}
let profile = &val[0];
profile.name.is_none()
&& matches!(
&profile.backend,
BackendConfig::Local {
model_type: ModelType::BaseEn,
threads: 4,
beam_size: 1,
language: Some(lang)
} if lang == "en"
)
&& is_default_hotkey(&profile.hotkey)
&& profile.preload
}
/// Transcription profile combining hotkey and backend configuration
#[derive(Debug, Clone, Serialize)]
pub struct TranscriptionProfile {
/// Optional explicit profile name (auto-generated if multiple profiles share same backend)
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Backend configuration (flattened into profile)
#[serde(flatten)]
pub backend: BackendConfig,
/// Hotkey configuration (inlined)
#[serde(flatten)]
pub hotkey: HotkeyConfig,
/// Preload backend at startup (Local: model loading, Deepgram: client initialization)
#[serde(default = "default_preload")]
pub preload: bool,
}
// Helper struct for deserializing old format (pre-backend enum)
#[derive(Deserialize)]
struct TranscriptionProfileHelper {
#[serde(default)]
name: Option<String>,
#[serde(default)]
backend: Option<String>,
// Old format fields (Local backend)
#[serde(default)]
model_type: Option<ModelType>,
#[serde(default = "default_threads")]
threads: usize,
#[serde(default = "default_beam_size")]
beam_size: usize,
#[serde(default = "default_language")]
language: Option<String>,
// New format fields (Deepgram backend)
#[serde(default)]
model: Option<String>,
#[serde(default = "default_smart_format")]
smart_format: bool,
// Common fields
#[serde(flatten)]
hotkey: HotkeyConfig,
#[serde(default = "default_preload")]
preload: bool,
}
impl<'de> Deserialize<'de> for TranscriptionProfile {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let helper = TranscriptionProfileHelper::deserialize(deserializer)?;
// Determine backend from fields
let backend = if let Some(backend_str) = &helper.backend {
// New format with explicit backend tag
match backend_str.as_str() {
"local" => BackendConfig::Local {
model_type: helper.model_type.unwrap_or_default(),
threads: helper.threads,
beam_size: helper.beam_size,
language: helper.language,
},
"deepgram" => BackendConfig::Deepgram {
model: helper.model.unwrap_or_else(|| "whisper-large".to_owned()),
language: helper.language,
smart_format: helper.smart_format,
},
_ => {
return Err(serde::de::Error::custom(format!(
"unknown backend type: {backend_str}"
)))
}
}
} else if let Some(model_type) = helper.model_type {
// Old format without backend tag - migrate to Local
BackendConfig::Local {
model_type,
threads: helper.threads,
beam_size: helper.beam_size,
language: helper.language,
}
} else {
// No backend and no model_type - use default
BackendConfig::Local {
model_type: ModelType::default(),
threads: helper.threads,
beam_size: helper.beam_size,
language: helper.language,
}
};
Ok(Self {
name: helper.name,
backend,
hotkey: helper.hotkey,
preload: helper.preload,
})
}
}
impl TranscriptionProfile {
/// Get profile name (explicit name or derived from backend)
#[must_use]
pub fn name(&self) -> &str {
self.name.as_ref().map_or_else(
|| match &self.backend {
BackendConfig::Local { model_type, .. } => model_type.as_str(),
BackendConfig::Deepgram { model, .. } => model.as_str(),
},
|name| name.as_str(),
)
}
/// Get model path for this profile (Local backend only)
#[must_use]
pub fn model_path(&self) -> Option<String> {
match &self.backend {
BackendConfig::Local { model_type, .. } => Some(model_type.model_path()),
BackendConfig::Deepgram { .. } => None,
}
}
/// Get model type (Local backend only)
#[must_use]
pub const fn model_type(&self) -> Option<ModelType> {
match &self.backend {
BackendConfig::Local { model_type, .. } => Some(*model_type),
BackendConfig::Deepgram { .. } => None,
}
}
}
/// Application configuration
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Config {
/// Deepgram API configuration (required if any profile uses Deepgram backend)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deepgram: Option<DeepgramConfig>,
/// Transcription profiles (each with hotkey + model config)
#[serde(
default = "default_profiles",
skip_serializing_if = "is_default_profiles"
)]
pub profiles: Vec<TranscriptionProfile>,
/// Hotkey configuration
#[serde(default, skip_serializing_if = "is_default_hotkey")]
#[allow(dead_code)] // Used in Phase 2+
pub hotkey: HotkeyConfig,
/// Audio capture configuration
#[serde(default, skip_serializing_if = "is_default_audio")]
#[allow(dead_code)] // Used in Phase 3+
pub audio: AudioConfig,
/// Whisper model configuration
#[serde(default, skip_serializing_if = "is_default_model")]
#[allow(dead_code)] // Used in Phase 4+
pub model: ModelConfig,
/// Telemetry configuration
#[serde(default, skip_serializing_if = "is_default_telemetry")]
pub telemetry: TelemetryConfig,
/// Recording configuration
#[serde(default, skip_serializing_if = "is_default_recording")]
pub recording: RecordingConfig,
/// Aliases configuration
#[serde(default, skip_serializing_if = "is_default_aliases")]
pub aliases: AliasesConfig,
}
/// Hotkey configuration
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct HotkeyConfig {
/// Modifier keys (e.g., `["Command", "Shift"]`)
#[allow(dead_code)] // Used in Phase 2
pub modifiers: Vec<String>,
/// Main key (e.g., "V")
#[allow(dead_code)] // Used in Phase 2
pub key: String,
}
impl Default for HotkeyConfig {
fn default() -> Self {
Self {
modifiers: vec!["Control".to_owned(), "Option".to_owned()],
key: "Z".to_owned(),
}
}
}
/// Audio capture configuration
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct AudioConfig {
/// Ring buffer size in samples
#[allow(dead_code)] // Used in Phase 3
pub buffer_size: usize,
/// Sample rate in Hz
#[allow(dead_code)] // Used in Phase 3
pub sample_rate: u32,
}
impl Default for AudioConfig {
fn default() -> Self {
Self {
buffer_size: 1024,
sample_rate: 16000,
}
}
}
/// Whisper model configuration
#[derive(Debug, Clone)]
pub struct ModelConfig {
/// Model type (e.g., "base.en", "small", "tiny")
pub model_type: ModelType,
/// Preload model at startup
pub preload: bool,
/// Number of CPU threads for inference
pub threads: usize,
/// Beam search width (higher = slower but more accurate)
pub beam_size: usize,
/// Language code (None = auto-detect)
pub language: Option<String>,
}
// Helper struct for deserializing old config format
#[derive(Deserialize)]
struct ModelConfigHelper {
#[serde(default)]
model_type: Option<ModelType>,
#[serde(default)]
name: Option<String>,
#[serde(default)]
#[allow(dead_code)] // Needed for deserialization but not used (path is ignored)
path: Option<String>,
#[serde(default = "default_preload")]
preload: bool,
#[serde(default = "default_threads")]
threads: usize,
#[serde(default = "default_beam_size")]
beam_size: usize,
#[serde(default = "default_language")]
language: Option<String>,
}
const fn default_preload() -> bool {
true
}
const fn default_threads() -> usize {
4 // Optimal for M1/M2 chips
}
const fn default_beam_size() -> usize {
1 // Greedy decoding (fast)
}
#[allow(clippy::unnecessary_wraps)]
fn default_language() -> Option<String> {
Some("en".to_owned()) // English by default (skips auto-detect overhead)
}
fn default_profiles() -> Vec<TranscriptionProfile> {
vec![TranscriptionProfile {
name: None,
backend: BackendConfig::Local {
model_type: ModelType::BaseEn,
threads: default_threads(),
beam_size: default_beam_size(),
language: default_language(),
},
hotkey: HotkeyConfig::default(),
preload: default_preload(),
}]
}
impl<'de> Deserialize<'de> for ModelConfig {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let helper = ModelConfigHelper::deserialize(deserializer)?;
// Migrate from old format if model_type is not set
let model_type = if let Some(mt) = helper.model_type {
mt
} else if let Some(name) = helper.name {
// Try to parse name into ModelType
ModelType::from_str(&name).unwrap_or_default()
} else {
ModelType::default()
};
Ok(Self {
model_type,
preload: helper.preload,
threads: helper.threads,
beam_size: helper.beam_size,
language: helper.language,
})
}
}
impl Serialize for ModelConfig {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeStruct;
let mut state = serializer.serialize_struct("ModelConfig", 5)?;
state.serialize_field("model_type", &self.model_type)?;
state.serialize_field("preload", &self.preload)?;
state.serialize_field("threads", &self.threads)?;
state.serialize_field("beam_size", &self.beam_size)?;
state.serialize_field("language", &self.language)?;
state.end()
}
}
impl Default for ModelConfig {
fn default() -> Self {
Self {
model_type: ModelType::default(),
preload: default_preload(),
threads: default_threads(),
beam_size: default_beam_size(),
language: default_language(),
}
}
}
/// Telemetry and crash logging configuration
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct TelemetryConfig {
/// Enable crash logging
pub enabled: bool,
/// Path to log file
pub log_path: String,
}
impl Default for TelemetryConfig {
fn default() -> Self {
Self {
enabled: true,
log_path: "~/.whisper-hotkey/crash.log".to_owned(),
}
}
}
/// Recording configuration
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct RecordingConfig {
/// Enable debug recordings
#[serde(default = "default_recording_enabled")]
pub enabled: bool,
/// Delete recordings older than N days (0 = keep all)
#[serde(default = "default_retention_days")]
pub retention_days: u32,
/// Keep only N most recent recordings (0 = unlimited)
#[serde(default = "default_max_count")]
pub max_count: usize,
/// Hours between cleanup runs (0 = startup only)
#[serde(default = "default_cleanup_interval_hours")]
pub cleanup_interval_hours: u32,
}
const fn default_recording_enabled() -> bool {
true
}
const fn default_retention_days() -> u32 {
7
}
const fn default_max_count() -> usize {
100
}
const fn default_cleanup_interval_hours() -> u32 {
1
}
impl Default for RecordingConfig {
fn default() -> Self {
Self {
enabled: default_recording_enabled(),
retention_days: default_retention_days(),
max_count: default_max_count(),
cleanup_interval_hours: default_cleanup_interval_hours(),
}
}
}
/// Aliases configuration
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct AliasesConfig {
/// Enable alias matching
#[serde(default = "default_aliases_enabled")]
pub enabled: bool,
/// Minimum similarity threshold (0.0-1.0)
#[serde(default = "default_aliases_threshold")]
pub threshold: f64,
/// Alias mappings (trigger phrase -> output text)
#[serde(default)]
pub entries: HashMap<String, String>,
}
const fn default_aliases_enabled() -> bool {
true
}
const fn default_aliases_threshold() -> f64 {
0.8
}
impl Default for AliasesConfig {
fn default() -> Self {
Self {
enabled: default_aliases_enabled(),
threshold: default_aliases_threshold(),
entries: HashMap::new(),
}
}
}
impl Default for Config {
fn default() -> Self {
Self {
deepgram: None,
profiles: default_profiles(),
hotkey: HotkeyConfig::default(),
audio: AudioConfig::default(),
model: ModelConfig::default(),
telemetry: TelemetryConfig::default(),
recording: RecordingConfig::default(),
aliases: AliasesConfig::default(),
}
}
}
impl Config {
/// Load config from ~/.whisper-hotkey/config.toml
///
/// Automatically migrates from old path (~/.whisper-hotkey.toml) if found.
/// Creates default config if none exists.
///
/// # Errors
/// Returns error if config is invalid TOML or path expansion fails
pub fn load() -> Result<Self> {
let config_path = Self::config_path()?;
// Migrate from old path if needed
if !config_path.exists() {
let old_path = Self::old_config_path()?;
if old_path.exists() {
// Ensure new directory exists before migration
if let Some(parent) = config_path.parent() {
fs::create_dir_all(parent).context("failed to create config directory")?;
}
fs::copy(&old_path, &config_path)
.context("failed to migrate config from old location")?;
fs::remove_file(&old_path)
.context("failed to remove old config file after migration")?;
tracing::info!(
"migrated config from {} to {} and removed old config file",
old_path.display(),
config_path.display()
);
}
}
if !config_path.exists() {
Self::create_default(&config_path).context("failed to create default config")?;
}
let mut contents =
fs::read_to_string(&config_path).context("failed to read config file")?;
// Migrate to sparse format if config has content (create backup first)
// Skip if backup already exists (already migrated) or file is empty
let backup_path = config_path.with_extension("toml.bak");
if !contents.trim().is_empty() && !backup_path.exists() {
Self::migrate_to_sparse(&config_path)
.context("failed to migrate config to sparse format")?;
// Re-read contents after migration
contents = fs::read_to_string(&config_path).context("failed to read config file")?;
}
let mut config: Self = toml::from_str(&contents).context("failed to parse config TOML")?;
// Migrate from old [hotkey]/[model] format to [[profiles]]
// Check if profiles is empty/default AND old sections exist (non-default values)
let needs_migration = (config.profiles.is_empty() || is_default_profiles(&config.profiles))
&& (!is_default_hotkey(&config.hotkey) || !is_default_model(&config.model));
if needs_migration {
tracing::info!("migrating config from old [hotkey]/[model] format to [[profiles]]");
config.migrate_to_profiles();
config.save().context("failed to save migrated config")?;
}
// Check if [model] section had old fields (name/path) and save migrated version
let had_old_fields = contents
.split("[model]")
.nth(1)
.and_then(|model_section| model_section.split('[').next())
.is_some_and(|model_only| {
model_only.contains("name =") || model_only.contains("path =")
});
if had_old_fields {
tracing::info!("migrating config: removing deprecated 'name' and 'path' fields");
config.save().context("failed to save migrated config")?;
}
// Ensure unique profile names (auto-generate for duplicates)
config.ensure_unique_names();
// Ensure at least one profile exists
if config.profiles.is_empty() {
anyhow::bail!(
"config must contain at least one profile - add a [[profiles]] section to {}",
Self::config_path()?.display()
);
}
// Validate hotkey conflicts
config.validate_hotkeys()?;
// Validate Deepgram configuration
config.validate_deepgram()?;
Ok(config)
}
fn config_path() -> Result<PathBuf> {
let home = std::env::var("HOME").context("HOME environment variable not set")?;
Ok(PathBuf::from(home).join(".whisper-hotkey/config.toml"))
}
fn old_config_path() -> Result<PathBuf> {
let home = std::env::var("HOME").context("HOME environment variable not set")?;
Ok(PathBuf::from(home).join(".whisper-hotkey.toml"))
}
fn create_default(path: &PathBuf) -> Result<()> {
// Ensure parent directory exists
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).context("failed to create config directory")?;
}
// Create empty config file - all defaults come from code
fs::write(path, "").context("failed to write default config")?;
Ok(())
}
/// Save config to ~/.whisper-hotkey/config.toml
///
/// # Errors
/// Returns error if TOML serialization fails or file write fails
pub fn save(&self) -> Result<()> {
let config_path = Self::config_path()?;
// Ensure parent directory exists
if let Some(parent) = config_path.parent() {
fs::create_dir_all(parent).context("failed to create config directory")?;
}
let contents =
toml::to_string_pretty(self).context("failed to serialize config to TOML")?;
fs::write(&config_path, contents).context("failed to write config file")?;
Ok(())
}
/// Migrate existing config to sparse format (removes default values)
/// Creates backup as config.toml.bak before migration
///
/// # Errors
/// Returns error if backup creation or save fails
fn migrate_to_sparse(config_path: &PathBuf) -> Result<()> {
// Read current config contents
let contents = fs::read_to_string(config_path).context("failed to read config file")?;
// Skip if already empty (already sparse)
if contents.trim().is_empty() {
return Ok(());
}
// Create backup
let backup_path = config_path.with_extension("toml.bak");
fs::copy(config_path, &backup_path).context("failed to create config backup")?;
tracing::info!("created config backup at {}", backup_path.display());
// Load config (parses with defaults)
let config: Self = toml::from_str(&contents).context("failed to parse config TOML")?;
// Save (will skip default values due to skip_serializing_if)
let sparse_contents =
toml::to_string_pretty(&config).context("failed to serialize config to TOML")?;
fs::write(config_path, sparse_contents).context("failed to write migrated config")?;
tracing::info!("migrated config to sparse format");
Ok(())
}
/// Get config file path for external opening
///
/// # Errors
/// Returns error if HOME environment variable is not set
pub fn get_config_path() -> Result<PathBuf> {
Self::config_path()
}
/// Expand ~ in paths to home directory
///
/// # Errors
/// Returns error if HOME environment variable is not set
#[allow(dead_code)] // Used in Phase 3+
pub fn expand_path(path: &str) -> Result<PathBuf> {
if let Some(stripped) = path.strip_prefix("~/") {
let home = std::env::var("HOME").context("HOME environment variable not set")?;
Ok(PathBuf::from(home).join(stripped))
} else {
Ok(PathBuf::from(path))
}
}
/// Migrate from old [hotkey]/[model] format to [[profiles]]
/// Converts single hotkey + model config into a single profile
fn migrate_to_profiles(&mut self) {
// Only migrate if profiles is empty or using defaults
if !self.profiles.is_empty() && !is_default_profiles(&self.profiles) {
return;
}
// Create single profile from old hotkey + model
self.profiles = vec![TranscriptionProfile {
name: None,
backend: BackendConfig::Local {
model_type: self.model.model_type,
threads: self.model.threads,
beam_size: self.model.beam_size,
language: self.model.language.clone(),
},
hotkey: self.hotkey.clone(),
preload: self.model.preload,
}];
}
/// Ensure unique profile names by auto-generating suffixes for duplicates
fn ensure_unique_names(&mut self) {
use std::collections::HashMap;
// Count occurrences of each derived name
let mut name_counts: HashMap<String, usize> = HashMap::new();
for profile in &self.profiles {
let derived_name = match &profile.backend {
BackendConfig::Local { model_type, .. } => model_type.as_str().to_owned(),
BackendConfig::Deepgram { model, .. } => model.clone(),
};
*name_counts.entry(derived_name).or_insert(0) += 1;
}
// Auto-generate unique names for duplicates
let mut name_counters: HashMap<String, usize> = HashMap::new();
for profile in &mut self.profiles {
if profile.name.is_none() {
let derived_name = match &profile.backend {
BackendConfig::Local { model_type, .. } => model_type.as_str().to_owned(),
BackendConfig::Deepgram { model, .. } => model.clone(),
};
if *name_counts.get(&derived_name).unwrap_or(&0) > 1 {
// Multiple profiles with same backend name, generate unique name
let counter = name_counters.entry(derived_name.clone()).or_insert(0);
*counter += 1;
profile.name = Some(format!("{derived_name}-{counter}"));
}
}
}
}
/// Validate no duplicate hotkeys across profiles
///
/// # Errors
/// Returns error if duplicate hotkeys are found
fn validate_hotkeys(&self) -> Result<()> {
use std::collections::HashSet;
let mut seen = HashSet::new();
for profile in &self.profiles {
// Sort modifiers for consistent signature (order-independent)
let mut sorted_mods = profile.hotkey.modifiers.clone();
sorted_mods.sort();
let hotkey_sig = format!("{:?}+{}", sorted_mods, profile.hotkey.key);
if !seen.insert(hotkey_sig.clone()) {
anyhow::bail!(
"duplicate hotkey detected: {} (profiles: {})",
hotkey_sig,
self.profiles
.iter()
.filter(|p| {
let mut sorted_mods = p.hotkey.modifiers.clone();
sorted_mods.sort();
format!("{:?}+{}", sorted_mods, p.hotkey.key) == hotkey_sig
})
.map(TranscriptionProfile::name)
.collect::<Vec<_>>()
.join(", ")
);
}
}
Ok(())
}
/// Validate Deepgram configuration is present if any profile uses Deepgram backend
///
/// # Errors
/// Returns error if Deepgram profiles exist without API key configuration
fn validate_deepgram(&self) -> Result<()> {
let has_deepgram_profile = self
.profiles
.iter()
.any(|p| matches!(p.backend, BackendConfig::Deepgram { .. }));
if has_deepgram_profile && self.deepgram.is_none() {
anyhow::bail!(
"Deepgram backend requires [deepgram] section with api_key in config. \
Add:\n\n[deepgram]\napi_key = \"YOUR_API_KEY\"\n\n\
to {}",
Self::config_path()?.display()
);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::env;
use std::sync::Mutex;
// Shared mutex for all tests that modify HOME
static HOME_TEST_LOCK: Mutex<()> = Mutex::new(());
#[test]
fn test_expand_path_with_tilde() {
let home = env::var("HOME").expect("HOME not set");
let result = Config::expand_path("~/test/path").unwrap();
assert_eq!(result, PathBuf::from(home).join("test/path"));
}
#[test]
fn test_expand_path_without_tilde() {
let result = Config::expand_path("/absolute/path").unwrap();
assert_eq!(result, PathBuf::from("/absolute/path"));
}
#[test]
fn test_expand_path_relative() {
let result = Config::expand_path("relative/path").unwrap();
assert_eq!(result, PathBuf::from("relative/path"));
}
#[test]
fn test_parse_valid_config() {
let toml = r#"
[hotkey]
modifiers = ["Control", "Option"]
key = "Z"
[audio]
buffer_size = 1024
sample_rate = 16000
[model]
model_type = "small"
preload = true
threads = 4
beam_size = 5
[telemetry]
enabled = true
log_path = "~/.whisper-hotkey/crash.log"
"#;
let config: Config = toml::from_str(toml).unwrap();
assert_eq!(config.hotkey.modifiers, vec!["Control", "Option"]);
assert_eq!(config.hotkey.key, "Z");