import os import json import musicbrainzngs import requests from mutagen import File # configure musicbrainz client musicbrainzngs.set_useragent("EDUrocksMetaFetcher", "1.0", "youremail@example.com") # paths SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) MUSIC_DIR = os.path.join(SCRIPT_DIR, "music") COVERS_DIR = os.path.join(SCRIPT_DIR, "covers") OUTPUT_JSON = os.path.join(SCRIPT_DIR, "tracks.json") os.makedirs(COVERS_DIR, exist_ok=True) def format_length(seconds): if not seconds or seconds <= 0: return "--:--" m, s = divmod(int(seconds), 60) return f"{m}:{str(s).zfill(2)}" def download_cover(url, album_id): ext = url.split('.')[-1].split('?')[0] filename = f"{album_id}.{ext}" path = os.path.join(COVERS_DIR, filename) if not os.path.exists(path): print(f" downloading cover art for album {album_id}") try: r = requests.get(url, timeout=10) if r.status_code == 200: with open(path, "wb") as f: f.write(r.content) return filename else: print(f" failed to download cover art: HTTP {r.status_code}") except Exception as e: print(f" error downloading cover art: {e}") else: # already downloaded return filename return None def query_musicbrainz(artist, title): try: # search recordings by artist and title, limit 1 best match results = musicbrainzngs.search_recordings(artist=artist, recording=title, limit=1) if results['recording-list']: rec = results['recording-list'][0] # get recording info rec_title = rec.get('title', title) rec_id = rec.get('id') # get artist credit name artist_credit = rec.get('artist-credit', []) artist_name = artist_credit[0]['name'] if artist_credit else artist # get releases (albums) this recording is on releases = rec.get('release-list', []) if releases: release = releases[0] album_title = release.get('title', "Unknown Album") album_id = release.get('id') date = release.get('date', "") # get cover art url via Cover Art Archive cover_url = None try: art = musicbrainzngs.get_image_list(album_id) if art['images']: cover_url = art['images'][0].get('image') except musicbrainzngs.ResponseError: # no cover art found, ignore pass else: album_title = "Unknown Album" album_id = None date = "" cover_url = None return { "title": rec_title, "artist": artist_name, "album": album_title, "year": date[:4] if date else "", "album_id": album_id, "cover_url": cover_url, } except Exception as e: print(f"MusicBrainz query failed for {artist} - {title}: {e}") return None def get_local_length(filepath): try: audio = File(filepath) if audio and audio.info: return audio.info.length except: pass return 0 def scan_music_folder(): tracks = [] for root, _, files in os.walk(MUSIC_DIR): for file in files: if file.lower().endswith((".mp3", ".flac", ".ogg", ".wav", ".m4a", ".aac")): full_path = os.path.join(root, file) print(f"Processing: {full_path}") # read embedded tags just to get artist/title for lookup (ignore metadata for output) try: audio = File(full_path, easy=True) if not audio: print(" can't read tags, skipping") continue artist = audio.get('artist', [None])[0] title = audio.get('title', [None])[0] if not artist or not title: print(" missing artist/title tags, skipping") continue except Exception as e: print(f" error reading tags: {e}") continue # query musicbrainz mb_data = query_musicbrainz(artist, title) if not mb_data: print(" musicbrainz lookup failed, skipping") continue # download cover if any cover_filename = None if mb_data['cover_url'] and mb_data['album_id']: cover_filename = download_cover(mb_data['cover_url'], mb_data['album_id']) length_sec = get_local_length(full_path) src_path = "./" + os.path.relpath(full_path, SCRIPT_DIR).replace(" ", "%20") track_entry = { "title": mb_data['title'], "artist": mb_data['artist'], "album": mb_data['album'], "year": mb_data['year'], "length": format_length(length_sec), "src": src_path, "cover": f"./covers/{cover_filename}" if cover_filename else "", } tracks.append(track_entry) print(f" added: {mb_data['artist']} - {mb_data['title']} from album {mb_data['album']}") return tracks if __name__ == "__main__": track_list = scan_music_folder() with open(OUTPUT_JSON, "w") as f: json.dump(track_list, f, indent=2) print(f"Done! wrote {len(track_list)} tracks to {OUTPUT_JSON}")