#!/usr/bin/python
import codecs
import re
from mutagen import flac
FILENAME='tracks'
CONFIRM=True
DEBUG=False
SWAPNAME=True
SAVE=True
SPLIT=False
if CONFIRM or DEBUG:
import pprint
# From
# http://stackoverflow.com/questions/10883399/unable-to-encode-decode-pprint-output
class PPUTF8(pprint.PrettyPrinter):
def format(self, object, context, maxlevels, level):
if isinstance(object, unicode):
return (object.encode('utf8'), True, False)
return pprint.PrettyPrinter.format(self, object, context,
maxlevels, level)
if __name__ == '__main__':
if CONFIRM or DEBUG:
pp = PPUTF8(indent=4)
with codecs.open(FILENAME, encoding='utf-8', mode='r') as f:
lines = f.readlines()
headers = lines[0][:-1].split('\t')
if SWAPNAME:
first_last = re.compile('^(?P<last>[^,]+),\s+(?P<first>.+)$')
files = {}
for i, file in enumerate(lines[1:]):
# i starts counting at zero while we need it to start counting at 1
# since 0 is the header line
i += 1
line = lines[i].replace('\n', '').split('\t')
file = line[0]
files[file] = {}
for j, tag in enumerate(line[1:]):
# j starts counting at 0, should be 1
j += 1
header = headers[j]
files[file][header] = tag.strip()
if header == 'ARTIST' or header == 'LYRICIST' or \
header == 'ARRANGER':
if SPLIT:
files[file][header] = [name.strip() for name in
tag.split(';')]
else:
files[file][header] = tag.strip()
if SWAPNAME:
for n, name in enumerate(files[file][header]):
res = first_last.match(name)
if res:
files[file][header][n] = res.group('first') + \
' ' + res.group('last')
if CONFIRM:
print "Loaded data:\n"
pp.pprint(files)
if CONFIRM:
if raw_input("\nSave files? [Y/n]").lower()in ['', 'y']:
SAVE = True
else:
SAVE = False
file = flac.FLAC()
for name in files.keys():
file.load(name)
# Delete tags
file.delete()
for key, val in files[name].iteritems():
file[key] = val
if SAVE:
file.save()
if DEBUG:
print "\n\nData in flac file:", name
pp.pprint(file)