diff --git a/README.md b/README.md index 73f3c61..a1d5760 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,8 @@ models/discogs-effnet-bsdynamic-1.labels.txt target/release/sonic-rs scan ~/Music \ --db data/music.db \ --model models/discogs-effnet-bsdynamic-1.onnx \ - --jobs 8 + --jobs 8 \ + --exclude Full/QOBUZ_MONITOR ``` The first pass is CPU-bound. Later passes skip unchanged files based on @@ -99,16 +100,23 @@ target/release/sonic-rs rebuild-index --db data/music.db ### `scan` ```text -sonic-rs scan [--db ] [--model ] [--jobs ] [--seed ] +sonic-rs scan [--db ] [--model ] [--jobs ] + [--exclude ]... [--seed ] ``` - Recursively walks the library. - `--jobs N` / `-j N` caps the rayon worker threads (default: every core). +- `--exclude DIR` (repeatable) skips an entire subtree; relative paths resolve + against `MUSIC_DIR`. Files under an excluded path are pruned from the + database, so they disappear from the index and playlists too. +- Logs discovery counts and a progress line every 50 processed tracks when + stderr is not a terminal (e.g. under `tee` or `nohup`); interactive runs get a + bar. - Considers only `flac`, `mp3`, `m4a`, `aac`, `ogg`, `opus`, and `wav` (case-insensitive). Cover art, `.cue`, `.log`, and other files are ignored. - Decodes, downmixes, resamples, computes log-mel patches, runs ONNX inference, and pools each track. -- Analyzes in 4,096-track batches and upserts each batch, so peak memory stays +- Analyzes in 128-track batches and upserts each batch, so peak memory stays bounded instead of holding the whole library's embeddings in RAM. - Removes rows for files that no longer exist. - Rebuilds the mean-centered arroy index deterministically. @@ -597,9 +605,10 @@ roughly 10–25 hours at 200–500 MB/s — so expect **~12–30 hours** end to a fast local share, longer on a single HDD or a busy network link. The implementation is sized for this: LMDB reserves 16 GiB of address space -(the file grows on demand), scanning writes every 4,096 tracks so RAM stays -bounded, and incremental rescans only walk the tree and rebuild the index. -Budget ~12 GB of disk for the SQLite database, WAL, and index at that scale. +(the file grows on demand), scanning writes every 128 tracks so RAM stays +bounded and progress is committed frequently, and incremental rescans only walk +the tree and rebuild the index. Budget ~12 GB of disk for the SQLite database, +WAL, and index at that scale. ### Effect of mean-centering diff --git a/src/main.rs b/src/main.rs index c291900..21070f7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -41,6 +41,9 @@ enum Command { /// Worker threads for the scan (defaults to all available cores). #[arg(long, short = 'j')] jobs: Option, + /// Directory subtree to skip (repeatable; relative to MUSIC_DIR). + #[arg(long, value_name = "DIR")] + exclude: Vec, }, /// Write a playlist of tracks nearest to a seed track. @@ -117,6 +120,7 @@ fn main() -> Result<()> { db, model, jobs, + exclude, } => { if let Some(jobs) = jobs { if jobs == 0 { @@ -127,7 +131,7 @@ fn main() -> Result<()> { .build_global() .context("failed to configure the scan worker pool")?; } - let summary = scan::run(&music_dir, &db, &model, cli.seed)?; + let summary = scan::run(&music_dir, &db, &model, &exclude, cli.seed)?; println!( "scanned {} files: {} analyzed, {} skipped, {} pruned, {} indexed", summary.discovered, diff --git a/src/scan.rs b/src/scan.rs index 0fd4af8..3348400 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -2,8 +2,10 @@ use std::collections::HashSet; use std::fs; +use std::io::IsTerminal; use std::path::{Path, PathBuf}; -use std::time::UNIX_EPOCH; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Instant, UNIX_EPOCH}; use anyhow::{bail, Context, Result}; use indicatif::{ProgressBar, ProgressStyle}; @@ -22,9 +24,11 @@ const AUDIO_EXTENSIONS: &[&str] = &["flac", "mp3", "m4a", "aac", "ogg", "opus", /// /// Results are written to SQLite after each batch, so peak memory stays /// bounded at roughly `batch * 7 KB` of embedding/tag blobs instead of holding -/// every track in the library in RAM at once. +/// every track in the library in RAM at once. Keep this small: a single very +/// long track (DJ mix, audiobook) otherwise delays the commit and all progress +/// reporting for the entire batch. #[cfg(not(test))] -const SCAN_BATCH_SIZE: usize = 4096; +const SCAN_BATCH_SIZE: usize = 128; /// Small batches in tests so multi-batch scans are exercised. #[cfg(test)] const SCAN_BATCH_SIZE: usize = 2; @@ -46,11 +50,47 @@ struct FileEntry { } /// Scan `music_dir`, update the SQLite database and rebuild the arroy index. -pub fn run(music_dir: &Path, db_path: &Path, model_path: &Path, seed: u64) -> Result { +/// +/// `excludes` are directory subtrees to ignore (repeatable). Relative paths +/// are resolved against `music_dir`. Files under an excluded subtree are not +/// analyzed and are pruned from the database, so exclusion removes them from +/// the index as well. +pub fn run( + music_dir: &Path, + db_path: &Path, + model_path: &Path, + excludes: &[PathBuf], + seed: u64, +) -> Result { if !music_dir.is_dir() { bail!("music directory {} does not exist", music_dir.display()); } + let music_root = std::path::absolute(music_dir).unwrap_or_else(|_| music_dir.to_path_buf()); + let excluded: Vec = excludes + .iter() + .map(|path| { + let joined = if path.is_absolute() { + path.clone() + } else { + music_root.join(path) + }; + std::path::absolute(&joined).unwrap_or(joined) + }) + .collect(); + if !excluded.is_empty() { + eprintln!( + "excluding: {}", + excluded + .iter() + .map(|path| path.display().to_string()) + .collect::>() + .join(", ") + ); + } + + let scan_start = Instant::now(); + // Fail early with a useful error if the model isn't usable. let _ = SonicModel::load(model_path) .with_context(|| format!("cannot open model {}", model_path.display()))?; @@ -61,7 +101,12 @@ pub fn run(music_dir: &Path, db_path: &Path, model_path: &Path, seed: u64) -> Re let mut files = Vec::new(); let mut existing_paths = HashSet::new(); - for entry in WalkDir::new(music_dir).follow_links(false) { + eprintln!("discovering audio files under {} ...", music_root.display()); + let walker = WalkDir::new(&music_root) + .follow_links(false) + .into_iter() + .filter_entry(|entry| !is_excluded(entry.path(), &excluded)); + for entry in walker { let entry = match entry { Ok(entry) => entry, Err(err) => { @@ -97,6 +142,9 @@ pub fn run(music_dir: &Path, db_path: &Path, model_path: &Path, seed: u64) -> Re mtime_ns, size, }); + if files.len().is_multiple_of(50_000) { + eprintln!(" found {} audio files ...", files.len()); + } } let discovered = files.len(); @@ -128,6 +176,19 @@ pub fn run(music_dir: &Path, db_path: &Path, model_path: &Path, seed: u64) -> Re ); progress.set_message("analyzing tracks"); + // `indicatif` hides the bar when stderr is not a terminal (e.g. through + // `tee`, `nohup`, or a log file). Emit plain progress lines in that case + // so long headless scans are observable. + let progress_hidden = !std::io::stderr().is_terminal(); + let analysis_start = Instant::now(); + let processed = AtomicUsize::new(0); + let total_to_analyze = to_process.len(); + eprintln!( + "discovered {discovered} audio files in {}: {} to analyze, {unchanged} unchanged", + format_secs(scan_start.elapsed().as_secs_f64()), + to_process.len() + ); + let mut skipped = unchanged; let mut analyzed = 0usize; @@ -165,6 +226,25 @@ pub fn run(music_dir: &Path, db_path: &Path, model_path: &Path, seed: u64) -> Re })(); progress.inc(1); + let done = processed.fetch_add(1, Ordering::Relaxed) + 1; + // Independent of batch boundaries: a single long track + // can stall a 128-track batch, but completed tracks keep + // reporting progress. + if progress_hidden && done.is_multiple_of(50) { + let elapsed = analysis_start.elapsed().as_secs_f64(); + let rate = done as f64 / elapsed.max(1e-9); + let remaining = total_to_analyze.saturating_sub(done); + let eta = if rate > 0.0 { + remaining as f64 / rate + } else { + 0.0 + }; + eprintln!( + " {done}/{total_to_analyze} processed ({rate:.2} tracks/s, elapsed {}, ETA {})", + format_secs(elapsed), + format_secs(eta) + ); + } (entry.clone(), result) }, ) @@ -193,6 +273,10 @@ pub fn run(music_dir: &Path, db_path: &Path, model_path: &Path, seed: u64) -> Re } progress.finish_and_clear(); + eprintln!( + "analysis complete: {analyzed} analyzed, {skipped} skipped in {}; rebuilding index ...", + format_secs(scan_start.elapsed().as_secs_f64()) + ); let pruned = db.prune_missing(&existing_paths)?; let index = SonicIndex::open(default_index_path(db_path))?; @@ -214,6 +298,11 @@ fn is_audio_file(path: &Path) -> bool { .is_some_and(|ext| AUDIO_EXTENSIONS.contains(&ext.as_str())) } +/// Component-aware prefix check: `/music/SKIPPER` is not inside `/music/SKIP`. +fn is_excluded(path: &Path, excludes: &[PathBuf]) -> bool { + excludes.iter().any(|prefix| path.starts_with(prefix)) +} + fn modified_ns(metadata: &fs::Metadata) -> i64 { metadata .modified() @@ -223,6 +312,18 @@ fn modified_ns(metadata: &fs::Metadata) -> i64 { .unwrap_or(0) } +/// Compact human-readable duration for progress lines (`1h05m`, `4m12s`, `9s`). +fn format_secs(seconds: f64) -> String { + let total = seconds.max(0.0).round() as u64; + if total >= 3600 { + format!("{}h{:02}m", total / 3600, (total % 3600) / 60) + } else if total >= 60 { + format!("{}m{:02}s", total / 60, total % 60) + } else { + format!("{total}s") + } +} + #[cfg(test)] mod tests { use super::*; @@ -280,7 +381,7 @@ mod tests { write_wav(&track, 4.0).unwrap(); let db_path = dir.path().join("library.db"); - let first = run(&music, &db_path, &model_path, 42).unwrap(); + let first = run(&music, &db_path, &model_path, &[], 42).unwrap(); assert_eq!(first.discovered, 1); assert_eq!(first.analyzed, 1); assert_eq!(first.pruned, 0); @@ -293,13 +394,13 @@ mod tests { drop(db); drop(index); - let second = run(&music, &db_path, &model_path, 42).unwrap(); + let second = run(&music, &db_path, &model_path, &[], 42).unwrap(); assert_eq!(second.analyzed, 0); assert_eq!(second.skipped, 1); assert_eq!(second.indexed, 1); fs::remove_file(&track).unwrap(); - let third = run(&music, &db_path, &model_path, 42).unwrap(); + let third = run(&music, &db_path, &model_path, &[], 42).unwrap(); assert_eq!(third.pruned, 1); assert_eq!(third.indexed, 0); @@ -327,7 +428,7 @@ mod tests { } let db_path = dir.path().join("library.db"); - let summary = run(&music, &db_path, &model_path, 42).unwrap(); + let summary = run(&music, &db_path, &model_path, &[], 42).unwrap(); assert_eq!(summary.discovered, 5); assert_eq!(summary.analyzed, 5); assert_eq!(summary.indexed, 5); @@ -336,6 +437,58 @@ mod tests { assert_eq!(db.track_count().unwrap(), 5); } + #[test] + fn excluded_directory_is_skipped_and_pruned() { + let model_path = default_model_path(); + if !model_path.exists() { + eprintln!( + "skipping scan exclusion test: {} not found", + model_path.display() + ); + return; + } + + let dir = TempDir::new().unwrap(); + let music = dir.path().join("music"); + fs::create_dir_all(music.join("keep")).unwrap(); + fs::create_dir_all(music.join("SKIP")).unwrap(); + write_wav(&music.join("keep/a.wav"), 3.0).unwrap(); + write_wav(&music.join("SKIP/b.wav"), 3.0).unwrap(); + + let db_path = dir.path().join("library.db"); + // Relative excludes resolve against the music directory. + let first = run(&music, &db_path, &model_path, &[PathBuf::from("SKIP")], 42).unwrap(); + assert_eq!(first.discovered, 1); + assert_eq!(first.analyzed, 1); + assert_eq!(first.indexed, 1); + + let db = Db::open(&db_path, MODEL_ID, EMBEDDING_DIM).unwrap(); + assert_eq!(db.track_count().unwrap(), 1); + drop(db); + + // Dropping the exclusion brings the skipped track back. + let second = run(&music, &db_path, &model_path, &[], 42).unwrap(); + assert_eq!(second.discovered, 2); + assert_eq!(second.analyzed, 1); + assert_eq!(second.indexed, 2); + + let db = Db::open(&db_path, MODEL_ID, EMBEDDING_DIM).unwrap(); + assert_eq!(db.track_count().unwrap(), 2); + } + + #[test] + fn exclusion_is_component_aware() { + let excludes = vec![PathBuf::from("/music/Full/SKIP")]; + assert!(is_excluded( + Path::new("/music/Full/SKIP/album/track.flac"), + &excludes + )); + assert!(!is_excluded( + Path::new("/music/Full/SKIPPER/track.flac"), + &excludes + )); + } + #[test] fn audio_extensions_are_case_insensitive() { assert!(is_audio_file(Path::new("a.FLAC")));