codesynapse-core 0.1.2

Core graph extraction and analysis engine for codesynapse — AST parsing, semantic embeddings, BM25 index
Documentation
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
use crate::error::CodeSynapseError;
use sha2::{Digest, Sha256};
use std::collections::HashSet;
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::LazyLock;

pub static VIDEO_EXTENSIONS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
    [
        ".mp4", ".mov", ".webm", ".mkv", ".avi", ".m4v", ".mp3", ".wav", ".m4a", ".ogg",
    ]
    .into_iter()
    .collect()
});

static URL_PREFIXES: &[&str] = &["http://", "https://", "www."];
static DEFAULT_MODEL: &str = "base";
static TRANSCRIPTS_DIR: &str = "codesynapse-out/transcripts";
static FALLBACK_PROMPT: &str = "Use proper punctuation and paragraph breaks.";

fn model_name() -> String {
    env::var("CODESYNAPSE_WHISPER_MODEL").unwrap_or_else(|_| DEFAULT_MODEL.to_string())
}

pub fn is_url(path: &str) -> bool {
    URL_PREFIXES.iter().any(|p| path.starts_with(p))
}

fn url_hash(url: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(url.as_bytes());
    let result = hasher.finalize();
    format!("{:x}", result)[..12].to_string()
}

fn find_exe(name: &str) -> Option<PathBuf> {
    let path_var = env::var_os("PATH")?;
    for dir in env::split_paths(&path_var) {
        let candidate = dir.join(name);
        if candidate.is_file() {
            return Some(candidate);
        }
    }
    None
}

pub fn download_audio(url: &str, output_dir: &Path) -> Result<PathBuf, CodeSynapseError> {
    let hash = url_hash(url);

    for ext in [".m4a", ".opus", ".mp3", ".ogg", ".wav", ".webm"] {
        let candidate = output_dir.join(format!("yt_{}{}", hash, ext));
        if candidate.exists() {
            eprintln!(
                "  cached audio: {}",
                candidate.file_name().unwrap_or_default().to_string_lossy()
            );
            return Ok(candidate);
        }
    }

    std::fs::create_dir_all(output_dir).map_err(CodeSynapseError::Io)?;

    let exe = find_exe("yt-dlp").ok_or_else(|| {
        CodeSynapseError::Validation(
            "yt-dlp is required for URL download. Install: pip install yt-dlp".to_string(),
        )
    })?;

    let out_template = output_dir.join(format!("yt_{}.%(ext)s", hash));
    let out_template_str = out_template.to_string_lossy().to_string();
    let display_url = &url[..url.len().min(80)];
    eprintln!("  downloading audio: {} ...", display_url);

    let result = Command::new(&exe)
        .args([
            "-f",
            "bestaudio[ext=m4a]/bestaudio/best",
            "-o",
            &out_template_str,
            "--quiet",
            "--no-warnings",
            "--no-playlist",
            url,
        ])
        .output()
        .map_err(CodeSynapseError::Io)?;

    if !result.status.success() {
        let stderr = String::from_utf8_lossy(&result.stderr);
        let msg = &stderr[..stderr.len().min(800)];
        return Err(CodeSynapseError::Validation(format!(
            "yt-dlp failed: {}",
            msg
        )));
    }

    for ext in [".m4a", ".opus", ".mp3", ".ogg", ".wav", ".webm"] {
        let candidate = output_dir.join(format!("yt_{}{}", hash, ext));
        if candidate.exists() {
            return Ok(candidate);
        }
    }

    if let Ok(entries) = std::fs::read_dir(output_dir) {
        let prefix = format!("yt_{}", hash);
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().to_string();
            if name.starts_with(&prefix) {
                return Ok(entry.path());
            }
        }
    }

    Err(CodeSynapseError::Validation(format!(
        "yt-dlp ran but no output file found for {}",
        url
    )))
}

fn build_whisper_prompt_inner(
    god_nodes: &[serde_json::Value],
    env_override: Option<&str>,
) -> String {
    if god_nodes.is_empty() {
        return FALLBACK_PROMPT.to_string();
    }

    if let Some(ov) = env_override {
        return ov.to_string();
    }

    let labels: Vec<&str> = god_nodes
        .iter()
        .filter_map(|n| n.get("label").and_then(|v| v.as_str()))
        .filter(|s| !s.is_empty())
        .take(5)
        .collect();

    if labels.is_empty() {
        return FALLBACK_PROMPT.to_string();
    }

    let topics = labels.join(", ");
    format!(
        "Technical discussion about {}. Use proper punctuation and paragraph breaks.",
        topics
    )
}

pub fn build_whisper_prompt(god_nodes: &[serde_json::Value]) -> String {
    let env_override = env::var("CODESYNAPSE_WHISPER_PROMPT").ok();
    build_whisper_prompt_inner(god_nodes, env_override.as_deref())
}

fn run_whisper(
    audio_path: &Path,
    model: &str,
    initial_prompt: Option<&str>,
) -> Result<String, CodeSynapseError> {
    let exe = find_exe("faster-whisper")
        .or_else(|| find_exe("whisper"))
        .ok_or_else(|| {
            CodeSynapseError::Validation(
                "faster-whisper or whisper CLI required. \
                 Install: pip install faster-whisper"
                    .to_string(),
            )
        })?;

    let mut cmd = Command::new(&exe);
    cmd.arg(audio_path.to_string_lossy().as_ref());
    cmd.args(["--model", model]);
    if let Some(prompt) = initial_prompt {
        cmd.args(["--initial_prompt", prompt]);
    }
    cmd.args(["--output_format", "txt"]);
    let out_dir = audio_path.parent().unwrap_or(Path::new("."));
    cmd.arg("--output_dir").arg(out_dir);

    let result = cmd.output().map_err(CodeSynapseError::Io)?;
    if !result.status.success() {
        let stderr = String::from_utf8_lossy(&result.stderr);
        let msg = &stderr[..stderr.len().min(800)];
        return Err(CodeSynapseError::Validation(format!(
            "whisper failed: {}",
            msg
        )));
    }

    let txt_path = out_dir.join(format!(
        "{}.txt",
        audio_path.file_stem().unwrap_or_default().to_string_lossy()
    ));
    if txt_path.exists() {
        return std::fs::read_to_string(&txt_path).map_err(CodeSynapseError::Io);
    }

    Ok(String::from_utf8_lossy(&result.stdout).to_string())
}

pub fn transcribe_with(
    video_path: &Path,
    output_dir: Option<&Path>,
    initial_prompt: Option<&str>,
    force: bool,
    whisper_fn: impl Fn(&Path, &str, Option<&str>) -> Result<String, CodeSynapseError>,
) -> Result<PathBuf, CodeSynapseError> {
    let out_dir = output_dir
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| PathBuf::from(TRANSCRIPTS_DIR));
    std::fs::create_dir_all(&out_dir).map_err(CodeSynapseError::Io)?;

    let audio_path = if is_url(&video_path.to_string_lossy()) {
        download_audio(&video_path.to_string_lossy(), &out_dir.join("downloads"))?
    } else {
        video_path.to_path_buf()
    };

    let stem = audio_path.file_stem().unwrap_or_default().to_string_lossy();
    let transcript_path = out_dir.join(format!("{}.txt", stem));

    if transcript_path.exists() && !force {
        return Ok(transcript_path);
    }

    let model = model_name();
    let prompt = initial_prompt.unwrap_or(FALLBACK_PROMPT);
    eprintln!(
        "  transcribing {} (model={}) ...",
        audio_path.file_name().unwrap_or_default().to_string_lossy(),
        model
    );

    let text = whisper_fn(&audio_path, &model, Some(prompt))?;
    let lines: Vec<&str> = text
        .lines()
        .map(|l| l.trim())
        .filter(|l| !l.is_empty())
        .collect();
    let transcript = lines.join("\n");

    std::fs::write(&transcript_path, &transcript).map_err(CodeSynapseError::Io)?;
    eprintln!(
        "  transcript saved -> {} ({} segments)",
        transcript_path.display(),
        lines.len()
    );

    Ok(transcript_path)
}

pub fn transcribe(
    video_path: &Path,
    output_dir: Option<&Path>,
    initial_prompt: Option<&str>,
    force: bool,
) -> Result<PathBuf, CodeSynapseError> {
    transcribe_with(video_path, output_dir, initial_prompt, force, run_whisper)
}

pub fn transcribe_all(
    video_files: &[String],
    output_dir: Option<&Path>,
    initial_prompt: Option<&str>,
) -> Vec<String> {
    if video_files.is_empty() {
        return vec![];
    }

    video_files
        .iter()
        .filter_map(
            |vf| match transcribe(Path::new(vf), output_dir, initial_prompt, false) {
                Ok(p) => Some(p.to_string_lossy().to_string()),
                Err(e) => {
                    eprintln!("  warning: could not transcribe {}: {}", vf, e);
                    None
                }
            },
        )
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn tmp() -> TempDir {
        tempfile::tempdir().unwrap()
    }

    // VIDEO_EXTENSIONS

    #[test]
    fn test_video_extensions_set() {
        assert!(VIDEO_EXTENSIONS.contains(".mp4"));
        assert!(VIDEO_EXTENSIONS.contains(".mp3"));
        assert!(VIDEO_EXTENSIONS.contains(".wav"));
        assert!(VIDEO_EXTENSIONS.contains(".mov"));
        assert!(!VIDEO_EXTENSIONS.contains(".py"));
        assert!(!VIDEO_EXTENSIONS.contains(".rs"));
    }

    // build_whisper_prompt

    #[test]
    fn test_build_whisper_prompt_no_nodes() {
        let prompt = build_whisper_prompt(&[]);
        assert!(!prompt.is_empty());
        assert!(prompt.to_lowercase().contains("punctuation"));
    }

    #[test]
    fn test_build_whisper_prompt_env_override() {
        let nodes = vec![
            serde_json::json!({"label": "Python"}),
            serde_json::json!({"label": "FastAPI"}),
        ];
        let prompt = build_whisper_prompt_inner(&nodes, Some("Custom domain hint."));
        assert_eq!(prompt, "Custom domain hint.");
    }

    #[test]
    fn test_build_whisper_prompt_returns_topic_string() {
        let nodes = vec![
            serde_json::json!({"label": "neural networks"}),
            serde_json::json!({"label": "transformers"}),
            serde_json::json!({"label": "attention"}),
        ];
        let prompt = build_whisper_prompt_inner(&nodes, None);
        let lower = prompt.to_lowercase();
        assert!(lower.contains("neural networks") || lower.contains("transformers"));
        assert!(lower.contains("punctuation"));
    }

    #[test]
    fn test_build_whisper_prompt_nodes_without_labels() {
        let nodes = vec![
            serde_json::json!({"id": "1"}),
            serde_json::json!({"id": "2", "label": ""}),
        ];
        let prompt = build_whisper_prompt_inner(&nodes, None);
        assert!(!prompt.is_empty());
    }

    // transcribe (via transcribe_with with injectable fn)

    #[test]
    fn test_transcribe_uses_cache() {
        let dir = tmp();
        let video = dir.path().join("lecture.mp4");
        fs::write(&video, b"fake").unwrap();
        let out_dir = dir.path().join("transcripts");
        fs::create_dir_all(&out_dir).unwrap();
        let cached = out_dir.join("lecture.txt");
        fs::write(&cached, "Cached transcript content.").unwrap();

        let called = std::cell::Cell::new(false);
        let result = transcribe_with(&video, Some(&out_dir), None, false, |_, _, _| {
            called.set(true);
            Ok("should not be called".to_string())
        })
        .unwrap();

        assert_eq!(result, cached);
        assert!(!called.get(), "whisper should not run when cache hit");
    }

    #[test]
    fn test_transcribe_force_reruns() {
        let dir = tmp();
        let video = dir.path().join("talk.mp4");
        fs::write(&video, b"fake").unwrap();
        let out_dir = dir.path().join("transcripts");
        fs::create_dir_all(&out_dir).unwrap();
        fs::write(out_dir.join("talk.txt"), "Old transcript.").unwrap();

        let result = transcribe_with(&video, Some(&out_dir), None, true, |_, _, _| {
            Ok("New transcript segment.".to_string())
        })
        .unwrap();

        assert_eq!(
            fs::read_to_string(&result).unwrap(),
            "New transcript segment."
        );
    }

    #[test]
    fn test_transcribe_missing_faster_whisper() {
        let dir = tmp();
        let video = dir.path().join("clip.mp4");
        fs::write(&video, b"fake").unwrap();
        let out_dir = dir.path().join("out");

        let result = transcribe_with(&video, Some(&out_dir), None, false, |_, _, _| {
            Err(CodeSynapseError::Validation(
                "faster-whisper not installed".to_string(),
            ))
        });

        assert!(result.is_err());
    }

    // transcribe_all

    #[test]
    fn test_transcribe_all_empty() {
        let results = transcribe_all(&[], None, None);
        assert!(results.is_empty());
    }

    #[test]
    fn test_transcribe_all_uses_cache() {
        let dir = tmp();
        let video = dir.path().join("lecture.mp4");
        fs::write(&video, b"fake").unwrap();
        let out_dir = dir.path().join("transcripts");
        fs::create_dir_all(&out_dir).unwrap();
        let cached = out_dir.join("lecture.txt");
        fs::write(&cached, "Cached.").unwrap();

        let results = transcribe_all(&[video.to_string_lossy().to_string()], Some(&out_dir), None);
        assert_eq!(results.len(), 1);
        assert!(results[0].contains("lecture.txt"));
    }

    #[test]
    fn test_transcribe_all_skips_failed() {
        let dir = tmp();
        let video = dir.path().join("broken.mp4");
        fs::write(&video, b"fake").unwrap();
        let out_dir = dir.path().join("out");

        // No cache exists and transcribe will try real whisper (which won't be found in test env)
        // transcribe_all catches errors and returns empty
        let results = transcribe_all(&[video.to_string_lossy().to_string()], Some(&out_dir), None);
        assert!(results.is_empty());
    }
}