Created
January 26, 2025 15:05
-
-
Save vordenken/d875e98db8fa047e330e96c2e5964c64 to your computer and use it in GitHub Desktop.
Sort music for Jellyfin (or other software wanting folder structures).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import shutil | |
| from mutagen.easyid3 import EasyID3 | |
| from mutagen.mp3 import MP3 | |
| def get_metadata(file_path): | |
| try: | |
| audio = EasyID3(file_path) | |
| artists = audio.get('artist', ['Unbekannter Künstler']) | |
| album_artists = audio.get('albumartist', [artists[0]]) | |
| album = audio.get('album', ['Unbekanntes Album'])[0] | |
| title = audio.get('title', [os.path.splitext(os.path.basename(file_path))[0]])[0] | |
| # Behandlung von Features | |
| if len(artists) > 1: | |
| main_artist = artists[0] | |
| features = ', '.join(artists[1:]) | |
| title = f"{title} (feat. {features})" | |
| else: | |
| main_artist = artists[0] | |
| return main_artist, album_artists[0], album, title | |
| except Exception as e: | |
| print(f"Fehler beim Lesen der Tags für {file_path}: {e}") | |
| return "Unbekannter Künstler", "Unbekannter Künstler", "Unbekanntes Album", os.path.splitext(os.path.basename(file_path))[0] | |
| def sanitize_filename(name): | |
| invalid_chars = '<>:"/\\|?*' | |
| return ''.join(c for c in name if c not in invalid_chars) | |
| def organize_music(source_dir, target_dir): | |
| for filename in os.listdir(source_dir): | |
| if filename.lower().endswith('.mp3'): | |
| file_path = os.path.join(source_dir, filename) | |
| artist, album_artist, album, title = get_metadata(file_path) | |
| artist = sanitize_filename(artist) | |
| album_artist = sanitize_filename(album_artist) | |
| album = sanitize_filename(album) | |
| title = sanitize_filename(title) | |
| if album_artist == "Various Artists": | |
| artist_dir = os.path.join(target_dir, "Various Artists") | |
| else: | |
| artist_dir = os.path.join(target_dir, album_artist) | |
| album_dir = os.path.join(artist_dir, album) | |
| os.makedirs(album_dir, exist_ok=True) | |
| new_filename = f"{artist} - {title}.mp3" | |
| destination = os.path.join(album_dir, new_filename) | |
| try: | |
| shutil.copy2(file_path, destination) | |
| print(f"Kopiert: {filename} -> {destination}") | |
| except PermissionError: | |
| print(f"Keine Berechtigung zum Kopieren von {filename}") | |
| except Exception as e: | |
| print(f"Fehler beim Kopieren von {filename}: {e}") | |
| if __name__ == "__main__": | |
| source_directory = "$CURRENT_MUSIC_PATH" | |
| target_directory = "$FINAL_MUSIC_PATH" | |
| organize_music(source_directory, target_directory) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment