rendered paste body#!/usr/bin/python -OO
import os.path
import sys
import mutagen.easyid3
import mutagen.id3
import mutagen.mp4
import mutagen.flac
if len(sys.argv) < 3:
print 'USAGE: %s [root source dir] [destination dir]' % sys.argv[0]
raise SystemExit
src, dest = sys.argv[1:]
if not os.path.exists(src):
print 'ERROR: Source dir %s does not exist.' % src
raise SystemExit
if not os.path.exists(dest):
print 'Creating destination dir `%s`.' % dest
os.makedirs(dest)
def flac(fname):
info = dict(mutagen.flac.Open(fname))
info['tracknumber'] = int(info.get('tracknumber', ['0/0'])[0].split('/')[0])
return info
def mp3(fname):
info = dict(mutagen.easyid3.Open(fname))
info['tracknumber'] = int(info.get('tracknumber', ['0/0'])[0].split('/')[0])
return info
def m4a(fname):
info = dict(mutagen.mp4.Open(fname))
info = { 'tracknumber': info.get('trkn', (0,))[0],
'title': info.get(r'\xa9nam', 'Unknown Title'),
'artist': info.get(r'\xa9ART', 'Unknown Artist'),
'album': info.get(r'\xa9alb', 'Unknown Album')
}
return info
handlers = {
'flac': flac,
'mp3': mp3,
'm4a': m4a,
'm4p': m4a
}
for root,dirs,files in os.walk(src):
for file in files:
fullpath = os.path.join(root, file)
ext = file.split('.')[-1]
try:
tags = handlers.get(ext, lambda x:'')(fullpath)
if tags != '':
val = lambda x,y : tags.get(x, [y])[0].strip()
artist = val('artist', 'Unknown Artist')
album = val('album', 'Unknown Album')
title = val('title', 'Unknown Track')
#title() Capitalizes Strings Like This
artist = artist.title()
album = album.title()
dir = os.path.join(dest, artist, album)
if not os.path.exists(dir):
os.makedirs(dir)
endfile = os.path.join(dir, '%s.%s' % (title.replace('/',''), ext))
if not os.path.exists(endfile):
try:
os.popen(u'ln "%s" "%s"' % (fullpath, endfile))
except:
print fullpath, endfile, ':('
except mutagen.id3.ID3NoHeaderError, KeyError:
#error loading tags
pass