Skip to content

Instantly share code, notes, and snippets.

@br0kenpixel
Last active June 2, 2023 19:31
Show Gist options
  • Save br0kenpixel/c0602ccc26929d24b038ed3177a5b9bb to your computer and use it in GitHub Desktop.
Save br0kenpixel/c0602ccc26929d24b038ed3177a5b9bb to your computer and use it in GitHub Desktop.
Organize songs into a nice folder structure (Artist/Album/Song)
import music_tag
from os import listdir, system, mkdir
from subprocess import run
from os.path import exists
import unicodedata #Django
import re
F_EXT = "m4a"
TARGET_DIR = "organized"
def getfiles():
files = listdir(".")
files = [file for file in files if file[0] != "."]
files = [file for file in files if file.endswith(F_EXT)]
return iter(files)
#Django
def slugify(value, allow_unicode=True):
"""
Taken from https://github.com/django/django/blob/master/django/utils/text.py
Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
dashes to single dashes. Remove characters that aren't alphanumerics,
underscores, or hyphens. Convert to lowercase. Also strip leading and
trailing whitespace, dashes, and underscores.
"""
value = str(value)
if allow_unicode:
value = unicodedata.normalize('NFKC', value)
else:
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = value.replace("/", " ")
value = value.replace("\\", " ")
value = re.sub(" +", " ", value)
return value
if exists(TARGET_DIR):
print("Re-creating target directory...")
system(f"rm -rf {TARGET_DIR}")
mkdir(TARGET_DIR)
print("Target directory is ready!")
for file in getfiles():
print(f"Loading {file}")
metadata = music_tag.load_file(file)
title = slugify(metadata["title"])
artist = slugify(str(metadata["albumartist"]))
album = slugify(str(metadata["album"]))
artist_dir = f"{TARGET_DIR}/{slugify(artist)}"
album_dir = f"{artist_dir}/{slugify(album)}"
if not exists(artist_dir):
mkdir(artist_dir)
if not exists(album_dir):
mkdir(album_dir)
run(["cp", file, f"{album_dir}/{title}.{F_EXT}"], check=True)
print("Done!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment