1use std::path::{Path, PathBuf};
4
5#[derive(Debug, Clone, Default, PartialEq, Eq)]
7pub struct SttProbe {
8 pub whisper_cli: Option<PathBuf>,
9 pub ffmpeg: Option<PathBuf>,
10 pub model_path: Option<PathBuf>,
11}
12
13impl SttProbe {
14 pub fn is_complete(&self) -> bool {
15 self.whisper_cli.is_some() && self.ffmpeg.is_some() && self.model_path.is_some()
16 }
17
18 pub fn resolve(
21 cli_override: Option<&str>,
22 model_override: Option<&str>,
23 ffmpeg_override: Option<&str>,
24 ) -> Self {
25 let auto = probe_stt_environment();
26 SttProbe {
27 whisper_cli: resolve_cli_path(cli_override, auto.whisper_cli),
28 ffmpeg: resolve_ffmpeg_path(ffmpeg_override, auto.ffmpeg),
29 model_path: resolve_model_path(model_override, auto.model_path),
30 }
31 }
32}
33
34pub fn probe_stt_environment() -> SttProbe {
35 SttProbe {
36 whisper_cli: discover_whisper_cli(),
37 ffmpeg: discover_ffmpeg(),
38 model_path: discover_whisper_model(),
39 }
40}
41
42pub fn discover_whisper_cli() -> Option<PathBuf> {
43 const CANDIDATES: &[&str] = &[
44 "/opt/homebrew/bin/whisper-cli",
45 "/usr/local/bin/whisper-cli",
46 ];
47 for candidate in CANDIDATES {
48 let path = PathBuf::from(candidate);
49 if is_executable(&path) {
50 return Some(path);
51 }
52 }
53 which_sync("whisper-cli")
54}
55
56pub fn discover_ffmpeg() -> Option<PathBuf> {
57 const CANDIDATES: &[&str] = &["/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg"];
58 for candidate in CANDIDATES {
59 let path = PathBuf::from(candidate);
60 if is_executable(&path) {
61 return Some(path);
62 }
63 }
64 which_sync("ffmpeg")
65}
66
67pub fn discover_whisper_model() -> Option<PathBuf> {
68 let home = dirs::home_dir()?;
69 let candidates = [
70 home.join("models/whisper/ggml-medium.en.bin"),
71 home.join("models/whisper/ggml-medium.bin"),
72 home.join("models/whisper/ggml-base.en.bin"),
73 home.join("models/whisper/ggml-small.en.bin"),
74 home.join("models/whisper/ggml-large-v3.bin"),
75 ];
76 candidates.into_iter().find(|p| p.is_file())
77}
78
79pub fn format_stt_probe_report(probe: &SttProbe) -> String {
81 let mut lines = vec!["Whisper STT probe:".to_string()];
82 lines.push(format!(
83 "- whisper-cli: {}",
84 probe
85 .whisper_cli
86 .as_ref()
87 .map(|p| p.display().to_string())
88 .unwrap_or_else(|| "not found".to_string())
89 ));
90 lines.push(format!(
91 "- ffmpeg: {}",
92 probe
93 .ffmpeg
94 .as_ref()
95 .map(|p| p.display().to_string())
96 .unwrap_or_else(|| "not found".to_string())
97 ));
98 lines.push(format!(
99 "- model: {}",
100 probe
101 .model_path
102 .as_ref()
103 .map(|p| p.display().to_string())
104 .unwrap_or_else(|| "not found".to_string())
105 ));
106 lines.join("\n")
107}
108
109pub fn stt_config_section(probe: &SttProbe, enabled: bool, language: &str) -> String {
111 if !enabled {
112 return "\n# Uncomment for Whisper voice-note transcription (fallback when native audio is unavailable):\n# [files]\n# enabled = true\n# [files.stt]\n# enabled = true\n# cli_path = \"/opt/homebrew/bin/whisper-cli\"\n# model_path = \"~/models/whisper/ggml-medium.en.bin\"\n# ffmpeg_path = \"ffmpeg\"\n# language = \"en\"\n".to_string();
113 }
114
115 let cli = path_for_toml(
116 probe.whisper_cli.as_deref(),
117 "/opt/homebrew/bin/whisper-cli",
118 );
119 let model = path_for_toml(
120 probe.model_path.as_deref(),
121 "~/models/whisper/ggml-medium.en.bin",
122 );
123 let ffmpeg = probe
124 .ffmpeg
125 .as_ref()
126 .map(|p| p.display().to_string())
127 .unwrap_or_else(|| "ffmpeg".to_string());
128
129 format!(
130 r#"
131[files]
132enabled = true
133
134[files.stt]
135enabled = true
136cli_path = "{cli}"
137model_path = "{model}"
138ffmpeg_path = "{ffmpeg}"
139language = "{language}"
140max_audio_mb = 25
141timeout_secs = 120
142"#
143 )
144}
145
146pub fn apply_stt_to_config_table(
147 doc: &mut toml::Table,
148 probe: &SttProbe,
149 enabled: bool,
150 language: &str,
151) -> anyhow::Result<()> {
152 let files = doc
153 .entry("files")
154 .or_insert_with(|| toml::Value::Table(toml::Table::new()));
155 let files_table = files
156 .as_table_mut()
157 .ok_or_else(|| anyhow::anyhow!("'files' is not a table"))?;
158
159 let cli = path_for_toml(
160 probe.whisper_cli.as_deref(),
161 "/opt/homebrew/bin/whisper-cli",
162 );
163 let model = path_for_toml(
164 probe.model_path.as_deref(),
165 "~/models/whisper/ggml-medium.en.bin",
166 );
167 let ffmpeg = probe
168 .ffmpeg
169 .as_ref()
170 .map(|p| p.display().to_string())
171 .unwrap_or_else(|| "ffmpeg".to_string());
172
173 let mut stt = toml::Table::new();
174 stt.insert("enabled".to_string(), toml::Value::Boolean(enabled));
175 stt.insert("cli_path".to_string(), toml::Value::String(cli));
176 stt.insert("model_path".to_string(), toml::Value::String(model));
177 stt.insert("ffmpeg_path".to_string(), toml::Value::String(ffmpeg));
178 stt.insert(
179 "language".to_string(),
180 toml::Value::String(language.to_string()),
181 );
182 stt.insert("max_audio_mb".to_string(), toml::Value::Integer(25));
183 stt.insert("timeout_secs".to_string(), toml::Value::Integer(120));
184
185 files_table.insert("stt".to_string(), toml::Value::Table(stt));
186 Ok(())
187}
188
189fn path_for_toml(found: Option<&Path>, fallback: &str) -> String {
190 found
191 .map(|p| p.display().to_string())
192 .unwrap_or_else(|| fallback.to_string())
193}
194
195fn resolve_cli_path(override_path: Option<&str>, auto: Option<PathBuf>) -> Option<PathBuf> {
196 match override_path.filter(|s| !s.is_empty()) {
197 Some(path) => {
198 let expanded = expand_tilde(path);
199 is_executable(&expanded).then_some(expanded)
200 }
201 None => auto,
202 }
203}
204
205fn resolve_model_path(override_path: Option<&str>, auto: Option<PathBuf>) -> Option<PathBuf> {
206 match override_path.filter(|s| !s.is_empty()) {
207 Some(path) => {
208 let expanded = expand_tilde(path);
209 (expanded.is_absolute() && expanded.is_file()).then_some(expanded)
210 }
211 None => auto,
212 }
213}
214
215fn resolve_ffmpeg_path(override_path: Option<&str>, auto: Option<PathBuf>) -> Option<PathBuf> {
216 match override_path.filter(|s| !s.is_empty()) {
217 Some(path) => {
218 let expanded = expand_tilde(path);
219 if is_executable(&expanded) {
220 Some(expanded)
221 } else {
222 which_sync(path)
223 }
224 }
225 None => auto,
226 }
227}
228
229fn expand_tilde(path: &str) -> PathBuf {
230 PathBuf::from(shellexpand::tilde(path).into_owned())
231}
232
233fn is_executable(path: &Path) -> bool {
236 path.is_absolute() && is_runnable(path)
237}
238
239fn which_sync(binary: &str) -> Option<PathBuf> {
243 let bare = !binary.is_empty()
244 && binary
245 .chars()
246 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
247 && binary != "."
248 && binary != "..";
249 if !bare {
250 return None;
251 }
252 let path = std::env::var_os("PATH")?;
253 std::env::split_paths(&path)
254 .filter(|dir| dir.is_absolute())
255 .flat_map(|dir| {
256 let plain = dir.join(binary);
257 #[cfg(windows)]
258 let candidates = vec![plain.clone(), plain.with_extension("exe")];
259 #[cfg(not(windows))]
260 let candidates = vec![plain];
261 candidates
262 })
263 .find(|candidate| is_runnable(candidate))
264}
265
266#[cfg(unix)]
267fn is_runnable(path: &Path) -> bool {
268 use std::os::unix::fs::PermissionsExt;
269 std::fs::metadata(path)
270 .is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
271}
272
273#[cfg(not(unix))]
274fn is_runnable(path: &Path) -> bool {
275 path.is_file()
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281
282 #[test]
283 fn which_sync_never_runs_shell_syntax() {
284 let marker =
285 std::env::temp_dir().join(format!("aidaemon-stt-which-{}", std::process::id()));
286 let _ = std::fs::remove_file(&marker);
287 for name in [
288 format!("x; touch {}", marker.display()),
289 format!("$(touch {})", marker.display()),
290 "../ffmpeg".to_string(),
291 "/bin/sh".to_string(),
292 String::new(),
293 ] {
294 assert_eq!(which_sync(&name), None, "{name}");
295 }
296 assert!(!marker.exists(), "a configured name ran a command");
297 assert_eq!(
298 resolve_ffmpeg_path(Some("ffmpeg; touch /tmp/x"), None),
299 None
300 );
301 }
302
303 #[test]
304 fn stt_config_section_disabled_is_commented() {
305 let section = stt_config_section(&SttProbe::default(), false, "en");
306 assert!(section.contains("# [files.stt]"));
307 assert!(!section.contains("enabled = true\ncli_path"));
308 }
309
310 #[test]
311 fn stt_config_section_enabled_includes_paths() {
312 let probe = SttProbe {
313 whisper_cli: Some(PathBuf::from("/opt/homebrew/bin/whisper-cli")),
314 ffmpeg: Some(PathBuf::from("/opt/homebrew/bin/ffmpeg")),
315 model_path: Some(PathBuf::from("/Users/me/models/whisper/ggml-medium.en.bin")),
316 };
317 let section = stt_config_section(&probe, true, "en");
318 assert!(section.contains("[files.stt]"));
319 assert!(section.contains("enabled = true"));
320 assert!(section.contains("whisper-cli"));
321 assert!(section.contains("ggml-medium.en.bin"));
322 assert!(section.contains("language = \"en\""));
323 }
324
325 #[test]
326 fn apply_stt_to_config_table_merges_under_files() {
327 let mut doc: toml::Table = toml::Table::new();
328 let probe = SttProbe {
329 whisper_cli: Some(PathBuf::from("/bin/whisper-cli")),
330 ffmpeg: Some(PathBuf::from("/bin/ffmpeg")),
331 model_path: Some(PathBuf::from("/models/ggml-medium.en.bin")),
332 };
333 apply_stt_to_config_table(&mut doc, &probe, true, "en").unwrap();
334 let files = doc.get("files").and_then(toml::Value::as_table).unwrap();
335 let stt = files.get("stt").and_then(toml::Value::as_table).unwrap();
336 assert_eq!(
337 stt.get("enabled").and_then(toml::Value::as_bool),
338 Some(true)
339 );
340 assert_eq!(
341 stt.get("cli_path").and_then(toml::Value::as_str),
342 Some("/bin/whisper-cli")
343 );
344 }
345
346 #[test]
347 fn resolve_honors_overrides() {
348 let dir = tempfile::tempdir().unwrap();
349 let cli = dir.path().join("whisper-cli");
350 std::fs::write(&cli, b"").unwrap();
351 #[cfg(unix)]
352 {
353 use std::os::unix::fs::PermissionsExt;
354 std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap();
355 }
356 let model = dir.path().join("model.bin");
357 std::fs::write(&model, b"fake").unwrap();
358
359 let probe = SttProbe::resolve(
360 Some(cli.to_str().unwrap()),
361 Some(model.to_str().unwrap()),
362 None,
363 );
364 assert_eq!(probe.whisper_cli, Some(cli));
365 assert_eq!(probe.model_path, Some(model));
366 }
367}