diff options
| author | Leonard Kugis <leonard@kug.is> | 2026-11-28 16:15:16 +0100 |
|---|---|---|
| committer | Leonard Kugis <leonard@kug.is> | 2026-11-28 16:15:16 +0100 |
| commit | 0fdda93b22fd548aecc0a35e24339f00da11b797 (patch) | |
| tree | 95b0bdf2e69324e851199648a0a122d62f70aa03 | |
| parent | ab98c6e9e24f638d08950c335e8c860b091debf3 (diff) | |
| download | slskd-0fdda93b22fd548aecc0a35e24339f00da11b797.tar.gz | |
This is a python script to upgrade an existing music library
using remote slsk instance.
It will perform scoring of search results and prefer 44.1 kHz, 16-Bit FLAC
as target format.
| -rwxr-xr-x | tools/slskd_music_upgrade.py | 2907 |
1 files changed, 2907 insertions, 0 deletions
diff --git a/tools/slskd_music_upgrade.py b/tools/slskd_music_upgrade.py new file mode 100755 index 00000000..f94ec149 --- /dev/null +++ b/tools/slskd_music_upgrade.py @@ -0,0 +1,2907 @@ +#!/usr/bin/env python3 +""" +slskd_music_upgrade.py + +Find lossless (preferably FLAC 16-bit / 44.1 kHz) replacements for lossy or +low-quality audio files and enqueue the best candidates on a slskd instance. + +The script itself talks to the slskd HTTP API. It only reads your local +files for metadata, so the paths passed with --include must be readable by +the machine running this script. Downloads happen on the slskd server. + +No third-party Python packages are required. If `ffprobe` is available it +is used for accurate tags, duration, bit depth, sample rate, and codec +information. Without ffprobe the script falls back to filename/directory +heuristics and treats files by extension. + +Examples +-------- + export SLSKD_URL=http://slsk.kug.is + export SLSKD_USERNAME=... + export SLSKD_PASSWORD=... + + # Preview metadata/search queries without contacting slskd. + python3 slskd_music_upgrade.py \ + --include ~/Music/SomeAlbum \ + --scan-only + + # Search and show candidates; do not enqueue anything. + python3 slskd_music_upgrade.py \ + --include ~/Music/SomeAlbum \ + --dry-run + + # Search a directory, skip a bonus-disc folder, and download the top 3 + # candidates for each track into slskd's download directory under + # "upgrades/...". + python3 slskd_music_upgrade.py \ + --include ~/Music/SomeAlbum \ + --exclude ~/Music/SomeAlbum/Bonus \ + --top 3 --yes + + # Use an API key instead of a username/password. + python3 slskd_music_upgrade.py --api-key "$SLSKD_API_KEY" \ + --include ~/Music --exclude '**/Compilations/**' --dry-run + +Notes +----- +Soulseek search results do not include audio spectra, so "not upscaled" can +only be judged from metadata. The script rejects files that are obviously +inconsistent (for example a 16-bit/96 kHz FLAC, or a FLAC whose average +bitrate looks like a 128-320 kbps transcode) and heavily penalizes anything +suspicious. It still cannot prove that a file is not a high-bitrate +transcode. Use `spek` or a spectral analyzer on the downloaded files if you +need certainty. + +The script uses the modern batch download endpoint: + POST /api/v0/transfers/downloads/batches +""" + +from __future__ import annotations + +import argparse +import base64 +import hashlib +import json +import logging +import math +import os +import re +import shutil +import subprocess +import sys +import time +import unicodedata +import urllib.error +import urllib.parse +import urllib.request +from collections import Counter +from dataclasses import dataclass, field +from difflib import SequenceMatcher +from pathlib import Path +from typing import Any, Iterable, Optional + +LOG = logging.getLogger("slskd-upgrade") + +AUDIO_EXTENSIONS = { + "aac", "aif", "aifc", "aiff", "alac", "ape", "dff", "dsf", "flac", + "m4a", "mka", "mp3", "mpc", "oga", "ogg", "opus", "wav", "wave", + "wma", "wv", +} + +LOSSLESS_EXTENSIONS = { + "aif", "aifc", "aiff", "alac", "ape", "dff", "dsf", "flac", "wav", + "wave", "wv", +} + +LOSSY_EXTENSIONS = { + "aac", "m4a", "mka", "mp3", "mpc", "oga", "ogg", "opus", "wma", +} + +LOSSLESS_CODECS = { + "alac", "ape", "flac", "wavpack", + "pcm_s16le", "pcm_s24le", "pcm_s32le", "pcm_f32le", "pcm_f64le", + "pcm_s16be", "pcm_s24be", "pcm_s32be", "pcm_u8", + "dsd_lsbf", "dsd_msbf", "dsd_lsbf_planar", "dsd_msbf_planar", +} + +STOP_WORDS = { + "a", "an", "and", "the", "of", "to", "in", "on", "for", "with", "by", + "feat", "ft", "featuring", "prod", "from", "at", +} + +GENERIC_DIRECTORY_NAMES = { + "album", "albums", "audio", "cd", "complete", "completed", "compilation", + "compilations", "data", "download", "downloads", "flac", "incoming", + "library", "lossless", "media", "mp3", "music", "music library", "share", + "shared", "song", "songs", "torrents", "track", "tracks", "various", + "various artists", +} + +VERSION_PATTERNS = { + "remix": ("remix", "rmx", "bootleg", "mashup", "flip", "vs", "versus"), + "instrumental": ("instrumental", "inst", "off vocal", "offvocal"), + "acapella": ("acapella", "acappella"), + "live": ("live",), + "acoustic": ("acoustic", "unplugged"), + "demo": ("demo",), + "cover": ("cover",), + "karaoke": ("karaoke",), + "sped": ("sped up", "slowed", "nightcore", "8d"), + "edit": ("radio edit", "single version", "single edit", "edit"), + "extended": ("extended", "club mix", "dub mix"), + "original": ("original mix", "original version"), +} + +HARD_VERSION_FAMILIES = { + "remix", "instrumental", "acapella", "live", "acoustic", "demo", "cover", + "karaoke", "sped", +} +SOFT_VERSION_FAMILIES = {"edit", "extended"} + +NOISE_BRACKETS_RE = re.compile( + r"[\(\[]\s*(?:" + r"official(?:\s+(?:audio|video|music\s+video|visuali[sz]er))?|" + r"lyrics?|audio|video|visuali[sz]er|hd|hq|4k|8k|" + r"free\s+download|out\s+now|premiere|explicit|clean|" + r"mp3|flac|320\s*kbps|128\s*kbps|256\s*kbps" + r")\b[^)\]]*[\)\]]", + re.IGNORECASE, +) + +SUSPICIOUS_WORDS_RE = re.compile( + r"\b(?:upscal(?:e|ed)|upmix(?:ed)?|transcod(?:e|ed)|" + r"fake\s+(?:flac|lossless)|mp3\s*(?:to|->|converted\s+to)\s*flac|" + r"320\s*kbps\s+flac)\b", + re.IGNORECASE, +) + +SPAM_URL_RE = re.compile( + r"[\(\[]?\s*(?:https?://|www\.)\S+[\)\]]?", + re.IGNORECASE, +) + +BAD_ARTIST_TAG_RE = re.compile( + r"^(?:data\d+|(?:disk|disc|cd|vol(?:ume)?)\s*\d*|" + r"unknown(?:\s+artist)?|various(?:\s+artists)?|va|v\s*a)$", + re.IGNORECASE, +) + +COMMON_LOSSY_BITRATES = (64, 96, 112, 128, 160, 192, 224, 256, 320) + +GUID_RE = re.compile( + r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", + re.IGNORECASE, +) + + +# --------------------------------------------------------------------------- +# text helpers +# --------------------------------------------------------------------------- + + +def normalize_text(value: Optional[str]) -> str: + """Case-fold, strip accents, and reduce everything else to words.""" + if not value: + return "" + + text = unicodedata.normalize("NFKD", str(value)) + text = "".join(char for char in text if not unicodedata.combining(char)) + text = text.casefold().replace("&", " and ") + text = "".join(char if char.isalnum() else " " for char in text) + return re.sub(r"\s+", " ", text).strip() + + +def tokens(value: Optional[str]) -> list[str]: + return normalize_text(value).split() + + +def content_tokens(value: Optional[str]) -> list[str]: + """Tokens without stopwords, falling back to all tokens for odd titles.""" + all_tokens = tokens(value) + meaningful = [token for token in all_tokens if token not in STOP_WORDS] + return meaningful or all_tokens + + +def token_coverage(needle: str, haystack_text: str) -> float: + """Fraction of needle's meaningful tokens also present in haystack.""" + needle_tokens = set(content_tokens(needle)) + if not needle_tokens: + return 0.0 + + haystack_tokens = set(tokens(haystack_text)) + return len(needle_tokens & haystack_tokens) / len(needle_tokens) + + +def fuzzy_ratio(left: str, right: str) -> float: + left_norm = normalize_text(left) + right_norm = normalize_text(right) + if not left_norm or not right_norm: + return 0.0 + return SequenceMatcher(None, left_norm, right_norm).ratio() + + +def safe_segment(value: str, fallback: str = "unknown", max_length: int = 96) -> str: + """Make one relative path segment safe for slskd's destination validation.""" + text = unicodedata.normalize("NFC", str(value or "")) + text = re.sub(r"[\x00-\x1f/\\:*?\"<>|]+", "_", text) + text = re.sub(r"\s+", " ", text).strip(" ._-") + if not text or text in {".", ".."}: + text = fallback + if len(text) > max_length: + suffix = "-" + hashlib.sha1(text.encode("utf-8")).hexdigest()[:6] + text = text[: max_length - len(suffix)].rstrip(" ._-") + suffix + return text + + +def safe_destination(parts: Iterable[str]) -> str: + cleaned: list[str] = [] + for part in parts: + for piece in str(part).replace("\\", "/").split("/"): + if not piece: + continue + segment = safe_segment(piece) + if segment in {".", ".."}: + continue + cleaned.append(segment) + + destination = "/".join(cleaned) + if not destination or destination.startswith("/"): + raise ValueError("destination must be a non-empty relative path") + if any(piece == ".." for piece in destination.split("/")): + raise ValueError("destination must not contain path traversal segments") + return destination + + +def parse_int(value: Any) -> Optional[int]: + if value is None: + return None + text = str(value).strip() + if not text: + return None + text = text.split("/", 1)[0] + try: + return int(float(text)) + except (TypeError, ValueError): + return None + + +def parse_float(value: Any) -> Optional[float]: + if value is None: + return None + try: + parsed = float(str(value).strip()) + return parsed if math.isfinite(parsed) and parsed > 0 else None + except (TypeError, ValueError): + return None + + +# --------------------------------------------------------------------------- +# metadata +# --------------------------------------------------------------------------- + + +def parse_filename(stem: str) -> tuple[str, str]: + """Best-effort (artist, title) extraction from a filename stem.""" + text = stem.replace("_", " ").strip() + text = re.sub( + r"^\s*[\[\(]?\d{1,3}[\]\)]?\s*[-–—._)\]]\s*", + "", + text, + ).strip() + + parts = re.split(r"\s+[-–—]\s+", text, maxsplit=2) + if len(parts) >= 3 and parse_int(parts[1]) is not None: + # "Artist - 01 - Title" + return ( + re.sub(r"\s+", " ", parts[0]).strip(), + re.sub(r"\s+", " ", parts[2]).strip(), + ) + + if len(parts) >= 2: + candidate_artist = re.sub(r"\s+", " ", parts[0]).strip() + candidate_title = re.sub(r"\s+", " ", " - ".join(parts[1:])).strip() + if candidate_artist and not candidate_artist.isdigit(): + return candidate_artist, candidate_title + + return "", re.sub(r"\s+", " ", text).strip() + + +def clean_tag_text(value: Optional[str]) -> str: + """Remove common download-site spam and normalize separators in tags.""" + text = str(value or "") + text = text.replace("_", " ") + text = SPAM_URL_RE.sub(" ", text) + text = re.sub(r"[\(\[]\s*[\)\]]", " ", text) + text = re.sub(r"\s+", " ", text).strip(" -–—._") + return text + + +def is_bad_artist_tag(value: str) -> bool: + normalized = normalize_text(value) + if not normalized: + return True + return bool(BAD_ARTIST_TAG_RE.match(normalized)) + + +def parse_embedded_artist_title(text: str) -> tuple[str, str]: + """Split an 'Artist - Title' string, tolerating a missing space.""" + text = clean_tag_text(text) + match = re.match(r"^\s*(.+?)\s+[-–—]\s+(.+?)\s*$", text) + if match: + return match.group(1).strip(), match.group(2).strip() + + # Things like "Headhunterz & KSHMR-Dharma" are common in badly tagged + # files. Only split on an unspaced hyphen when the left side clearly + # looks like more than a single hyphenated name (e.g. "Jay-Z"). + for match in re.finditer(r"-(?=\S)", text): + left = text[: match.start()].strip() + right = text[match.end():].strip() + if not left or not right: + continue + lowered = left.casefold() + if " & " in left or " and " in lowered or " vs " in lowered or " " in left: + return left, right + + return "", text + + +def clean_album_directory(name: str) -> str: + text = name.strip() + text = re.sub( + r"^\s*[\[\(]?(?:19|20)\d{2}[\]\)]?\s*[-–—_.]?\s*", + "", + text, + ) + text = re.sub( + r"\s*[\[\(][^)\]]*(?:flac|cd|mp3|web|vinyl|" + r"16b|24b|44[.,]1|48\s*khz|96\s*khz|bit)[^)\]]*[\)\]]", + " ", + text, + flags=re.IGNORECASE, + ) + text = re.sub(r"\s*[-–—]\s*(?:cd|disc|disk)\s*\d+\s*$", "", text, flags=re.IGNORECASE) + text = re.sub(r"\s+", " ", text).strip(" -–—._") + return text + + +def is_disc_directory(name: str) -> bool: + return bool( + re.fullmatch( + r"\s*(?:cd|disc|disk|dvd|vol(?:ume)?)\s*\d+\s*", + name, + flags=re.IGNORECASE, + ) + ) + + +def is_generic_directory(name: str) -> bool: + normalized = normalize_text(name) + if not normalized or normalized in GENERIC_DIRECTORY_NAMES: + return True + if re.fullmatch(r"[a-z]", normalized): + return True + if re.fullmatch(r"(?:19|20)\d{2}", normalized): + return True + if is_disc_directory(name): + return True + return False + + +def split_artist_album_directory(name: str) -> tuple[str, str]: + text = clean_album_directory(name) + match = re.match(r"^\s*(.+?)\s+[-–—]\s+(.+?)\s*$", text) + if match: + left, right = match.group(1).strip(), match.group(2).strip() + if left and right and not left.isdigit() and not re.fullmatch(r"(?:19|20)\d{2}", left): + return left, right + return "", "" + + +def find_album_directory(path: Path) -> Path: + """Walk up past disc directories and generic folders to find the album.""" + parent = path.parent + while is_disc_directory(parent.name) or is_generic_directory(parent.name): + if parent == parent.parent: + break + parent = parent.parent + return parent + + +def infer_album(path: Path, root: Optional[Path] = None) -> tuple[str, str, Path]: + """Return (album, artist_from_directory, album_directory).""" + album_directory = find_album_directory(path) + + # If the file sits directly in the include root, the root is a library or + # loose-tracks folder, not necessarily an album. Guessing an album name + # from it produces queries like "Artist upgrade"; leave it empty instead. + if root is not None and album_directory == root: + return "", "", album_directory + + album = clean_album_directory(album_directory.name) + artist, album_from_split = split_artist_album_directory(album_directory.name) + + if album_from_split: + album = album_from_split + + if album and is_generic_directory(album): + album = "" + + return album, artist, album_directory + + +def infer_artist(path: Path, album_directory: Path, root: Path) -> str: + """Walk a few ancestors looking for a likely artist directory.""" + current = album_directory.parent + for _ in range(4): + if current == current.parent: + break + # Never infer an artist from the include root or anything above it. + if root not in current.parents: + break + if not is_generic_directory(current.name): + artist, _album = split_artist_album_directory(current.name) + if artist: + return artist + cleaned = clean_album_directory(current.name) + if cleaned and not re.fullmatch(r"(?:19|20)\d{2}", cleaned): + return cleaned + current = current.parent + return "" + + +def ffprobe_metadata(path: Path) -> dict[str, Any]: + """Read tags/stream info with ffprobe; return an empty dict on failure.""" + ffprobe = shutil.which("ffprobe") + if not ffprobe: + return {} + + command = [ + ffprobe, + "-v", "error", + "-show_entries", + ( + "format=duration,bit_rate:" + "format_tags=artist,album_artist,albumartist,album,title,track,tracknumber:" + "stream=index,codec_type,codec_name,sample_rate,bits_per_raw_sample," + "bits_per_sample,bit_rate,duration:" + "stream_tags=artist,album_artist,albumartist,album,title,track,tracknumber" + ), + "-of", "json", + str(path), + ] + + try: + result = subprocess.run( + command, + check=False, + capture_output=True, + text=True, + timeout=25, + ) + except (OSError, subprocess.SubprocessError): + return {} + + if result.returncode != 0 or not result.stdout.strip(): + return {} + + try: + data = json.loads(result.stdout) + except json.JSONDecodeError: + return {} + + streams = data.get("streams") or [] + audio_stream = next( + (stream for stream in streams if stream.get("codec_type") == "audio"), + {}, + ) + format_info = data.get("format") or {} + + tags: dict[str, str] = {} + for source in (audio_stream.get("tags") or {}, format_info.get("tags") or {}): + for key, value in source.items(): + if value is None: + continue + tags[str(key).casefold()] = str(value) + + def tag(*names: str) -> str: + for name in names: + value = tags.get(name.casefold()) + if value: + return value + return "" + + return { + "tags": tags, + "title": tag("title"), + "artist": tag("artist"), + "album_artist": tag("album_artist", "albumartist"), + "album": tag("album"), + "track_number": parse_int(tag("tracknumber", "track")), + "duration": parse_float(format_info.get("duration")) + or parse_float(audio_stream.get("duration")), + "bit_depth": parse_int(audio_stream.get("bits_per_raw_sample")) + or parse_int(audio_stream.get("bits_per_sample")), + "sample_rate": parse_int(audio_stream.get("sample_rate")), + "bitrate": parse_int(audio_stream.get("bit_rate")) + or parse_int(format_info.get("bit_rate")), + "codec": str(audio_stream.get("codec_name") or "").casefold(), + } + + +def infer_bitrate_from_name(path: Path) -> Optional[int]: + matches = re.findall(r"(?<!\d)(64|96|112|128|160|192|224|256|320)\s*(?:kbps|kbit)?", path.stem, re.I) + if matches: + return int(matches[-1]) + return None + + +@dataclass +class Track: + path: Path + root: Path + artist: str = "" + album_artist: str = "" + title: str = "" + album: str = "" + track_number: Optional[int] = None + duration: Optional[float] = None + bit_depth: Optional[int] = None + sample_rate: Optional[int] = None + bitrate: Optional[int] = None + codec: Optional[str] = None + extension: str = "" + is_lossless: bool = False + search_query: str = "" + search_mode: str = "" + skip_reason: str = "" + + @property + def display_name(self) -> str: + if self.artist and self.title: + return f"{self.artist} - {self.title}" + return self.title or self.path.stem + + +def read_track(path: Path, root: Path) -> Track: + extension = path.suffix.casefold().lstrip(".") + probed = ffprobe_metadata(path) + + title = clean_tag_text(probed.get("title")) + artist = clean_tag_text(probed.get("artist")) + album_artist = clean_tag_text(probed.get("album_artist")) + album = clean_tag_text(probed.get("album")) + track_number = probed.get("track_number") + duration = probed.get("duration") + bit_depth = probed.get("bit_depth") or None + sample_rate = probed.get("sample_rate") or None + bitrate = probed.get("bitrate") or None + codec = probed.get("codec") or "" + + artist_tag_was_bad = is_bad_artist_tag(artist) + if artist_tag_was_bad: + artist = "" + if is_bad_artist_tag(album_artist): + album_artist = "" + + parsed_artist, parsed_title = parse_filename(path.stem) + + # If the artist tag is junk ("Va", "data1", "CD1") but the filename has a + # clear "Artist - Title" form, prefer the filename. + if artist_tag_was_bad and parsed_artist and parsed_title: + artist = parsed_artist + title = parsed_title + + if not title: + title = parsed_title or path.stem + if not artist and album_artist: + artist = album_artist + if not artist: + artist = parsed_artist + + # If the artist is still missing and the title contains a clear + # "Artist - Title" pair, use that instead. + if is_bad_artist_tag(artist): + embedded_artist, embedded_title = parse_embedded_artist_title(title) + if embedded_artist and embedded_title: + artist = embedded_artist + title = embedded_title + + if not album_artist: + album_artist = artist + + album_from_directory, artist_from_directory, album_directory = infer_album(path, root) + if not album: + album = album_from_directory + if not artist: + artist = artist_from_directory + if not artist: + artist = infer_artist(path, album_directory, root) + if not album_artist: + album_artist = artist + + # Some taggers put the artist at the start or end of the title too: + # "Heartless - I Am Insane (Extended)" with artist "Heartless". + if artist and title: + artist_words = artist.split() + artist_pattern = r"\s+".join(re.escape(word) for word in artist_words) + title = re.sub( + r"^\s*" + artist_pattern + r"\s*[-–—]\s*", + "", + title, + count=1, + flags=re.IGNORECASE, + ).strip() + + without_suffix = re.sub( + r"\s*[-–—]\s*" + artist_pattern + r"\s*$", + "", + title, + count=1, + flags=re.IGNORECASE, + ).strip() + if without_suffix and without_suffix != title: + title = without_suffix + + if bitrate is not None: + # ffprobe returns bits/second; Soulseek/API returns kbps. + bitrate = int(round(bitrate / 1000)) + elif extension in LOSSY_EXTENSIONS: + bitrate = infer_bitrate_from_name(path) + + is_lossless = extension in LOSSLESS_EXTENSIONS or codec in LOSSLESS_CODECS + + if extension == "m4a": + implied_kbps = None + try: + file_size = path.stat().st_size + except OSError: + file_size = 0 + if duration and file_size: + implied_kbps = file_size * 8 / duration / 1000 + if codec == "alac": + is_lossless = True + elif codec: + is_lossless = codec in LOSSLESS_CODECS + else: + is_lossless = bool( + bit_depth + and sample_rate + and (bitrate is None or bitrate >= 500) + and (implied_kbps is None or implied_kbps >= 500) + ) + + if not title: + title = path.stem + + return Track( + path=path, + root=root, + artist=artist.strip(), + album_artist=(album_artist or artist).strip(), + title=title.strip(), + album=album.strip(), + track_number=track_number, + duration=duration, + bit_depth=bit_depth, + sample_rate=sample_rate, + bitrate=bitrate, + codec=codec or None, + extension=extension, + is_lossless=is_lossless, + ) + + +def needs_upgrade(track: Track, force: bool) -> tuple[bool, str]: + if force: + return True, "" + + if track.is_lossless: + bit_depth_ok = track.bit_depth is None or track.bit_depth >= 16 + sample_rate_ok = track.sample_rate is None or track.sample_rate >= 44100 + if bit_depth_ok and sample_rate_ok: + return False, "already lossless at CD quality or better" + + return True, "" + + +def source_quality_text(track: Track) -> str: + if track.is_lossless: + bit_depth = f"{track.bit_depth}-bit" if track.bit_depth else "lossless" + sample_rate = f"{track.sample_rate / 1000:g} kHz" if track.sample_rate else "" + return " ".join(part for part in (bit_depth, sample_rate) if part) + if track.bitrate: + return f"~{track.bitrate} kbps" + return track.extension.upper() or "lossy" + + +# --------------------------------------------------------------------------- +# search planning +# --------------------------------------------------------------------------- + + +def clean_query_text(value: str) -> str: + text = NOISE_BRACKETS_RE.sub(" ", value or "") + text = re.sub( + r"[\(\[]\s*(?:feat\.?|ft\.?|featuring)[^)\]]*[\)\]]", + " ", + text, + flags=re.IGNORECASE, + ) + text = re.sub( + r"\s+(?:feat\.?|ft\.?|featuring)\s+.*$", + " ", + text, + flags=re.IGNORECASE, + ) + text = re.sub(r"[\\/:*?\"<>|]+", " ", text) + text = re.sub(r"\s+", " ", text).strip(" -–—._") + return text + + +def shorten_query(text: str, max_length: int = 120) -> str: + if len(text) <= max_length: + return text + cut = text[:max_length].rsplit(" ", 1)[0].strip() + return cut or text[:max_length] + + +def build_track_query(track: Track) -> str: + title = clean_query_text(track.title) + artist = clean_query_text(track.artist) + album = clean_query_text(track.album) + + if artist and normalize_text(artist) in normalize_text(title): + artist = "" + + if artist: + parts = [artist, title] + elif album and len(content_tokens(title)) <= 2: + # Short/generic titles benefit from the album name when no artist is + # available; long titles are already distinctive enough on their own. + parts = [album, title] + else: + parts = [title] + + parts = [part for part in parts if part] + if not parts: + parts = [clean_query_text(track.path.stem)] + + return shorten_query(" ".join(parts)) + + +def build_album_query(track: Track) -> str: + artist = clean_query_text(track.album_artist or track.artist) + album = clean_query_text(track.album) + + if normalize_text(artist) in {"various artists", "various"}: + artist = "" + + if artist and album: + return shorten_query(f"{artist} {album}") + if album: + return shorten_query(album) + return build_track_query(track) + + +@dataclass +class SearchGroup: + key: tuple[str, ...] + query: str + tracks: list[Track] + responses: list[dict[str, Any]] = field(default_factory=list) + search_id: Optional[str] = None + error: Optional[str] = None + response_count: int = 0 + file_count: int = 0 + elapsed: float = 0.0 + + @property + def label(self) -> str: + if self.key and self.key[0] == "album": + return "album" + return "track" + + +def plan_searches(tracks: list[Track], search_mode: str, album_min_tracks: int) -> list[SearchGroup]: + groups: list[SearchGroup] = [] + + if search_mode == "track": + for track in tracks: + track.search_query = build_track_query(track) + track.search_mode = "track" + groups.append( + SearchGroup(key=("track", str(track.path)), query=track.search_query, tracks=[track]) + ) + return [group for group in groups if group.query] + + album_groups: dict[tuple[str, ...], list[Track]] = {} + for track in tracks: + album_artist = (track.album_artist or track.artist).strip() + is_various = normalize_text(album_artist) in {"various artists", "various"} + if ( + search_mode in {"auto", "album"} + and track.album + and album_artist + and not is_various + ): + key = ( + "album", + normalize_text(album_artist), + normalize_text(track.album), + ) + album_groups.setdefault(key, []).append(track) + else: + track.search_query = build_track_query(track) + track.search_mode = "track" + if track.search_query: + groups.append( + SearchGroup( + key=("track", str(track.path)), + query=track.search_query, + tracks=[track], + ) + ) + + for key, grouped_tracks in album_groups.items(): + grouped_tracks.sort(key=lambda item: str(item.path).casefold()) + if len(grouped_tracks) >= max(2, album_min_tracks): + query = build_album_query(grouped_tracks[0]) + if query: + for track in grouped_tracks: + track.search_query = query + track.search_mode = "album" + groups.append(SearchGroup(key=key, query=query, tracks=grouped_tracks)) + continue + + for track in grouped_tracks: + track.search_query = build_track_query(track) + track.search_mode = "track" + if track.search_query: + groups.append( + SearchGroup( + key=("track", str(track.path)), + query=track.search_query, + tracks=[track], + ) + ) + + groups.sort(key=lambda group: str(group.tracks[0].path).casefold()) + return groups + + +# --------------------------------------------------------------------------- +# slskd API client +# --------------------------------------------------------------------------- + + +class ApiError(Exception): + def __init__(self, status: int, body: str, message: Optional[str] = None): + self.status = status + self.body = body + super().__init__(message or f"HTTP {status}: {body[:500]}") + + +class SlskdClient: + def __init__( + self, + base_url: str, + username: Optional[str] = None, + password: Optional[str] = None, + api_key: Optional[str] = None, + request_timeout: int = 45, + ): + if not base_url: + raise ValueError("slskd URL is required") + if not base_url.startswith(("http://", "https://")): + base_url = "http://" + base_url + self.base_url = base_url.rstrip("/") + self.username = username + self.password = password + self.api_key = api_key + self.request_timeout = request_timeout + self.token: Optional[str] = None + self._destination_cache: dict[str, bool] = {} + self.instant_zero_streak = 0 + + # -- low level --------------------------------------------------------- + + def _headers(self, auth: bool) -> dict[str, str]: + headers = {"Accept": "application/json"} + if auth: + if self.token: + headers["Authorization"] = f"Bearer {self.token}" + elif self.api_key: + headers["X-API-Key"] = self.api_key + return headers + + def _request_once( + self, + method: str, + path: str, + payload: Optional[Any] = None, + *, + auth: bool = True, + timeout: Optional[int] = None, + ) -> Any: + url = self.base_url + path + data = None + headers = self._headers(auth) + + if payload is not None: + data = json.dumps(payload).encode("utf-8") + headers["Content-Type"] = "application/json" + + request = urllib.request.Request(url, data=data, headers=headers, method=method) + + try: + with urllib.request.urlopen( + request, + timeout=timeout or self.request_timeout, + ) as response: + raw = response.read() + status = response.status + except urllib.error.HTTPError as error: + body = error.read().decode("utf-8", errors="replace") + raise ApiError(error.code, body) from error + except urllib.error.URLError as error: + raise ApiError(0, str(error.reason or error)) from error + except TimeoutError as error: + raise ApiError(0, f"request timed out: {error}") from error + + if status == 204 or not raw: + return None + if status == 207: + # Multi-status still carries a JSON body; fall through and parse it. + pass + if status < 200 or status >= 300: + body = raw.decode("utf-8", errors="replace") + raise ApiError(status, body) + + text = raw.decode("utf-8", errors="replace") + try: + return json.loads(text) + except json.JSONDecodeError: + return text + + def request( + self, + method: str, + path: str, + payload: Optional[Any] = None, + *, + auth: bool = True, + timeout: Optional[int] = None, + retry_auth: bool = True, + ) -> Any: + try: + return self._request_once( + method, + path, + payload, + auth=auth, + timeout=timeout, + ) + except ApiError as error: + if error.status == 401 and auth and retry_auth and not self.api_key: + LOG.info("Session expired; logging in again") + self.login() + return self._request_once( + method, + path, + payload, + auth=auth, + timeout=timeout, + ) + raise + + # -- authentication ---------------------------------------------------- + + def login(self) -> None: + if self.api_key: + return + if not self.username or not self.password: + raise ApiError( + 401, + "no credentials supplied", + "Authentication requires --username/--password or --api-key", + ) + + LOG.debug("Logging in as %s", self.username) + response = self._request_once( + "POST", + "/api/v0/session", + {"username": self.username, "password": self.password}, + auth=False, + ) + if not isinstance(response, dict) or not response.get("token"): + raise ApiError(401, "login response did not contain a token") + self.token = response["token"] + + def ensure_authenticated(self) -> None: + if self.api_key: + # Validate the key early so a typo doesn't look like "no results". + self.request("GET", "/api/v0/session") + return + if not self.token: + self.login() + else: + try: + self.request("GET", "/api/v0/session") + except ApiError as error: + if error.status == 401: + self.login() + else: + raise + + def check_soulseek_connection(self) -> bool: + try: + application = self.request("GET", "/api/v0/application", timeout=30) + except ApiError as error: + LOG.debug("Could not read application state: %s", error) + return True + + if not isinstance(application, dict): + return True + + server = application.get("server") or {} + connected = bool(server.get("isConnected")) + logged_in = bool(server.get("isLoggedIn")) + if not connected or not logged_in: + LOG.warning( + "slskd is not connected/logged in to the Soulseek server " + "(connected=%s, loggedIn=%s); searches will likely fail", + connected, + logged_in, + ) + return False + return True + + # -- searches ---------------------------------------------------------- + + def search( + self, + query: str, + *, + search_timeout: int, + response_limit: int, + file_limit: int, + ) -> dict[str, Any]: + payload = { + "searchText": query, + # slskd 0.26.x passes SearchTimeout straight to Soulseek.NET, + # which expects milliseconds. Our CLI option is in seconds. + "searchTimeout": max(5, search_timeout) * 1000, + "responseLimit": max(1, response_limit), + "fileLimit": max(1, file_limit), + "filterResponses": True, + } + + started = time.monotonic() + created = None + for attempt in range(4): + try: + created = self.request( + "POST", + "/api/v0/searches", + payload, + timeout=90, + ) + break + except ApiError as error: + if error.status == 429 and attempt < 3: + delay = 20 * (attempt + 1) + LOG.warning("slskd is busy (HTTP 429); retrying search in %ss", delay) + time.sleep(delay) + continue + raise + + if not isinstance(created, dict) or not created.get("id"): + raise ApiError(500, str(created), "slskd did not return a search id") + + search_id = str(created["id"]) + deadline = time.monotonic() + max(75, search_timeout * 4 + 30) + last_state = "" + search: dict[str, Any] = created + + while time.monotonic() < deadline: + search = self.request( + "GET", + f"/api/v0/searches/{urllib.parse.quote(search_id)}", + timeout=30, + ) + if not isinstance(search, dict): + break + last_state = str(search.get("state") or "") + if search.get("isComplete") or "Completed" in last_state: + break + if "Errored" in last_state: + raise ApiError(500, last_state, f"search failed: {last_state}") + time.sleep(1) + else: + try: + self.request( + "PUT", + f"/api/v0/searches/{urllib.parse.quote(search_id)}", + timeout=30, + ) + except ApiError: + pass + raise ApiError(0, last_state, f"search {search_id} did not complete in time") + + responses = self.request( + "GET", + f"/api/v0/searches/{urllib.parse.quote(search_id)}/responses", + timeout=120, + ) + if not isinstance(responses, list): + responses = [] + + return { + "id": search_id, + "state": last_state, + "responses": responses, + "response_count": int(search.get("responseCount") or len(responses)), + "file_count": int(search.get("fileCount") or 0), + "elapsed": time.monotonic() - started, + } + + def delete_search(self, search_id: str) -> None: + try: + self.request( + "DELETE", + f"/api/v0/searches/{urllib.parse.quote(search_id)}", + timeout=30, + ) + except ApiError: + LOG.debug("Could not delete search %s", search_id) + + # -- downloads --------------------------------------------------------- + + def destination_has_files(self, destination: str) -> bool: + if destination in self._destination_cache: + return self._destination_cache[destination] + + encoded = base64.b64encode(destination.encode("utf-8")).decode("ascii") + path = "/api/v0/files/downloads/directories/" + urllib.parse.quote( + encoded, + safe="", + ) + + exists = False + try: + listing = self.request("GET", path, timeout=30) + if isinstance(listing, dict): + files = listing.get("files") or [] + exists = any( + isinstance(item, dict) + and item.get("name") + and not str(item.get("name")).startswith(".") + for item in files + ) + except ApiError as error: + if error.status not in {404, 403, 401}: + LOG.debug("Could not check destination %s: %s", destination, error) + + self._destination_cache[destination] = exists + return exists + + def enqueue_batch( + self, + username: str, + filename: str, + size: int, + destination: str, + search_id: Optional[str] = None, + ) -> dict[str, Any]: + payload: dict[str, Any] = { + "username": username, + "files": [{"filename": filename, "size": int(size)}], + "options": {"destination": destination}, + } + if search_id: + payload["searchId"] = search_id + + response = self.request( + "POST", + "/api/v0/transfers/downloads/batches", + payload, + timeout=120, + ) + if not isinstance(response, dict): + raise ApiError(500, str(response), "unexpected batch response") + return response + + def get_download(self, username: str, transfer_id: str) -> Optional[dict[str, Any]]: + path = ( + "/api/v0/transfers/downloads/" + + urllib.parse.quote(username, safe="") + + "/" + + urllib.parse.quote(transfer_id, safe="") + ) + try: + download = self.request("GET", path, timeout=30) + except ApiError: + return None + return download if isinstance(download, dict) else None + + +# --------------------------------------------------------------------------- +# candidate evaluation +# --------------------------------------------------------------------------- + + +@dataclass +class Candidate: + username: str + filename: str + size: int + extension: str + length: Optional[float] + bit_depth: Optional[int] + sample_rate: Optional[int] + bitrate: Optional[int] + is_lossless: bool + has_free_upload_slot: bool = False + queue_length: int = 0 + upload_speed: int = 0 + locked: bool = False + search_id: Optional[str] = None + search_query: str = "" + implied_kbps: Optional[float] = None + score: float = 0.0 + reasons: list[str] = field(default_factory=list) + warnings: list[str] = field(default_factory=list) + + @property + def path_text(self) -> str: + return self.filename.replace("\\", "/") + + @property + def display_format(self) -> str: + if self.is_lossless: + parts = [self.extension.upper() or "lossless"] + if self.bit_depth: + parts.append(f"{self.bit_depth}-bit") + if self.sample_rate: + parts.append(f"{self.sample_rate / 1000:g} kHz") + return " / ".join(parts) + bitrate = self.bitrate or self.implied_kbps + return f"{self.extension.upper() or 'lossy'}" + ( + f" ~{int(bitrate)} kbps" if bitrate else "" + ) + + +def make_candidate( + response: dict[str, Any], + file_info: dict[str, Any], + *, + locked: bool, + search_id: Optional[str], + search_query: str, +) -> Optional[Candidate]: + username = str(response.get("username") or "").strip() + filename = str(file_info.get("filename") or "").strip() + if not username or not filename: + return None + + extension = filename.rsplit(".", 1)[-1].casefold() if "." in filename else "" + if extension not in AUDIO_EXTENSIONS: + return None + + if any(part == ".." for part in filename.replace("\\", "/").split("/")): + return None + + size = parse_int(file_info.get("size")) or 0 + length = parse_float(file_info.get("length")) + bit_depth = parse_int(file_info.get("bitDepth")) or None + sample_rate = parse_int(file_info.get("sampleRate")) or None + bitrate = parse_int(file_info.get("bitRate")) or None + + implied_kbps = None + if length and size: + implied_kbps = size * 8 / length / 1000 + + is_lossless = extension in LOSSLESS_EXTENSIONS + if extension == "m4a": + is_lossless = bool( + (bit_depth and sample_rate) + and (bitrate is None or bitrate >= 500) + and (implied_kbps is None or implied_kbps >= 500) + ) + + if extension == "mp3" and bitrate is None and implied_kbps: + bitrate = int(round(implied_kbps)) + + return Candidate( + username=username, + filename=filename, + size=size, + extension=extension, + length=length, + bit_depth=bit_depth, + sample_rate=sample_rate, + bitrate=bitrate, + is_lossless=is_lossless, + has_free_upload_slot=bool(response.get("hasFreeUploadSlot")), + queue_length=parse_int(response.get("queueLength")) or 0, + upload_speed=parse_int(response.get("uploadSpeed")) or 0, + locked=locked, + search_id=search_id, + search_query=search_query, + implied_kbps=implied_kbps, + ) + + +def detect_versions(text: str) -> set[str]: + normalized = normalize_text(text) + found: set[str] = set() + for family, patterns in VERSION_PATTERNS.items(): + for pattern in patterns: + if re.search(rf"\b{re.escape(normalize_text(pattern))}\b", normalized): + found.add(family) + break + return found + + +def nearest_common_lossy_bitrate(kbps: float) -> Optional[int]: + for bitrate in COMMON_LOSSY_BITRATES: + if abs(kbps - bitrate) <= max(4.0, bitrate * 0.025): + return bitrate + return None + + +def extract_filename_track_number(filename: str) -> Optional[int]: + name = Path(filename.replace("\\", "/")).name + match = re.match( + r"^\s*(?:cd\s*\d+\s*[-_. ]*)?(\d{1,3})[\s._-]", + name, + flags=re.IGNORECASE, + ) + return parse_int(match.group(1)) if match else None + + +def evaluate_candidate(candidate: Candidate, track: Track, args: argparse.Namespace) -> bool: + """Score a candidate in place; return False if it should be rejected.""" + filename_text = candidate.path_text + filename_stem = Path(filename_text).stem + + if SUSPICIOUS_WORDS_RE.search(filename_text): + return False + + if candidate.locked and not args.allow_locked: + return False + + # Match the title against the filename itself, not the whole path. Album + # folders often contain the album name, which would otherwise make every + # file in a "Title Track" album match that title. + title_tokens = set(content_tokens(track.title)) + title_overlap = token_coverage(track.title, filename_stem) + exact_title = bool( + normalize_text(track.title) + and normalize_text(track.title) in normalize_text(filename_stem) + ) + fuzzy = fuzzy_ratio(track.title, filename_stem) + + required_overlap = 1.0 if len(title_tokens) <= 1 else 0.6 + if title_overlap < required_overlap and not exact_title and fuzzy < 0.84: + return False + + artist_overlap = token_coverage(track.artist, filename_text) if track.artist else 0.0 + album_overlap = token_coverage(track.album, filename_text) if track.album else 0.0 + + source_versions = detect_versions(f"{track.title} {track.album}") + candidate_versions = detect_versions(filename_text) + + score = 0.0 + + # Format / target quality ------------------------------------------------ + if candidate.is_lossless: + if candidate.extension == "flac": + score += 60 + candidate.reasons.append("FLAC") + elif candidate.extension in {"alac", "ape", "wv"}: + score += 52 + candidate.reasons.append(candidate.extension.upper()) + else: + score += 42 + candidate.reasons.append(candidate.extension.upper() or "lossless") + + if candidate.bit_depth == 16 and candidate.sample_rate == 44100: + score += 45 + candidate.reasons.append("ideal 16-bit/44.1 kHz") + elif candidate.bit_depth == 16 and candidate.sample_rate == 48000: + score += 35 + candidate.reasons.append("16-bit/48 kHz") + elif candidate.bit_depth == 24 and candidate.sample_rate in {44100, 48000}: + score += 32 + candidate.reasons.append("24-bit CD-rate") + elif candidate.sample_rate in {88200, 96000}: + score += 25 + candidate.reasons.append(f"{candidate.sample_rate / 1000:g} kHz") + elif candidate.bit_depth or candidate.sample_rate: + score += 15 + else: + score += 20 + candidate.warnings.append("sample rate/bit depth missing from search result") + + if candidate.bit_depth: + if candidate.bit_depth < 16: + score -= 15 + candidate.warnings.append(f"unusually low bit depth ({candidate.bit_depth}-bit)") + elif candidate.bit_depth > 24: + score -= 10 + candidate.warnings.append(f"unusually high bit depth ({candidate.bit_depth}-bit)") + + if candidate.sample_rate: + if candidate.sample_rate not in { + 44100, 48000, 88200, 96000, 176400, 192000, + }: + score -= 8 + candidate.warnings.append( + f"unusual sample rate ({candidate.sample_rate / 1000:g} kHz)" + ) + if candidate.bit_depth == 16 and candidate.sample_rate > 48000: + score -= 18 + candidate.warnings.append( + "16-bit audio above 48 kHz is unusual (possible upscale)" + ) + + # Target bonus. + if candidate.sample_rate == 44100 and candidate.bit_depth == 16: + score += 10 + elif candidate.sample_rate == 44100: + score += 4 + + # Capacity / transcode consistency. + if candidate.implied_kbps is not None: + kbps = candidate.implied_kbps + candidate.reasons.append(f"~{int(kbps)} kbps") + + if candidate.length and candidate.length >= 30 and kbps < args.min_lossless_kbps: + candidate.warnings.append( + f"average bitrate ~{int(kbps)} kbps is below the lossless minimum" + ) + return False + + if candidate.bit_depth and candidate.sample_rate: + pcm_capacity_kbps = candidate.sample_rate * candidate.bit_depth * 2 / 1000 + if kbps > pcm_capacity_kbps * 1.18: + candidate.warnings.append( + "size/bitrate exceeds the capacity implied by the metadata" + ) + return False + + if kbps < pcm_capacity_kbps * 0.12: + score -= 8 + candidate.warnings.append( + "very low bitrate for the reported lossless format" + ) + + suspicious_bitrate = nearest_common_lossy_bitrate(kbps) + if suspicious_bitrate and kbps < 380: + score -= 25 + candidate.warnings.append( + f"average bitrate is close to {suspicious_bitrate} kbps, " + "which can indicate a lossy transcode" + ) + + if ( + candidate.sample_rate + and candidate.sample_rate <= 48000 + and (candidate.bit_depth or 16) <= 16 + and kbps > 1500 + ): + score -= 12 + candidate.warnings.append( + "implausibly high bitrate for 16-bit CD audio" + ) + + if re.search(r"\b(?:mp3|aac|ogg|opus|m4a)\b", filename_stem, re.I): + score -= 15 + candidate.warnings.append( + "path mentions a lossy format despite lossless extension" + ) + + else: + if not args.allow_lossy: + return False + if track.is_lossless: + return False + + bitrate = candidate.bitrate or candidate.implied_kbps or 0 + if track.bitrate and bitrate: + if bitrate <= track.bitrate * 1.02: + candidate.warnings.append( + f"lossy bitrate ({int(bitrate)} kbps) is not higher than " + f"the source ({track.bitrate} kbps)" + ) + return False + + if bitrate >= 320: + score += 18 + elif bitrate >= 256: + score += 14 + elif bitrate >= 192: + score += 8 + else: + score += 2 + candidate.reasons.append(f"lossy ~{int(bitrate)} kbps") + candidate.warnings.append("lossy result accepted because --allow-lossy was used") + + if candidate.implied_kbps and candidate.implied_kbps < 64: + return False + + # Title / artist / album matching --------------------------------------- + title_bonus = 50 * min(1.0, max(title_overlap, 1.0 if exact_title else 0.0)) + if fuzzy >= 0.84: + title_bonus = max(title_bonus, 40 * fuzzy) + score += title_bonus + candidate.reasons.append(f"title match {max(title_overlap, fuzzy):.0%}") + + if track.artist: + score += 30 * artist_overlap + if artist_overlap: + candidate.reasons.append(f"artist match {artist_overlap:.0%}") + elif artist_overlap == 0: + candidate.warnings.append("artist not found in result path") + + if track.album and album_overlap: + score += 12 * album_overlap + candidate.reasons.append(f"album match {album_overlap:.0%}") + + # Version compatibility -------------------------------------------------- + extra_hard = candidate_versions - source_versions - {"original"} + extra_soft = (candidate_versions & SOFT_VERSION_FAMILIES) - source_versions + missing_hard = source_versions - candidate_versions - {"original"} + if extra_hard: + score -= 35 + candidate.warnings.append( + "result has a different version: " + ", ".join(sorted(extra_hard)) + ) + if extra_soft: + score -= 12 + candidate.warnings.append( + "result has a different edit/version: " + ", ".join(sorted(extra_soft)) + ) + if missing_hard: + score -= 25 + candidate.warnings.append( + "source version tag missing from result: " + ", ".join(sorted(missing_hard)) + ) + + # Duration --------------------------------------------------------------- + if track.duration and candidate.length: + tolerance = max( + args.duration_tolerance, + track.duration * args.duration_tolerance_percent / 100, + ) + delta = abs(track.duration - candidate.length) + if delta > tolerance: + candidate.warnings.append( + f"duration differs by {delta:.0f}s (limit {tolerance:.0f}s)" + ) + return False + duration_score = max(0.0, 1.0 - delta / tolerance) + score += 12 * duration_score + candidate.reasons.append(f"duration Δ{delta:.1f}s") + elif track.duration and not candidate.length: + candidate.warnings.append("duration missing from search result") + elif candidate.length and not track.duration: + candidate.reasons.append(f"duration {candidate.length:.0f}s") + + # Track number ----------------------------------------------------------- + if track.track_number is not None: + candidate_number = extract_filename_track_number(filename_text) + if candidate_number is not None: + if candidate_number == track.track_number: + score += 5 + else: + score -= 5 + + # Availability ----------------------------------------------------------- + if candidate.has_free_upload_slot: + score += 8 + candidate.reasons.append("free upload slot") + + if candidate.upload_speed > 0: + score += min(8.0, candidate.upload_speed / 1_000_000 * 2) + candidate.reasons.append( + f"upload {candidate.upload_speed / 1_000_000:.1f} MB/s" + ) + + if candidate.queue_length > 0: + penalty = min(15.0, 5 * math.log10(1 + candidate.queue_length)) + score -= penalty + candidate.warnings.append(f"queue length {candidate.queue_length}") + + candidate.score = round(score, 2) + return candidate.score >= args.min_score + + +def rank_candidates( + track: Track, + responses: list[dict[str, Any]], + args: argparse.Namespace, + *, + search_id: Optional[str] = None, + search_query: str = "", +) -> list[Candidate]: + seen: set[tuple[str, str]] = set() + candidates: list[Candidate] = [] + + for response in responses: + if not isinstance(response, dict): + continue + collections = [("files", False)] + if args.allow_locked: + collections.append(("lockedFiles", True)) + + for collection_name, locked in collections: + for file_info in response.get(collection_name) or []: + if not isinstance(file_info, dict): + continue + candidate = make_candidate( + response, + file_info, + locked=locked, + search_id=search_id, + search_query=search_query, + ) + if candidate is None: + continue + + key = ( + candidate.username.casefold(), + normalize_text(candidate.filename), + ) + if key in seen: + continue + seen.add(key) + + if evaluate_candidate(candidate, track, args): + candidates.append(candidate) + + candidates.sort( + key=lambda item: ( + -item.score, + item.queue_length, + -item.upload_speed, + item.username.casefold(), + item.filename.casefold(), + ) + ) + return candidates + + +def select_top(candidates: list[Candidate], top_n: int, max_per_user: int) -> list[Candidate]: + selected: list[Candidate] = [] + selected_ids: set[int] = set() + per_user: Counter[str] = Counter() + + for candidate in candidates: + if len(selected) >= top_n: + break + user_key = candidate.username.casefold() + if per_user[user_key] >= max_per_user: + continue + selected.append(candidate) + selected_ids.add(id(candidate)) + per_user[user_key] += 1 + + if len(selected) < top_n: + for candidate in candidates: + if len(selected) >= top_n: + break + if id(candidate) in selected_ids: + continue + selected.append(candidate) + selected_ids.add(id(candidate)) + + return selected + + +# --------------------------------------------------------------------------- +# filesystem scanning +# --------------------------------------------------------------------------- + + +def is_audio_file(path: Path) -> bool: + return path.suffix.casefold().lstrip(".") in AUDIO_EXTENSIONS + + +def prepare_excludes(specs: list[str]) -> tuple[list[Path], list[str]]: + exact: list[Path] = [] + globs: list[str] = [] + for spec in specs: + if not spec: + continue + expanded = os.path.expanduser(spec) + if any(character in expanded for character in "*?["): + globs.append(expanded.replace("\\", "/")) + else: + exact.append(Path(expanded).resolve()) + return exact, globs + + +def is_excluded(path: Path, exact: list[Path], globs: list[str]) -> bool: + resolved = path.resolve() + for excluded_path in exact: + if resolved == excluded_path or excluded_path in resolved.parents: + return True + + if not globs: + return False + + posix_path = resolved.as_posix() + try: + relative_path = resolved.relative_to(Path.cwd().resolve()).as_posix() + except ValueError: + relative_path = posix_path + + for pattern in globs: + normalized_pattern = pattern.replace("\\", "/") + if ( + _fnmatch(posix_path, normalized_pattern) + or _fnmatch(relative_path, normalized_pattern) + or _fnmatch(path.name, normalized_pattern) + ): + return True + for parent in resolved.parents: + if _fnmatch(parent.as_posix(), normalized_pattern): + return True + return False + + +def _fnmatch(path: str, pattern: str) -> bool: + import fnmatch + + return fnmatch.fnmatch(path, pattern) or fnmatch.fnmatch(path.casefold(), pattern.casefold()) + + +def collect_audio_files( + includes: list[str], + excludes: list[str], +) -> tuple[list[tuple[Path, Path]], list[str]]: + exact_excludes, glob_excludes = prepare_excludes(excludes) + include_paths = [Path(os.path.expanduser(item)).resolve() for item in includes] + roots: list[Path] = [] + + errors: list[str] = [] + for include in include_paths: + if not include.exists(): + errors.append(f"include path does not exist: {include}") + continue + roots.append(include if include.is_dir() else include.parent) + + seen: set[Path] = set() + collected: list[tuple[Path, Path]] = [] + + for include in include_paths: + if not include.exists(): + continue + + if include.is_file(): + if not is_audio_file(include): + errors.append(f"not a supported audio file: {include}") + elif not is_excluded(include, exact_excludes, glob_excludes): + resolved = include.resolve() + if resolved not in seen: + seen.add(resolved) + collected.append((resolved, include.parent)) + continue + + for directory, directory_names, filenames in os.walk(include): + directory_path = Path(directory) + kept_directories: list[str] = [] + for name in sorted(directory_names): + child = directory_path / name + if name.startswith("."): + continue + if is_excluded(child, exact_excludes, glob_excludes): + continue + kept_directories.append(name) + directory_names[:] = kept_directories + + for name in sorted(filenames): + if name.startswith("."): + continue + path = directory_path / name + if not is_audio_file(path): + continue + if is_excluded(path, exact_excludes, glob_excludes): + continue + resolved = path.resolve() + if resolved in seen: + continue + seen.add(resolved) + collected.append((resolved, _choose_root(resolved, roots))) + + collected.sort(key=lambda item: str(item[0]).casefold()) + return collected, errors + + +def _choose_root(path: Path, roots: list[Path]) -> Path: + candidates = [] + for root in roots: + if path == root or root in path.parents: + candidates.append(root) + if not candidates: + return path.parent + return max(candidates, key=lambda root: len(root.parts)) + + +# --------------------------------------------------------------------------- +# search + download orchestration +# --------------------------------------------------------------------------- + + +def search_with_retry( + client: SlskdClient, + query: str, + args: argparse.Namespace, +) -> dict[str, Any]: + attempts = max(0, args.search_retries) + 1 + + # If several searches in a row finish instantly with zero responses, + # retrying is just going to burn time. Keep issuing one search per query + # (so a genuine no-result query still works) but stop the retries. + if getattr(client, "instant_zero_streak", 0) >= 2: + attempts = 1 + + last_result: Optional[dict[str, Any]] = None + last_error: Optional[Exception] = None + + for attempt in range(attempts): + try: + result = client.search( + query, + search_timeout=args.search_timeout, + response_limit=args.response_limit, + file_limit=args.file_limit, + ) + except ApiError as error: + last_error = error + if error.status in {429, 0} and attempt + 1 < attempts: + delay = args.retry_delay * (attempt + 1) + LOG.warning("Search failed (%s); retrying in %ss", error, delay) + time.sleep(delay) + continue + raise + + last_result = result + if result["response_count"] > 0: + client.instant_zero_streak = 0 + return result + + # A zero-result search that finishes in a fraction of the timeout is + # usually a sign that Soulseek is throttling search requests. + instant = result["elapsed"] < max(3.0, args.search_timeout * 0.25) + if instant: + client.instant_zero_streak = getattr(client, "instant_zero_streak", 0) + 1 + else: + client.instant_zero_streak = 0 + + if attempt + 1 < attempts and instant: + delay = args.retry_delay * (attempt + 1) + LOG.warning( + "Search for %r returned 0 responses in %.1fs (possible rate limit); " + "retrying in %ss", + query, + result["elapsed"], + delay, + ) + time.sleep(delay) + continue + + return result + + if last_result is not None: + return last_result + if last_error is not None: + raise last_error + raise ApiError(0, "search failed") + + +def destination_for(track: Track, candidate: Candidate, rank: int, args: argparse.Namespace) -> str: + prefix_parts = [ + safe_segment(part, fallback="upgrades") + for part in args.destination_prefix.replace("\\", "/").split("/") + if part.strip() + ] or ["upgrades"] + + try: + relative_parent = track.path.parent.relative_to(track.root) + except ValueError: + relative_parent = Path() + + relative_parts = list(relative_parent.parts) if relative_parent.parts else [] + + if args.flat: + parts = [*prefix_parts] + elif args.mirror: + parts = [*prefix_parts, *relative_parts] + else: + parts = [ + *prefix_parts, + *relative_parts, + safe_segment(track.path.stem, fallback="track"), + f"{rank:02d}-{safe_segment(candidate.username, fallback='user')}", + ] + + return safe_destination(parts) + + +def enqueue_download( + client: SlskdClient, + track: Track, + candidate: Candidate, + rank: int, + args: argparse.Namespace, +) -> dict[str, Any]: + destination = destination_for(track, candidate, rank, args) + + # In mirror/flat mode many downloads share one destination directory, so + # "directory has files" is not a safe indication that this candidate was + # already downloaded. Only use the check for the unique per-candidate + # destinations created by the default layout. + if ( + args.skip_existing + and not args.flat + and not args.mirror + and client.destination_has_files(destination) + ): + return { + "skipped": True, + "reason": "destination already contains files", + "destination": destination, + "batch_id": None, + "transfer_ids": [], + } + + search_id = candidate.search_id + if args.delete_searches or not search_id or not GUID_RE.match(search_id): + search_id = None + + try: + response = client.enqueue_batch( + username=candidate.username, + filename=candidate.filename, + size=candidate.size, + destination=destination, + search_id=search_id, + ) + except ApiError as error: + return { + "skipped": False, + "destination": destination, + "error": str(error), + "batch_id": None, + "transfer_ids": [], + } + + batch = response.get("batch") or {} + failures = response.get("failures") or [] + transfer_ids = [ + str(transfer.get("id")) + for transfer in batch.get("transfers") or [] + if transfer.get("id") + ] + + if failures: + messages = [ + str(failure.get("message") or failure.get("filename") or failure) + for failure in failures + ] + return { + "skipped": False, + "destination": destination, + "error": "; ".join(messages), + "batch_id": batch.get("id"), + "transfer_ids": transfer_ids, + } + + return { + "skipped": False, + "destination": destination, + "error": None, + "batch_id": batch.get("id"), + "transfer_ids": transfer_ids, + } + + +def wait_for_downloads( + client: SlskdClient, + downloads: list[dict[str, Any]], + timeout: int, +) -> None: + pending = [ + item + for item in downloads + if item.get("transfer_ids") and not item.get("error") and not item.get("skipped") + ] + if not pending: + return + + deadline = time.monotonic() + timeout + LOG.info("Waiting for %d download(s) to finish...", len(pending)) + + while pending and time.monotonic() < deadline: + still_pending: list[dict[str, Any]] = [] + for item in pending: + transfer_id = item["transfer_ids"][0] + download = client.get_download(item["username"], transfer_id) + state = str((download or {}).get("state") or "") + item["state"] = state + + if not state or "Completed" not in state: + still_pending.append(item) + else: + percent = (download or {}).get("percentComplete") + LOG.info( + " %s -> %s%s", + item["filename"], + state, + f" ({percent}%)" if percent is not None else "", + ) + + pending = still_pending + if pending: + time.sleep(3) + + for item in pending: + item["state"] = item.get("state") or "not completed before timeout" + LOG.warning("Download did not finish before timeout: %s", item["filename"]) + + +# --------------------------------------------------------------------------- +# reporting / CLI +# --------------------------------------------------------------------------- + + +def candidate_to_dict(candidate: Candidate, extra: Optional[dict[str, Any]] = None) -> dict[str, Any]: + data: dict[str, Any] = { + "username": candidate.username, + "filename": candidate.filename, + "size": candidate.size, + "format": candidate.display_format, + "score": candidate.score, + "reasons": candidate.reasons, + "warnings": candidate.warnings, + "search_query": candidate.search_query, + } + if extra: + data.update(extra) + return data + + +def format_candidate_line(index: int, candidate: Candidate) -> str: + warnings = "; ".join(candidate.warnings) + line = ( + f" {index}. score={candidate.score:6.1f} " + f"{candidate.username} [{candidate.display_format}] " + f"{candidate.filename}" + ) + if warnings: + line += f"\n warning: {warnings}" + return line + + +def build_report( + tracks: list[Track], + selections: dict[str, list[Candidate]], + downloads: dict[str, list[dict[str, Any]]], + groups: list[SearchGroup], + args: argparse.Namespace, + skipped_tracks: Optional[list[Track]] = None, +) -> dict[str, Any]: + track_reports = [] + for track in tracks: + selected = selections.get(str(track.path), []) + download_items = downloads.get(str(track.path), []) + by_download = { + (item.get("username"), item.get("filename")): item + for item in download_items + if item.get("filename") + } + + candidates_report = [] + for candidate in selected: + extra = by_download.get((candidate.username, candidate.filename)) + item = candidate_to_dict(candidate) + if extra: + item.update( + { + "destination": extra.get("destination"), + "batch_id": extra.get("batch_id"), + "transfer_ids": extra.get("transfer_ids"), + "error": extra.get("error"), + "skipped": extra.get("skipped"), + "state": extra.get("state"), + } + ) + candidates_report.append(item) + + track_reports.append( + { + "path": str(track.path), + "artist": track.artist, + "album": track.album, + "title": track.title, + "source_quality": source_quality_text(track), + "search_query": track.search_query, + "search_mode": track.search_mode, + "skip_reason": track.skip_reason or None, + "candidates": candidates_report, + } + ) + + return { + "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "slskd_url": args.url, + "includes": args.include, + "excludes": args.exclude, + "dry_run": args.dry_run, + "scan_only": args.scan_only, + "top": args.top, + "tracks": track_reports, + "skipped": [ + { + "path": str(track.path), + "artist": track.artist, + "album": track.album, + "title": track.title, + "source_quality": source_quality_text(track), + "reason": track.skip_reason, + } + for track in (skipped_tracks or []) + ], + "searches": [ + { + "query": group.query, + "mode": group.label, + "search_id": group.search_id, + "response_count": group.response_count, + "file_count": group.file_count, + "elapsed_seconds": round(group.elapsed, 3), + "error": group.error, + } + for group in groups + ], + } + + +def write_report(path: str, report: dict[str, Any]) -> None: + output = Path(os.path.expanduser(path)) + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text( + json.dumps(report, indent=2, ensure_ascii=False), + encoding="utf-8", + ) + + +def parse_args(argv: Optional[list[str]] = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "Find higher-quality versions of local music files on Soulseek via " + "slskd and enqueue the best candidates on the server." + ), + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=( + "Environment variables: SLSKD_URL, SLSKD_USERNAME, SLSKD_PASSWORD, " + "SLSKD_API_KEY.\n\n" + "Examples:\n" + " slskd_music_upgrade.py --include ~/Music/Album --dry-run\n" + " slskd_music_upgrade.py -i ~/Music/A -i ~/Music/B -x '**/Bonus/**' --yes\n" + ), + ) + + parser.add_argument( + "include_paths", + nargs="*", + help="Files or directories to scan (can also be given with --include).", + ) + parser.add_argument( + "-i", "--include", + action="append", + default=[], + metavar="PATH", + help="File or directory to scan. Repeat for multiple paths.", + ) + parser.add_argument( + "-x", "--exclude", + action="append", + default=[], + metavar="PATH_OR_GLOB", + help="File/directory path or glob to skip. Repeat for multiple exclusions.", + ) + + parser.add_argument( + "--url", + default=os.environ.get("SLSKD_URL", "http://localhost:5030"), + help="Base URL of the slskd instance (default: %(default)s).", + ) + parser.add_argument( + "--username", + default=os.environ.get("SLSKD_USERNAME"), + help="slskd username (or SLSKD_USERNAME).", + ) + parser.add_argument( + "--password", + default=os.environ.get("SLSKD_PASSWORD"), + help="slskd password (or SLSKD_PASSWORD).", + ) + parser.add_argument( + "--api-key", + default=os.environ.get("SLSKD_API_KEY"), + help="slskd API key (or SLSKD_API_KEY); alternative to username/password.", + ) + + parser.add_argument( + "-n", "--top", + type=int, + default=3, + help="Number of candidates to download per track (default: %(default)s).", + ) + parser.add_argument( + "--max-per-user", + type=int, + default=1, + help=( + "Prefer at most this many candidates from the same uploader before " + "filling remaining slots from duplicates (default: %(default)s)." + ), + ) + parser.add_argument( + "--destination-prefix", + default="slskd-upgrades", + help=( + "Relative destination directory under slskd's download root " + "(default: %(default)s)." + ), + ) + parser.add_argument( + "--mirror", + action="store_true", + help=( + "Mirror the source directory structure under the destination prefix " + "instead of creating a per-track/uploader subdirectory." + ), + ) + parser.add_argument( + "--flat", + action="store_true", + help="Put every download directly under the destination prefix.", + ) + parser.add_argument( + "--skip-existing", + action=argparse.BooleanOptionalAction, + default=True, + help=( + "Skip a destination that already contains files, to make reruns " + "idempotent (default: %(default)s)." + ), + ) + + parser.add_argument( + "--scan-only", + action="store_true", + help=( + "Scan metadata and print search queries/skip reasons without " + "contacting slskd or searching." + ), + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Search and show the plan, but do not enqueue downloads.", + ) + parser.add_argument( + "-y", "--yes", + action="store_true", + help="Do not ask for confirmation before enqueueing downloads.", + ) + parser.add_argument( + "--force", + action="store_true", + help="Search even for files that are already lossless CD-quality or better.", + ) + parser.add_argument( + "--allow-lossy", + action="store_true", + help="Allow lossy candidates when no lossless candidate is available.", + ) + parser.add_argument( + "--allow-locked", + action="store_true", + help="Allow files that peers report as locked.", + ) + parser.add_argument( + "--min-score", + type=float, + default=100.0, + help="Minimum candidate score (default: %(default)s).", + ) + parser.add_argument( + "--min-lossless-kbps", + type=float, + default=350.0, + help=( + "Reject lossless files whose average bitrate is below this value; " + "this catches many low-bitrate transcodes (default: %(default)s)." + ), + ) + parser.add_argument( + "--duration-tolerance", + type=float, + default=8.0, + help="Absolute duration tolerance in seconds (default: %(default)s).", + ) + parser.add_argument( + "--duration-tolerance-percent", + type=float, + default=4.0, + help="Duration tolerance as a percentage of source duration (default: %(default)s).", + ) + + parser.add_argument( + "--search-mode", + choices=("auto", "album", "track"), + default="auto", + help=( + "auto: per-track for flat directories/file lists, album searches " + "for nested library folders; album: always prefer album searches; " + "track: always search per track (default: %(default)s)." + ), + ) + parser.add_argument( + "--album-search-min-tracks", + type=int, + default=2, + help="Minimum tracks needed to use an album search (default: %(default)s).", + ) + parser.add_argument( + "--search-timeout", + type=int, + default=15, + help="Soulseek search timeout in seconds (default: %(default)s).", + ) + parser.add_argument( + "--response-limit", + type=int, + default=150, + help="Maximum number of search responses to accept (default: %(default)s).", + ) + parser.add_argument( + "--file-limit", + type=int, + default=5000, + help="Maximum number of search result files to accept (default: %(default)s).", + ) + parser.add_argument( + "--search-delay", + type=float, + default=8.0, + help="Delay in seconds between searches (default: %(default)s).", + ) + parser.add_argument( + "--search-retries", + type=int, + default=1, + help=( + "Extra attempts for a zero-result search that completed suspiciously " + "quickly (default: %(default)s)." + ), + ) + parser.add_argument( + "--retry-delay", + type=float, + default=30.0, + help="Base delay for search retries in seconds (default: %(default)s).", + ) + parser.add_argument( + "--batch-delay", + type=float, + default=1.0, + help="Delay in seconds between download enqueue requests (default: %(default)s).", + ) + parser.add_argument( + "--limit", + type=int, + default=None, + help="Process at most this many source tracks (useful for testing).", + ) + parser.add_argument( + "--wait", + action="store_true", + help="Wait for enqueued transfers to complete.", + ) + parser.add_argument( + "--wait-timeout", + type=int, + default=900, + help="Maximum seconds to wait for transfers with --wait (default: %(default)s).", + ) + parser.add_argument( + "--report", + default=None, + metavar="PATH", + help="Write a JSON report to this path.", + ) + parser.add_argument( + "--delete-searches", + action="store_true", + help="Delete search records from slskd after reading their responses.", + ) + parser.add_argument( + "-v", "--verbose", + action="store_true", + help="Enable debug logging.", + ) + + args = parser.parse_args(argv) + + args.include = [*args.include_paths, *args.include] + if not args.include: + parser.error("at least one --include path (or positional path) is required") + if args.top < 1: + parser.error("--top must be at least 1") + if args.max_per_user < 1: + parser.error("--max-per-user must be at least 1") + if not args.destination_prefix.strip(): + parser.error("--destination-prefix must not be empty") + if args.search_timeout < 5: + LOG.warning("--search-timeout below 5 seconds is not allowed by slskd; using 5") + args.search_timeout = 5 + if args.mirror and args.flat: + parser.error("--mirror and --flat are mutually exclusive") + if ( + not args.scan_only + and not args.api_key + and not (args.username and args.password) + ): + parser.error("provide --username and --password, or --api-key") + + return args + + +def main(argv: Optional[list[str]] = None) -> int: + args = parse_args(argv) + + logging.basicConfig( + level=logging.DEBUG if args.verbose else logging.INFO, + format="%(levelname)-7s %(message)s", + ) + + LOG.info("Scanning %d include path(s)...", len(args.include)) + file_entries, scan_errors = collect_audio_files(args.include, args.exclude) + for error in scan_errors: + LOG.error("%s", error) + if scan_errors and not file_entries: + return 2 + + if args.limit is not None: + file_entries = file_entries[: max(0, args.limit)] + + if not file_entries: + LOG.error("No audio files found in the included paths") + return 2 + + LOG.info("Found %d audio file(s); reading metadata...", len(file_entries)) + + tracks: list[Track] = [] + skipped: list[Track] = [] + for index, (path, root) in enumerate(file_entries, 1): + if index % 50 == 0 or index == len(file_entries): + LOG.debug(" metadata %d/%d", index, len(file_entries)) + track = read_track(path, root) + should_search, reason = needs_upgrade(track, args.force) + if not should_search: + track.skip_reason = reason + skipped.append(track) + continue + tracks.append(track) + + LOG.info( + "%d track(s) need an upgrade; %d already lossless/skipped", + len(tracks), + len(skipped), + ) + if not tracks: + LOG.info("Nothing to do.") + return 0 + + effective_search_mode = args.search_mode + if args.search_mode == "auto" and all( + track.path.parent == track.root for track in tracks + ): + # A flat list of loose tracks (or a single album folder included as + # the root) is better handled with precise per-track searches. Album + # tags in such folders are often arbitrary compilation/catalog names. + effective_search_mode = "track" + LOG.info( + "Input is a flat directory/file list; using per-track searches " + "(use --search-mode album to force album searches)" + ) + + groups = plan_searches(tracks, effective_search_mode, args.album_search_min_tracks) + if not groups: + LOG.error("Could not build any search queries from the selected files") + return 2 + + if args.scan_only: + LOG.info("Scan-only mode; no slskd API calls will be made.") + for track in tracks: + LOG.info( + "SEARCH %-58s query=%r", + track.display_name[:58], + track.search_query, + ) + for track in skipped: + LOG.info( + "SKIP %-58s %s", + track.display_name[:58], + track.skip_reason, + ) + LOG.info( + "Scan complete: %d to search, %d skipped", + len(tracks), + len(skipped), + ) + if args.report: + report = build_report( + tracks, + {}, + {str(track.path): [] for track in tracks}, + groups, + args, + skipped, + ) + write_report(args.report, report) + LOG.info("Report written to %s", args.report) + return 0 + + client = SlskdClient( + args.url, + username=args.username, + password=args.password, + api_key=args.api_key, + ) + + try: + client.ensure_authenticated() + client.check_soulseek_connection() + except ApiError as error: + LOG.error("Could not authenticate to slskd: %s", error) + return 2 + + LOG.info( + "Using %d search(es) for %d track(s) (%s mode)", + len(groups), + len(tracks), + effective_search_mode, + ) + + search_cache: dict[str, dict[str, Any]] = {} + cache_hits = 0 + + for index, group in enumerate(groups, 1): + LOG.info( + "[search %d/%d] %s (%d track%s): %r", + index, + len(groups), + group.label, + len(group.tracks), + "" if len(group.tracks) == 1 else "s", + group.query, + ) + try: + cache_key = group.query.casefold() + if cache_key in search_cache: + result = search_cache[cache_key] + cache_hits += 1 + LOG.info(" -> reusing result from an identical earlier search") + else: + result = search_with_retry(client, group.query, args) + if result["response_count"] > 0: + search_cache[cache_key] = result + group.responses = result["responses"] + group.search_id = result["id"] + group.response_count = result["response_count"] + group.file_count = result["file_count"] + group.elapsed = result["elapsed"] + LOG.info( + " -> %d response(s), %d file(s), %.1fs", + group.response_count, + group.file_count, + group.elapsed, + ) + except ApiError as error: + group.error = str(error) + LOG.error(" -> search failed: %s", error) + + if args.delete_searches and group.search_id: + client.delete_search(group.search_id) + + if index < len(groups) and args.search_delay > 0: + time.sleep(args.search_delay) + + if groups and all( + group.response_count == 0 and group.error is None for group in groups + ): + LOG.warning( + "Every search returned zero responses. This usually means " + "Soulseek is rate-limiting the account, not that the tracks are " + "missing. Wait a while and try again." + ) + + # Rank candidates for every track. Tracks in an album search share the + # same response set, but each track is matched independently. + selections: dict[str, list[Candidate]] = {} + for track in tracks: + group = next((item for item in groups if track in item.tracks), None) + responses = group.responses if group else [] + search_id = group.search_id if group else None + search_query = group.query if group else track.search_query + + candidates = rank_candidates( + track, + responses, + args, + search_id=search_id, + search_query=search_query, + ) + selected = select_top(candidates, args.top, args.max_per_user) + selections[str(track.path)] = selected + + LOG.info( + "%s (%s)", + track.display_name, + source_quality_text(track), + ) + if selected: + for candidate_index, candidate in enumerate(selected, 1): + LOG.info(format_candidate_line(candidate_index, candidate)) + else: + LOG.info(" no acceptable candidates") + + # If an album search did not produce a candidate for some tracks, try a + # more specific per-track search for those tracks. This is done only for + # tracks that actually used an album query, keeping search traffic + # reasonable. + track_groups = { + str(track.path): group for group in groups for track in group.tracks + } + album_missing = [ + track for track in tracks + if not selections.get(str(track.path)) + and not track.skip_reason + and track.search_mode == "album" + ] + + missing_tracks: list[Track] = [] + throttled_skips = 0 + instant_threshold = max(3.0, args.search_timeout * 0.25) + for track in album_missing: + group = track_groups.get(str(track.path)) + if ( + group + and group.error is None + and group.response_count == 0 + and group.elapsed < instant_threshold + ): + # The album search finished instantly with nothing. That is the + # signature of Soulseek rate limiting rather than a missing track, + # so another search now would only add noise. + throttled_skips += 1 + continue + missing_tracks.append(track) + + if throttled_skips: + LOG.warning( + "%d track(s) skipped fallback searches because Soulseek appears " + "to be throttling searches (instant zero-result responses)", + throttled_skips, + ) + + if missing_tracks: + LOG.info( + "%d track(s) had no acceptable album-search candidates; " + "trying per-track searches", + len(missing_tracks), + ) + for index, track in enumerate(missing_tracks, 1): + query = build_track_query(track) + if not query: + continue + LOG.info( + "[fallback %d/%d] %r", + index, + len(missing_tracks), + query, + ) + try: + cache_key = query.casefold() + if cache_key in search_cache: + result = search_cache[cache_key] + cache_hits += 1 + LOG.info(" -> reusing result from an identical earlier search") + else: + result = search_with_retry(client, query, args) + if result["response_count"] > 0: + search_cache[cache_key] = result + group = SearchGroup( + key=("track", str(track.path)), + query=query, + tracks=[track], + responses=result["responses"], + search_id=result["id"], + response_count=result["response_count"], + file_count=result["file_count"], + elapsed=result["elapsed"], + ) + groups.append(group) + + candidates = rank_candidates( + track, + result["responses"], + args, + search_id=result["id"], + search_query=query, + ) + selected = select_top(candidates, args.top, args.max_per_user) + selections[str(track.path)] = selected + track.search_query = query + track.search_mode = "track-fallback" + if selected: + for candidate_index, candidate in enumerate(selected, 1): + LOG.info(format_candidate_line(candidate_index, candidate)) + else: + LOG.info(" no acceptable candidates") + + if args.delete_searches: + client.delete_search(result["id"]) + except ApiError as error: + LOG.error(" -> fallback search failed: %s", error) + + if index < len(missing_tracks) and args.search_delay > 0: + time.sleep(args.search_delay) + + if cache_hits: + LOG.info("Reused %d identical search result(s)", cache_hits) + + total_selected = sum(len(items) for items in selections.values()) + per_track_selected = { + str(track.path): selections.get(str(track.path), []) + for track in tracks + } + + LOG.info( + "Plan complete: %d candidate(s) selected for %d track(s)", + total_selected, + sum(1 for items in per_track_selected.values() if items), + ) + + downloads: dict[str, list[dict[str, Any]]] = {str(track.path): [] for track in tracks} + + if args.dry_run: + if total_selected: + LOG.info("Dry-run destinations:") + for track in tracks: + for rank, candidate in enumerate( + per_track_selected.get(str(track.path), []), 1 + ): + try: + destination = destination_for(track, candidate, rank, args) + except ValueError as error: + destination = f"<invalid: {error}>" + LOG.info( + " %s #%d %s -> %s", + track.display_name, + rank, + candidate.username, + destination, + ) + LOG.info("Dry run; no downloads were enqueued.") + report = build_report(tracks, per_track_selected, downloads, groups, args, skipped) + if args.report: + write_report(args.report, report) + LOG.info("Report written to %s", args.report) + return 0 + + if total_selected == 0: + LOG.warning("No acceptable candidates found; nothing to download.") + report = build_report(tracks, per_track_selected, downloads, groups, args, skipped) + if args.report: + write_report(args.report, report) + return 0 + + if not args.yes: + try: + answer = input( + f"Enqueue {total_selected} download(s) on {args.url}? [y/N] " + ).strip().casefold() + except EOFError: + answer = "" + if answer not in {"y", "yes"}: + LOG.info("Aborted; nothing was enqueued.") + return 0 + + enqueued = 0 + failed = 0 + skipped_existing = 0 + + for track in tracks: + selected = per_track_selected.get(str(track.path), []) + if not selected: + continue + + LOG.info("Enqueueing %s", track.display_name) + for rank, candidate in enumerate(selected, 1): + item = enqueue_download(client, track, candidate, rank, args) + item.update( + { + "username": candidate.username, + "filename": candidate.filename, + } + ) + downloads[str(track.path)].append(item) + + if item.get("skipped"): + skipped_existing += 1 + LOG.info( + " %d. skipped (%s): %s", + rank, + item.get("reason"), + item.get("destination"), + ) + elif item.get("error"): + failed += 1 + LOG.error( + " %d. failed: %s (%s)", + rank, + candidate.username, + item["error"], + ) + else: + enqueued += 1 + LOG.info( + " %d. queued: %s -> %s", + rank, + candidate.username, + item.get("destination"), + ) + + if args.batch_delay > 0: + time.sleep(args.batch_delay) + + if args.wait: + wait_for_downloads( + client, + [item for items in downloads.values() for item in items], + args.wait_timeout, + ) + + LOG.info( + "Done: %d enqueued, %d failed, %d skipped as already present", + enqueued, + failed, + skipped_existing, + ) + + if skipped: + LOG.info( + "%d file(s) were skipped because they are already lossless/CD-quality " + "(use --force to search them anyway)", + len(skipped), + ) + + report = build_report(tracks, per_track_selected, downloads, groups, args, skipped) + if args.report: + write_report(args.report, report) + LOG.info("Report written to %s", args.report) + + return 1 if failed and not enqueued else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) |
