← back to krav4enkodm__whisperx

Function bodies 57 total

All specs Real LLM only Function bodies
resolve_whisper_bin function · rust · L5-L21 (17 LOC)
src/binaries.rs
pub fn resolve_whisper_bin(config: &AppConfig) -> PathBuf {
    if config.whisper_bin.eq_ignore_ascii_case("auto") {
        if let Some(path) = bundled_whisper_cli_path() {
            return path;
        }
        return PathBuf::from("whisper-cli");
    }

    if config.whisper_bin == "whisper-cli"
        && let Some(path) = bundled_whisper_cli_path()
    {
        return path;
    }

    PathBuf::from(&config.whisper_bin)
}
bundled_whisper_cli_path function · rust · L22-L31 (10 LOC)
src/binaries.rs
pub fn bundled_whisper_cli_path() -> Option<PathBuf> {
    let current_exe = std::env::current_exe().ok()?;
    let parent = current_exe.parent()?;
    let candidate = parent.join("whisper-cli");
    if candidate.is_file() {
        return Some(candidate);
    }
    None
}
binary_available function · rust · L32-L39 (8 LOC)
src/binaries.rs
pub fn binary_available(path: &Path) -> bool {
    if path.components().count() > 1 || path.is_absolute() {
        path.is_file()
    } else {
        which::which(path).is_ok()
    }
}
apply_library_path_env function · rust · L40-L57 (18 LOC)
src/binaries.rs
pub fn apply_library_path_env(command: &mut Command, whisper_bin: &Path) {
    let Some(parent) = whisper_bin.parent() else {
        return;
    };
    if parent.as_os_str().is_empty() {
        return;
    }

    let mut value = parent.to_string_lossy().to_string();
    if let Ok(existing) = std::env::var("LD_LIBRARY_PATH")
        && !existing.is_empty()
    {
        value.push(':');
        value.push_str(&existing);
    }
    command.env("LD_LIBRARY_PATH", value);
}
as_str function · rust · L15-L20 (6 LOC)
src/config.rs
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Type => "type",
            Self::Clipboard => "clipboard",
        }
    }
default function · rust · L65-L82 (18 LOC)
src/config.rs
    fn default() -> Self {
        Self {
            default_model: "base.en".to_string(),
            model_dir: default_model_dir(),
            whisper_bin: "auto".to_string(),
            ffmpeg_bin: "ffmpeg".to_string(),
            xdotool_bin: "xdotool".to_string(),
            threads: 4,
            language: "en".to_string(),
            convert: true,
            mic_socket: default_mic_socket_path(),
            mic_source: "default".to_string(),
            mic_min_seconds: 0.2,
            mic_output: MicOutputMode::Type,
            clipboard_bin: "xclip".to_string(),
            timeout_secs: 3600,
        }
    }
apply_file_config function · rust · L86-L129 (44 LOC)
src/config.rs
    fn apply_file_config(&mut self, file: FileConfig) {
        if let Some(default_model) = file.default_model {
            self.default_model = default_model;
        }
        if let Some(model_dir) = file.model_dir {
            self.model_dir = model_dir;
        }
        if let Some(whisper_bin) = file.whisper_bin {
            self.whisper_bin = whisper_bin;
        }
        if let Some(ffmpeg_bin) = file.ffmpeg_bin {
            self.ffmpeg_bin = ffmpeg_bin;
        }
        if let Some(xdotool_bin) = file.xdotool_bin {
            self.xdotool_bin = xdotool_bin;
        }
        if let Some(threads) = file.threads {
            self.threads = threads;
        }
        if let Some(language) = file.language {
            self.language = language;
        }
        if let Some(convert) = file.convert {
            self.convert = convert;
        }
        if let Some(mic_socket) = file.mic_socket {
            self.mic_socket = mic_socket;
        }
        if let Some(mic_
Citation: Repobility (2026). State of AI-Generated Code. https://repobility.com/research/
load function · rust · L131-L148 (18 LOC)
src/config.rs
pub fn load(config_path_override: Option<&PathBuf>) -> Result<(AppConfig, PathBuf)> {
    let path = resolve_config_path(config_path_override)?;
    let mut config = AppConfig::default();

    if path.exists() {
        let raw = fs::read_to_string(&path)
            .with_context(|| format!("failed reading config at {}", path.display()))?;
        let file_cfg: FileConfig = toml::from_str(&raw)
            .with_context(|| format!("failed parsing TOML config at {}", path.display()))?;
        config.apply_file_config(file_cfg);
    }

    config.model_dir = expand_tilde(&config.model_dir);
    config.mic_socket = expand_tilde(&config.mic_socket);

    Ok((config, path))
}
init function · rust · L149-L171 (23 LOC)
src/config.rs
pub fn init(config_path_override: Option<&PathBuf>, force: bool) -> Result<PathBuf> {
    let path = resolve_config_path(config_path_override)?;

    if path.exists() && !force {
        bail!(
            "config already exists at {} (use --force to overwrite)",
            path.display()
        );
    }

    let default = AppConfig::default();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create config directory {}", parent.display()))?;
    }

    let serialized = toml::to_string_pretty(&default)?;
    fs::write(&path, serialized)
        .with_context(|| format!("failed writing config to {}", path.display()))?;

    Ok(path)
}
resolve_config_path function · rust · L172-L180 (9 LOC)
src/config.rs
pub fn resolve_config_path(config_path_override: Option<&PathBuf>) -> Result<PathBuf> {
    if let Some(path) = config_path_override {
        return Ok(expand_tilde(path));
    }

    let base = dirs::config_dir().context("unable to determine OS config directory")?;
    Ok(base.join("whisperx").join("config.toml"))
}
default_model_dir function · rust · L181-L187 (7 LOC)
src/config.rs
fn default_model_dir() -> PathBuf {
    dirs::cache_dir()
        .unwrap_or_else(|| PathBuf::from(".cache"))
        .join("whisperx")
        .join("models")
}
default_mic_socket_path function · rust · L188-L196 (9 LOC)
src/config.rs
fn default_mic_socket_path() -> PathBuf {
    if let Some(runtime) = dirs::runtime_dir() {
        return runtime.join("whisperx").join("mic.sock");
    }

    let user = std::env::var("USER").unwrap_or_else(|_| "user".to_string());
    PathBuf::from(format!("/tmp/whisperx-{user}/mic.sock"))
}
expand_tilde function · rust · L197-L211 (15 LOC)
src/config.rs
pub fn expand_tilde(path: &Path) -> PathBuf {
    let raw = path.to_string_lossy();
    if raw == "~" {
        return dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
    }

    if let Some(suffix) = raw.strip_prefix("~/") {
        if let Some(home) = dirs::home_dir() {
            return home.join(suffix);
        }
    }

    path.to_path_buf()
}
applies_file_overrides function · rust · L222-L259 (38 LOC)
src/config.rs
    fn applies_file_overrides() {
        let mut config = AppConfig::default();
        let file = FileConfig {
            default_model: Some("small.en".to_string()),
            model_dir: Some(PathBuf::from("~/models")),
            whisper_bin: Some("./bin/whisper-cli".to_string()),
            ffmpeg_bin: Some("/usr/bin/ffmpeg".to_string()),
            xdotool_bin: Some("/usr/bin/xdotool".to_string()),
            threads: Some(8),
            language: Some("auto".to_string()),
            convert: Some(false),
            _deprecated_mic_hotkey: None,
            mic_socket: Some(PathBuf::from("~/mic.sock")),
            mic_source: Some("alsa_input".to_string()),
            mic_min_seconds: Some(0.35),
            mic_output: Some(MicOutputMode::Clipboard),
            _deprecated_mic_copy_to_clipboard: None,
            clipboard_bin: Some("/usr/bin/xclip".to_string()),
            timeout_secs: Some(123),
        };

        config.apply_file_config(file);

        assert
accepts_deprecated_mic_copy_to_clipboard_field function · rust · L268-L277 (10 LOC)
src/config.rs
    fn accepts_deprecated_mic_copy_to_clipboard_field() {
        let mut config = AppConfig::default();
        let file = FileConfig {
            _deprecated_mic_copy_to_clipboard: Some(true),
            ..FileConfig::default()
        };

        config.apply_file_config(file);
        assert_eq!(config.mic_output, MicOutputMode::Type);
    }
All rows scored by the Repobility analyzer (https://repobility.com)
run function · rust · L10-L149 (140 LOC)
src/doctor.rs
pub fn run(config: &AppConfig) -> Result<()> {
    let mut failures = 0_u32;

    let ffmpeg_ok = which::which(&config.ffmpeg_bin).is_ok();
    print_check(
        ffmpeg_ok,
        "ffmpeg",
        &format!(
            "binary '{}'{}",
            config.ffmpeg_bin,
            if ffmpeg_ok {
                " found"
            } else {
                " not found in PATH"
            }
        ),
    );
    if !ffmpeg_ok {
        failures += 1;
    }

    let whisper_bin = binaries::resolve_whisper_bin(config);
    let whisper_found = binaries::binary_available(&whisper_bin);
    let whisper_runnable = if whisper_found {
        check_whisper_runnable(&whisper_bin)
    } else {
        false
    };
    let whisper_ok = whisper_found && whisper_runnable;
    let whisper_details = if !whisper_found {
        format!(
            "resolved to '{}' (not found). Set whisper_bin in config if needed",
            whisper_bin.display()
        )
    } else if !whisper_runnable {
     
check_whisper_runnable function · rust · L150-L164 (15 LOC)
src/doctor.rs
fn check_whisper_runnable(whisper_bin: &Path) -> bool {
    let mut command = Command::new(whisper_bin);
    command
        .arg("--help")
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    binaries::apply_library_path_env(&mut command, whisper_bin);

    command
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}
print_check function · rust · L165-L172 (8 LOC)
src/doctor.rs
fn print_check(ok: bool, name: &str, details: &str) {
    if ok {
        println!("[ok]   {name}: {details}");
    } else {
        println!("[fail] {name}: {details}");
    }
}
check_writable_dir function · rust · L177-L189 (13 LOC)
src/doctor.rs
fn check_writable_dir(path: &Path) -> Result<bool> {
    cache::ensure_dir(path)?;

    let probe_path = path.join(".whisperx-write-probe");
    match fs::write(&probe_path, b"ok") {
        Ok(_) => {
            let _ = fs::remove_file(&probe_path);
            Ok(true)
        }
        Err(_) => Ok(false),
    }
}
main function · rust · L13-L19 (7 LOC)
src/main.rs
fn main() {
    if let Err(err) = run() {
        eprintln!("error: {err:#}");
        std::process::exit(1);
    }
}
run function · rust · L20-L62 (43 LOC)
src/main.rs
fn run() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Transcribe(args) => {
            let (config, _) = config::load(cli.config.as_ref())?;
            transcribe::run(&config, &args)?;
        }
        Commands::Mic { command } => {
            let (config, _) = config::load(cli.config.as_ref())?;
            mic::run(&config, &command)?;
        }
        Commands::Models { command } => {
            let (config, _) = config::load(cli.config.as_ref())?;
            match command {
                ModelsCommand::List => models::list(&config)?,
                ModelsCommand::Install { name } => {
                    let path = models::ensure_model(&config, &name)?;
                    println!("Installed model '{name}' at {}", path.display());
                }
                ModelsCommand::Path => println!("{}", config.model_dir.display()),
            }
        }
        Commands::Config { command } => match command {
            ConfigC
as_str function · rust · L37-L45 (9 LOC)
src/mic.rs
    fn as_str(self) -> &'static str {
        match self {
            Self::Start => "start",
            Self::Stop => "stop",
            Self::Toggle => "toggle",
            Self::Status => "status",
            Self::Shutdown => "shutdown",
        }
    }
parse function · rust · L46-L56 (11 LOC)
src/mic.rs
    fn parse(value: &str) -> Option<Self> {
        match value {
            "start" => Some(Self::Start),
            "stop" => Some(Self::Stop),
            "toggle" => Some(Self::Toggle),
            "status" => Some(Self::Status),
            "shutdown" => Some(Self::Shutdown),
            _ => None,
        }
    }
Repobility · code-quality intelligence platform · https://repobility.com
run function · rust · L91-L101 (11 LOC)
src/mic.rs
pub fn run(config: &AppConfig, command: &MicCommand) -> Result<()> {
    match command {
        MicCommand::Daemon(args) => run_daemon(config, args),
        MicCommand::Start(args) => run_control(config, args, MicAction::Start),
        MicCommand::Stop(args) => run_control(config, args, MicAction::Stop),
        MicCommand::Toggle(args) => run_control(config, args, MicAction::Toggle),
        MicCommand::Status(args) => run_control(config, args, MicAction::Status),
        MicCommand::Shutdown(args) => run_control(config, args, MicAction::Shutdown),
    }
}
run_daemon function · rust · L102-L241 (140 LOC)
src/mic.rs
fn run_daemon(config: &AppConfig, args: &MicDaemonArgs) -> Result<()> {
    let socket_path = resolve_socket_path(config, args.socket.as_ref());
    let ffmpeg_bin = args
        .ffmpeg_bin
        .clone()
        .unwrap_or_else(|| config.ffmpeg_bin.clone());
    let xdotool_bin = args
        .xdotool_bin
        .clone()
        .unwrap_or_else(|| config.xdotool_bin.clone());
    let source = args
        .source
        .clone()
        .unwrap_or_else(|| config.mic_source.clone());
    let min_seconds = args.min_seconds.unwrap_or(config.mic_min_seconds);
    let mic_output = config.mic_output;

    if !binaries::binary_available(Path::new(&ffmpeg_bin)) {
        bail!("ffmpeg binary '{}' not found", ffmpeg_bin);
    }

    if !args.dry_run && matches!(mic_output, MicOutputMode::Type) {
        let display = std::env::var("DISPLAY").unwrap_or_default();
        if display.trim().is_empty() {
            bail!("DISPLAY is not set. mic typing mode requires an X11 session");
      
run_control function · rust · L242-L253 (12 LOC)
src/mic.rs
fn run_control(config: &AppConfig, args: &MicControlArgs, action: MicAction) -> Result<()> {
    let socket_path = resolve_socket_path(config, args.socket.as_ref());
    let response = send_action(&socket_path, action)?;
    println!("{response}");

    if response.starts_with("error:") {
        bail!("daemon returned error");
    }

    Ok(())
}
resolve_socket_path function · rust · L254-L259 (6 LOC)
src/mic.rs
fn resolve_socket_path(config: &AppConfig, socket_override: Option<&PathBuf>) -> PathBuf {
    socket_override
        .cloned()
        .unwrap_or_else(|| config.mic_socket.clone())
}
send_action function · rust · L260-L281 (22 LOC)
src/mic.rs
fn send_action(socket_path: &Path, action: MicAction) -> Result<String> {
    let mut stream = UnixStream::connect(socket_path).with_context(|| {
        format!(
            "failed connecting to mic daemon at {} (is `whisperx mic daemon` running?)",
            socket_path.to_string_lossy()
        )
    })?;

    stream
        .write_all(format!("{}\n", action.as_str()).as_bytes())
        .context("failed writing request to mic daemon")?;
    stream.flush().context("failed flushing request")?;

    let mut reader = BufReader::new(stream);
    let mut response = String::new();
    reader
        .read_line(&mut response)
        .context("failed reading mic daemon response")?;

    Ok(response.trim().to_string())
}
handle_client function · rust · L282-L317 (36 LOC)
src/mic.rs
fn handle_client(
    mut stream: UnixStream,
    state: &mut MicDaemonState,
    running: &AtomicBool,
) -> Result<()> {
    let mut line = String::new();
    {
        let mut reader = BufReader::new(&stream);
        reader
            .read_line(&mut line)
            .context("failed reading daemon request")?;
    }

    let request = line.trim();
    let action = MicAction::parse(request).ok_or_else(|| {
        anyhow::anyhow!(
            "unsupported daemon request '{}': use start|stop|toggle|status|shutdown",
            request
        )
    })?;

    let (response, should_shutdown) =
        process_action(state, action).unwrap_or_else(|err| (format!("error: {err:#}"), false));

    stream
        .write_all(format!("{response}\n").as_bytes())
        .context("failed writing daemon response")?;
    stream.flush().context("failed flushing daemon response")?;

    if should_shutdown {
        running.store(false, Ordering::SeqCst);
    }

    Ok(())
}
process_action function · rust · L318-L387 (70 LOC)
src/mic.rs
fn process_action(state: &mut MicDaemonState, action: MicAction) -> Result<(String, bool)> {
    match action {
        MicAction::Start => {
            if state.active.is_some() {
                return Ok(("ok: already recording".to_string(), false));
            }

            let active_window = if state.dry_run || !matches!(state.mic_output, MicOutputMode::Type)
            {
                None
            } else {
                capture_active_window(&state.xdotool_bin)
            };
            let recording = start_recording(&state.ffmpeg_bin, &state.source, active_window)
                .with_context(|| {
                    format!(
                        "failed starting microphone capture for source '{}'",
                        state.source
                    )
                })?;
            state.active = Some(recording);
            Ok(("ok: recording started".to_string(), false))
        }
        MicAction::Stop => {
            if let Some(recording) = sta
finalize_recording_cycle function · rust · L388-L436 (49 LOC)
src/mic.rs
fn finalize_recording_cycle(
    state: &mut MicDaemonState,
    recording: ActiveRecording,
) -> Result<String> {
    let completed = stop_recording(recording)?;

    if completed.duration_secs < state.min_seconds {
        return Ok(format!(
            "ok: ignored short capture ({:.2}s < {:.2}s)",
            completed.duration_secs, state.min_seconds
        ));
    }

    let transcript = transcribe::transcribe_path_to_text(
        &state.config,
        &completed.wav_path,
        state.model.clone(),
        state.threads,
        state.language.clone(),
        state.translate,
        state.passthrough.clone(),
    )?;

    let text = normalize_transcript_text(&transcript);
    if text.is_empty() {
        return Ok("ok: empty transcript".to_string());
    }

    if state.dry_run {
        println!("{text}");
    } else {
        match state.mic_output {
            MicOutputMode::Type => {
                if let Some(window_id) = completed.active_window.as_deref()
       
Want this analysis on your repo? https://repobility.com/scan/
ensure_whisper_runnable function · rust · L437-L459 (23 LOC)
src/mic.rs
fn ensure_whisper_runnable(whisper_bin: &Path) -> Result<()> {
    let mut command = Command::new(whisper_bin);
    command
        .arg("--help")
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    binaries::apply_library_path_env(&mut command, whisper_bin);

    let status = command
        .status()
        .with_context(|| format!("failed running {} --help", whisper_bin.display()))?;

    if !status.success() {
        bail!(
            "whisper-cli '{}' is not runnable (check bundled shared libraries)",
            whisper_bin.display()
        );
    }

    Ok(())
}
start_recording function · rust · L460-L502 (43 LOC)
src/mic.rs
fn start_recording(
    ffmpeg_bin: &str,
    source: &str,
    active_window: Option<String>,
) -> Result<ActiveRecording> {
    let temp_dir =
        tempfile::tempdir().context("failed to create temporary microphone directory")?;
    let wav_path = temp_dir.path().join("capture.wav");

    let mut command = Command::new(ffmpeg_bin);
    command
        .arg("-hide_banner")
        .arg("-loglevel")
        .arg("error")
        .arg("-y")
        .arg("-f")
        .arg("pulse")
        .arg("-i")
        .arg(source)
        .arg("-ar")
        .arg("16000")
        .arg("-ac")
        .arg("1")
        .arg("-c:a")
        .arg("pcm_s16le")
        .arg(&wav_path)
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::piped());

    let child = command.spawn().with_context(|| {
        format!("failed to launch ffmpeg microphone capture with source '{source}'")
    })?;

    Ok(ActiveRecording {
        child,
        temp_dir,
        wav_path,
   
stop_recording function · rust · L503-L545 (43 LOC)
src/mic.rs
fn stop_recording(mut recording: ActiveRecording) -> Result<CompletedRecording> {
    if let Some(mut stdin) = recording.child.stdin.take() {
        let _ = stdin.write_all(b"q\n");
        let _ = stdin.flush();
    }

    let status = match recording
        .child
        .wait_timeout(RELEASE_TIMEOUT)
        .context("failed waiting for ffmpeg capture process")?
    {
        Some(status) => status,
        None => {
            let _ = recording.child.kill();
            let _ = recording.child.wait();
            bail!("ffmpeg capture did not stop in time");
        }
    };

    let mut stderr_bytes = Vec::new();
    if let Some(mut stderr) = recording.child.stderr.take() {
        stderr
            .read_to_end(&mut stderr_bytes)
            .context("failed reading ffmpeg stderr")?;
    }

    if !status.success() {
        let stderr = String::from_utf8_lossy(&stderr_bytes).trim().to_string();
        bail!("ffmpeg capture failed: {stderr}");
    }

    if !recording.wav_
capture_active_window function · rust · L546-L566 (21 LOC)
src/mic.rs
fn capture_active_window(xdotool_bin: &str) -> Option<String> {
    let output = Command::new(xdotool_bin)
        .arg("getactivewindow")
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    let window = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if window.is_empty() {
        return None;
    }

    Some(window)
}
restore_window_focus function · rust · L567-L584 (18 LOC)
src/mic.rs
fn restore_window_focus(xdotool_bin: &str, window_id: &str) -> Result<()> {
    let status = Command::new(xdotool_bin)
        .arg("windowactivate")
        .arg(window_id)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .status()
        .with_context(|| format!("failed running '{}'", xdotool_bin))?;

    if !status.success() {
        bail!("xdotool failed to activate window {window_id}");
    }

    thread::sleep(WINDOW_RESTORE_DELAY);
    Ok(())
}
copy_to_clipboard function · rust · L585-L606 (22 LOC)
src/mic.rs
fn copy_to_clipboard(clipboard_bin: &str, text: &str) -> Result<()> {
    let mut child = Command::new(clipboard_bin)
        .arg("-selection")
        .arg("clipboard")
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .with_context(|| format!("failed starting '{}'", clipboard_bin))?;

    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(text.as_bytes())
            .with_context(|| format!("failed writing to '{}'", clipboard_bin))?;
    }
    std::thread::spawn(move || {
        let _ = child.wait();
    });

    Ok(())
}
inject_text function · rust · L611-L633 (23 LOC)
src/mic.rs
fn inject_text(xdotool_bin: &str, text: &str) -> Result<()> {
    for chunk in split_typing_chunks(text, TYPING_CHUNK_SIZE) {
        let status = Command::new(xdotool_bin)
            .arg("type")
            .arg("--clearmodifiers")
            .arg("--delay")
            .arg("1")
            .arg("--")
            .arg(chunk)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .status()
            .with_context(|| format!("failed running '{}'", xdotool_bin))?;

        if !status.success() {
            bail!("xdotool failed while typing transcript");
        }
    }

    Ok(())
}
split_typing_chunks function · rust · L634-L658 (25 LOC)
src/mic.rs
fn split_typing_chunks(text: &str, max_chars: usize) -> Vec<&str> {
    if text.chars().count() <= max_chars {
        return vec![text];
    }

    let mut chunks = Vec::new();
    let mut start = 0;
    let mut char_count = 0;

    for (idx, _) in text.char_indices() {
        if char_count >= max_chars {
            chunks.push(&text[start..idx]);
            start = idx;
            char_count = 0;
        }
        char_count += 1;
    }

    if start < text.len() {
        chunks.push(&text[start..]);
    }

    chunks
}
Citation: Repobility (2026). State of AI-Generated Code. https://repobility.com/research/
parses_supported_actions function · rust · L665-L681 (17 LOC)
src/mic.rs
    fn parses_supported_actions() {
        assert!(matches!(MicAction::parse("start"), Some(MicAction::Start)));
        assert!(matches!(MicAction::parse("stop"), Some(MicAction::Stop)));
        assert!(matches!(
            MicAction::parse("toggle"),
            Some(MicAction::Toggle)
        ));
        assert!(matches!(
            MicAction::parse("status"),
            Some(MicAction::Status)
        ));
        assert!(matches!(
            MicAction::parse("shutdown"),
            Some(MicAction::Shutdown)
        ));
        assert!(MicAction::parse("invalid").is_none());
    }
list function · rust · L23-L42 (20 LOC)
src/models.rs
pub fn list(config: &AppConfig) -> Result<()> {
    let registry = load_registry()?;

    println!(
        "{:<20} {:<10} {:<40} Description",
        "Model", "Installed", "File"
    );
    for model in registry {
        let path = model_path(config, &model);
        let installed = if path.exists() { "yes" } else { "no" };
        let description = model.description.unwrap_or_default();
        println!(
            "{:<20} {:<10} {:<40} {}",
            model.name, installed, model.file, description
        );
    }

    Ok(())
}
ensure_model function · rust · L43-L76 (34 LOC)
src/models.rs
pub fn ensure_model(config: &AppConfig, name: &str) -> Result<PathBuf> {
    let registry = load_registry()?;
    let model = registry
        .iter()
        .find(|m| m.name == name)
        .ok_or_else(|| anyhow::anyhow!("unknown model '{name}'"))?
        .clone();

    cache::ensure_dir(&config.model_dir)?;
    let destination = model_path(config, &model);

    if destination.exists() {
        if let Some(expected) = model.sha256.as_deref() {
            let actual = sha256_file(&destination)?;
            if !hashes_match(&actual, expected) {
                eprintln!(
                    "warning: checksum mismatch for existing model '{}', re-downloading",
                    destination.display()
                );
                fs::remove_file(&destination).with_context(|| {
                    format!("failed to remove stale model at {}", destination.display())
                })?;
            } else {
                return Ok(destination);
            }
        } else {
load_registry function · rust · L77-L87 (11 LOC)
src/models.rs
fn load_registry() -> Result<Vec<ModelRecord>> {
    let models: Vec<ModelRecord> = serde_json::from_str(include_str!("../assets/models.json"))
        .context("failed to parse assets/models.json")?;

    if models.is_empty() {
        bail!("model registry is empty");
    }

    Ok(models)
}
download_model function · rust · L92-L167 (76 LOC)
src/models.rs
fn download_model(model: &ModelRecord, destination: &Path) -> Result<()> {
    let client = Client::new();
    let mut response = client
        .get(&model.url)
        .send()
        .with_context(|| format!("failed downloading model from {}", model.url))?;

    if !response.status().is_success() {
        bail!(
            "model download failed with status {} from {}",
            response.status(),
            model.url
        );
    }

    let total_size = response.content_length().or(model.size).unwrap_or(0);

    let progress = if total_size > 0 {
        let pb = ProgressBar::new(total_size);
        pb.set_style(
            ProgressStyle::with_template("{bar:40.cyan/blue} {bytes}/{total_bytes} {msg}")
                .unwrap_or_else(|_| ProgressStyle::default_bar()),
        );
        pb.set_message(format!("downloading {}", model.name));
        pb
    } else {
        ProgressBar::hidden()
    };

    let temp_path = destination.with_extension("download");
    let mut
sha256_file function · rust · L172-L190 (19 LOC)
src/models.rs
fn sha256_file(path: &Path) -> Result<String> {
    let mut file = File::open(path)
        .with_context(|| format!("failed opening model file for checksum: {}", path.display()))?;

    let mut hasher = Sha256::new();
    let mut buffer = [0_u8; 8192];
    loop {
        let bytes_read = file
            .read(&mut buffer)
            .with_context(|| format!("failed reading {}", path.display()))?;
        if bytes_read == 0 {
            break;
        }
        hasher.update(&buffer[..bytes_read]);
    }

    Ok(hex::encode(hasher.finalize()))
}
parses_valid_model_record_json function · rust · L206-L223 (18 LOC)
src/models.rs
    fn parses_valid_model_record_json() {
        let record: ModelRecord = serde_json::from_str(
            r#"{
                "name": "base.en",
                "file": "ggml-base.en.bin",
                "url": "https://example.test/model.bin",
                "sha256": "abc123",
                "size": 42,
                "description": "Test"
            }"#,
        )
        .expect("record should parse");

        assert_eq!(record.name, "base.en");
        assert_eq!(record.file, "ggml-base.en.bin");
        assert_eq!(record.sha256.as_deref(), Some("abc123"));
        assert_eq!(record.size, Some(42));
    }
from function · rust · L29-L41 (13 LOC)
src/transcribe.rs
    fn from(args: &TranscribeArgs) -> Self {
        Self {
            input: args.input.clone(),
            model: args.model.clone(),
            output: args.output,
            no_convert: args.no_convert,
            no_timestamps: false,
            threads: args.threads,
            language: args.language.clone(),
            translate: args.translate,
            passthrough: args.passthrough.clone(),
        }
    }
All rows scored by the Repobility analyzer (https://repobility.com)
run function · rust · L43-L49 (7 LOC)
src/transcribe.rs
pub fn run(config: &AppConfig, args: &TranscribeArgs) -> Result<()> {
    let request = TranscribeRequest::from(args);
    let content = run_request(config, &request)?;
    print_output(request.output, &content);
    Ok(())
}
run_request function · rust · L50-L114 (65 LOC)
src/transcribe.rs
pub fn run_request(config: &AppConfig, request: &TranscribeRequest) -> Result<String> {
    if !request.input.exists() {
        bail!("input file does not exist: {}", request.input.display());
    }

    let model_name = request
        .model
        .clone()
        .unwrap_or_else(|| config.default_model.clone());
    let model_path = models::ensure_model(config, &model_name)?;

    let timeout = Duration::from_secs(config.timeout_secs);
    let (prepared_input, _temp_wav) = prepare_input(config, request, timeout)?;

    let output_dir = tempfile::tempdir().context("failed to create temporary output directory")?;
    let output_base = output_dir.path().join("whisperx-output");

    let whisper_bin = binaries::resolve_whisper_bin(config);
    let mut command = Command::new(&whisper_bin);
    command
        .arg("-m")
        .arg(&model_path)
        .arg("-f")
        .arg(&prepared_input)
        .arg("-of")
        .arg(&output_base)
        .stdin(Stdio::null())
        .stdou
transcribe_path_to_text function · rust · L115-L138 (24 LOC)
src/transcribe.rs
pub fn transcribe_path_to_text(
    config: &AppConfig,
    input: &Path,
    model: Option<String>,
    threads: Option<usize>,
    language: Option<String>,
    translate: bool,
    passthrough: Vec<String>,
) -> Result<String> {
    let request = TranscribeRequest {
        input: input.to_path_buf(),
        model,
        output: OutputFormat::Txt,
        no_convert: true,
        no_timestamps: true,
        threads,
        language,
        translate,
        passthrough,
    };

    run_request(config, &request)
}
page 1 / 2next ›