scan.py (9.2 KB)


  1 #!/usr/bin/env python3
  2 """
  3 Scans /mix directory and populates tracks.json with metadata
  4 Supports MP3, M4A, OGG, FLAC, and WAV formats
  5 Automatically manages a virtual environment for dependencies
  6 """
  7 
  8 import os
  9 import sys
 10 import subprocess
 11 import json
 12 from pathlib import Path
 13 
 14 ROOT_DIR = Path(__file__).parent.parent.absolute()
 15 VENV_DIR = ROOT_DIR / "venv"
 16 MIX_DIR = ROOT_DIR / "mix"
 17 OUTPUT_FILE = MIX_DIR / "tracks.json"
 18 
 19 
 20 def setup_venv(packages=("mutagen",)):
 21 	"""Create the shared venv if missing and ensure each package is installed.
 22 	Returns the path to the venv Python interpreter."""
 23 	if sys.platform == "win32":
 24 		pip_path = VENV_DIR / "Scripts" / "pip"
 25 		python_path = VENV_DIR / "Scripts" / "python"
 26 	else:
 27 		pip_path = VENV_DIR / "bin" / "pip"
 28 		python_path = VENV_DIR / "bin" / "python3"
 29 
 30 	if not VENV_DIR.exists() or not python_path.exists():
 31 		if VENV_DIR.exists():
 32 			print("Virtual environment incomplete, recreating...")
 33 			import shutil
 34 			shutil.rmtree(VENV_DIR)
 35 		else:
 36 			print("Creating virtual environment...")
 37 
 38 		try:
 39 			subprocess.check_call([sys.executable, "-m", "venv", str(VENV_DIR)])
 40 			print("Virtual environment created successfully.")
 41 		except subprocess.CalledProcessError as e:
 42 			print(f"Error creating virtual environment: {e}")
 43 			sys.exit(1)
 44 
 45 	if not pip_path.exists():
 46 		print("Installing pip in virtual environment...")
 47 		try:
 48 			subprocess.check_call([str(python_path), "-m", "ensurepip", "--upgrade"])
 49 		except subprocess.CalledProcessError as e:
 50 			print(f"Error ensuring pip: {e}")
 51 			sys.exit(1)
 52 
 53 	for pkg in packages:
 54 		check = subprocess.run(
 55 			[str(python_path), "-c", f"import {pkg}"],
 56 			capture_output=True
 57 		)
 58 		if check.returncode != 0:
 59 			try:
 60 				subprocess.check_call([str(python_path), "-m", "pip", "install", "-q", pkg])
 61 			except subprocess.CalledProcessError:
 62 				print(f"Note: Could not install {pkg} (offline?).\n")
 63 
 64 	return python_path
 65 
 66 
 67 def bootstrap(script_path, packages=("mutagen",), sentinel="--in-venv"):
 68 	"""Ensure the calling script is running inside the shared venv
 69 	with `packages` available. Re-execs through the venv Python on first call;
 70 	returns immediately on the second pass once the sentinel is in argv.
 71 
 72 	Each script that uses this should pass its own __file__ as script_path."""
 73 	if sentinel in sys.argv:
 74 		sys.argv.remove(sentinel)
 75 		return
 76 	python_path = setup_venv(packages)
 77 	process = subprocess.Popen([str(python_path), script_path, sentinel, *sys.argv[1:]])
 78 	while True:
 79 		try:
 80 			sys.exit(process.wait())
 81 		except KeyboardInterrupt:
 82 			continue
 83 
 84 
 85 def run_in_venv():
 86 	"""Re-run this script in the virtual environment (CLI use of scan.py)."""
 87 	python_path = setup_venv()
 88 	print("Running scanner in virtual environment...\n")
 89 	subprocess.check_call([str(python_path), __file__, "--in-venv"])
 90 	sys.exit(0)
 91 
 92 
 93 SUPPORTED_EXTENSIONS = ('.mp3', '.m4a', '.ogg', '.flac', '.wav')
 94 
 95 _INVALID_FILENAME_CHARS = '<>:"/\\|?*'
 96 
 97 
 98 def _sanitize_filename(name):
 99 	for char in _INVALID_FILENAME_CHARS:
100 		name = name.replace(char, '')
101 	return name.strip()
102 
103 
104 def _write_tags(audio_file, artist, title, MutagenFile):
105 	"""Write artist/title tags to disk if they don't already match. Returns
106 	True if anything was written."""
107 	try:
108 		audio = MutagenFile(audio_file, easy=True)
109 		if audio is None:
110 			return False
111 		if audio.tags is None:
112 			audio.add_tags()
113 		current_title = audio.tags.get('title', [None])[0]
114 		current_artist = audio.tags.get('artist', [None])[0]
115 		if current_title == title and current_artist == artist:
116 			return False
117 		audio.tags['title'] = title
118 		audio.tags['artist'] = artist
119 		audio.save()
120 		return True
121 	except Exception:
122 		return False
123 
124 
125 def _canonicalize(tracks, has_mutagen, MutagenFile, silent):
126 	"""Rename files to 'Artist – Title.ext' and sync ID3 tags so disk state
127 	matches tracks.json metadata. Mutates `tracks` in place; returns a list
128 	of {from, to} renames so callers can migrate any external state (eg.
129 	preloaded blob URLs in connected browser tabs)."""
130 	renames = []
131 	for entry in tracks:
132 		old_filename = entry['filename']
133 		ext = Path(old_filename).suffix
134 		artist = _sanitize_filename(entry['artist'])
135 		title = _sanitize_filename(entry['title'])
136 		new_filename = f"{artist} – {title}{ext}"
137 
138 		old_path = MIX_DIR / old_filename
139 		new_path = MIX_DIR / new_filename
140 
141 		# Keep tags aligned with the (possibly hand-edited) tracks.json
142 		# entry, regardless of whether a rename is needed.
143 		if has_mutagen and old_path.exists():
144 			_write_tags(old_path, entry['artist'], entry['title'], MutagenFile)
145 
146 		if old_filename == new_filename:
147 			continue
148 		if not old_path.exists():
149 			continue
150 		if new_path.exists():
151 			# Don't clobber an unrelated file that already occupies the
152 			# canonical name. Leave the entry pointing at its current file.
153 			if not silent:
154 				print(f"  Skipping rename {old_filename} -> {new_filename} (target exists)")
155 			continue
156 		try:
157 			old_path.rename(new_path)
158 			entry['filename'] = new_filename
159 			renames.append({'from': old_filename, 'to': new_filename})
160 			if not silent:
161 				print(f"  Renamed: {old_filename} -> {new_filename}")
162 		except Exception as e:
163 			if not silent:
164 				print(f"  Error renaming {old_filename}: {e}")
165 	return renames
166 
167 
168 def rescan(silent=False):
169 	"""Reconcile tracks.json with /mix. Renames files to canonical
170 	'Artist – Title.ext' form when they drift, syncing ID3 tags at the same
171 	time. Returns (tracks, changed, renames) where renames is a list of
172 	{from, to} dicts for any files that moved this pass."""
173 	try:
174 		from mutagen import File as MutagenFile  # type: ignore
175 		has_mutagen = True
176 	except ImportError:
177 		MutagenFile = None
178 		has_mutagen = False
179 		if not silent:
180 			print("Mutagen not available. Metadata will be derived from filenames.\n")
181 
182 	if not MIX_DIR.exists():
183 		MIX_DIR.mkdir(parents=True, exist_ok=True)
184 
185 	audio_files = [f for f in MIX_DIR.iterdir() if f.suffix.lower() in SUPPORTED_EXTENSIONS]
186 
187 	existing_tracks = []
188 	if OUTPUT_FILE.exists():
189 		try:
190 			with open(OUTPUT_FILE, 'r', encoding='utf-8') as f:
191 				loaded = json.load(f)
192 			if isinstance(loaded, list):
193 				existing_tracks = loaded
194 		except (json.JSONDecodeError, OSError) as e:
195 			if not silent:
196 				print(f"Warning: could not read existing {OUTPUT_FILE.name} ({e}). Starting fresh.\n")
197 
198 	existing_by_filename = {
199 		t['filename']: t for t in existing_tracks
200 		if isinstance(t, dict) and 'filename' in t
201 	}
202 	on_disk_filenames = {f.name for f in audio_files}
203 	files_by_name = {f.name: f for f in audio_files}
204 
205 	def read_metadata(audio_file):
206 		title = None
207 		artist = None
208 		if has_mutagen:
209 			audio = MutagenFile(audio_file, easy=True)
210 			if audio and audio.tags:
211 				title = audio.tags.get('title', [None])[0]
212 				artist = audio.tags.get('artist', [None])[0]
213 		if not title:
214 			title = audio_file.stem
215 		if not artist:
216 			artist = "Unknown Artist"
217 		return {"title": title, "artist": artist, "filename": audio_file.name}
218 
219 	tracks = []
220 	removed = []
221 	for entry in existing_tracks:
222 		if not isinstance(entry, dict) or 'filename' not in entry:
223 			continue
224 		if entry['filename'] in on_disk_filenames:
225 			tracks.append(entry)
226 		else:
227 			removed.append(entry['filename'])
228 
229 	new_files = sorted(
230 		(files_by_name[name] for name in on_disk_filenames if name not in existing_by_filename),
231 		key=lambda f: f.name,
232 	)
233 	new_tracks = []
234 	for audio_file in new_files:
235 		try:
236 			new_tracks.append(read_metadata(audio_file))
237 		except Exception as e:
238 			if not silent:
239 				print(f"✗ Error reading {audio_file.name}: {e}")
240 
241 	if not silent:
242 		for track in new_tracks:
243 			print(f"+ {track['artist']} - {track['title']}")
244 		for filename in removed:
245 			print(f"- {filename} (removed; no longer on disk)")
246 		if not new_tracks and not removed:
247 			print("No changes — tracks.json already matches /mix.")
248 
249 	tracks.extend(new_tracks)
250 
251 	renames = _canonicalize(tracks, has_mutagen, MutagenFile, silent)
252 
253 	changed = bool(new_tracks) or bool(removed) or bool(renames)
254 	if changed or not OUTPUT_FILE.exists():
255 		try:
256 			OUTPUT_FILE.write_text(
257 				json.dumps(tracks, indent='\t', ensure_ascii=False) + '\n',
258 				encoding='utf-8',
259 			)
260 		except Exception as e:
261 			if not silent:
262 				print(f"\nError writing {OUTPUT_FILE.name}: {e}")
263 			raise
264 
265 	return tracks, changed, renames
266 
267 
268 def scan_tracks():
269 	"""CLI entry point: rescan and print a summary."""
270 	if not MIX_DIR.exists():
271 		print(f"Creating {MIX_DIR.name} directory...")
272 		MIX_DIR.mkdir(parents=True, exist_ok=True)
273 		print(f"✓ {MIX_DIR.name} directory created.")
274 		print(f"\nAdd audio files to the {MIX_DIR.name} directory and run this script again.")
275 		print(f"Supported formats: {', '.join(SUPPORTED_EXTENSIONS)}")
276 		sys.exit(0)
277 
278 	audio_files = [f for f in MIX_DIR.iterdir() if f.suffix.lower() in SUPPORTED_EXTENSIONS]
279 	if not audio_files:
280 		print(f"No audio files found in {MIX_DIR}")
281 		print(f"\nPlease add audio files to the {MIX_DIR.name} directory and run this script again.")
282 		print(f"Supported formats: {', '.join(SUPPORTED_EXTENSIONS)}")
283 		sys.exit(0)
284 
285 	print(f"Found {len(audio_files)} audio file(s). Extracting metadata...\n")
286 	tracks, changed, _renames = rescan(silent=False)
287 	if not tracks:
288 		print("\nNo valid audio files could be processed.")
289 		sys.exit(1)
290 	if changed:
291 		print(f"\n✓ Updated {OUTPUT_FILE.name} ({len(tracks)} track(s)).")
292 
293 
294 def main():
295 	"""Main entry point"""
296 	# Check if we're already running in venv
297 	if "--in-venv" not in sys.argv:
298 		run_in_venv()
299 	else:
300 		scan_tracks()
301 
302 
303 if __name__ == "__main__":
304 	main()