Created
June 4, 2022 13:22
-
-
Save wesleyel/eb60df291270cf3b298fbbb576993091 to your computer and use it in GitHub Desktop.
ID3Tag your *.(mp3|flac) from filename
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
# origin code by hiryu85 | |
# https://github.com/hiryu85/python-ID3TagFromFilename/blob/master/id3fromfile.py | |
# rewrite at 2022.06.04 | |
from glob import glob | |
from re import match | |
from string import Template | |
from sys import argv, exit | |
from mutagen import File | |
ID3TagMap = { | |
'tracknumber': '(?P<trackNum>\d+)', | |
'title': '(?P<title>.+)', | |
'artist': '(?P<artist>.+)', | |
'album': '(?P<album>.+)', | |
} | |
if __name__ == '__main__': | |
if len(argv) < 2: | |
print('Usage: %s "pattern" <template>' % argv[0]) | |
exit(1) | |
file_pattern, file_template = argv[1:] | |
print('Matching %s:' % file_pattern) | |
for fname in glob(file_pattern): | |
ftitle = ''.join(fname.rsplit('.', 1)[:-1]) | |
print(fname + ' ...', end="") | |
try: | |
id3tag_regex_pattern = r'^%s$' % Template(file_template).substitute(ID3TagMap) | |
try: | |
id3tags = match(id3tag_regex_pattern, ftitle).groupdict([]) | |
audiofile = File(fname) | |
try: | |
audiofile.add_tags() | |
except Exception: | |
pass | |
if len(audiofile.keys()) > 1: | |
print(" SKIPPED") | |
continue | |
for tag in id3tags.keys(): | |
value = id3tags[tag] | |
audiofile[tag.upper()] = value | |
audiofile.save() | |
print(' [OK]') | |
except Exception as e: | |
print(repr(e)) | |
pass | |
except ValueError: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment