Makefile: add pickrand
[cmccabe-bin] / tagger.py
1 #!/usr/bin/python
2
3 #
4 # Changes mp3 ID3 tags to match the file names.
5 #
6 # I like to store my mp3s in a file structure like this:
7 #
8 # Artist Name - Album Title = Conductor [Encoding]/01 - Track 1.mp3
9 # Artist Name - Album Title = Conductor [Encoding]/02 - Track 2.mp3
10 # ...
11 #
12 # This script runs through an entire directory of mp3s, and changes all the
13 # ID3 tags to match the file names.
14 #
15 # Philosophical aside: I guess you could argue that this defeats the point of
16 # ID3 tags, since under this system, allthe information is stored in the file
17 # name. This is true; however, I need to play my music on a lot of different
18 # systems (like mp3 players) which don't use my file naming scheme.
19 #
20 # I have had bad experiences with ID3 tags in the past. Every program seems
21 # to generate and parse them a little bit differently. The ID3 standard
22 # doesn't even specify whether to use unicode vs. Latin-1, let alone what you
23 # should do if a file has conflicting ID3v1 and ID3v2 tags.
24 #
25 # It's just easier to use a filing system that actually works well-- the Linux
26 # filesystem -- and regard IDv3 tags as something ephemeral that's generated
27 # out of the "real" file information.
28 #
29 # Colin McCabe
30 # 2008/12/7
31 #
32
33 import getopt
34 import os
35 import re
36 import stat
37 import string
38 import subprocess
39 import sys
40
41 # GLOBALS
42
43 # script arguments
44 dry_run = False
45 verbose = False
46 self_test = False
47
48 # globals
49 total_albums = 0
50 id3v2_wrapper = ""
51
52 # Verifies that there is an executable script named 'target' in the same 
53 # directory as this script. If not, prints an error message and exits.
54 def find_companion_script(target):
55     try:
56         mydir = os.path.dirname(sys.argv[0])
57         target_path = mydir + "/" + target
58         statinfo = os.stat(mydir + "/" + target)
59         mode = statinfo[0]
60         if not (mode & stat.S_IEXEC):
61             print "ERROR: " + target + " is not executable"
62             sys.exit(1)
63         return target_path 
64     except Exception, e:
65         print "ERROR: can't find id3v2_wrapper.sh: " + str(e)
66         sys.exit(1)
67
68 # Verifies that a given program is installed.
69 def verify_program_installed(prog):
70     try:
71         proc = subprocess.Popen(prog, stdout=subprocess.PIPE)
72         line = proc.stdout.readline()
73         return True
74     except Exception, e:
75         print "failed to execute " + str(prog)
76         return False
77
78 # Regular expressions for parsing file names--
79 # which is, after all, what this program is all about
80 music_file_re = re.compile(".*\.mp3$")
81
82 music_file_name_re = re.compile(".*/" +
83             "(?P<dir_name>[^/]*)/" +
84             "(?P<track_number>[0123456789][0123456789]*) - " +
85             "(?P<track_name>[^/]*)" +
86             "\.[a-zA-Z0123456789]*$")
87
88 dir_name_re = re.compile("(.*/)?" +
89             "(?P<artist>[0-9A-Za-z _.\-]*?) - " +
90             "(?P<album>[0-9A-Za-z _(),'.\-\+]*)" + 
91             "(?P<conductor> = [0-9A-Za-z _'.\-]*)?"
92             "(?P<encoding>\[LL\])?$")
93
94 def self_test_music_file(m, artist, album_name, \
95                         conductor, track_number, title):
96     if (m.album.artist != artist):
97         print "FAILED: artist: \"" + m.album.artist + "\""
98         print "\tshould be: \"" + artist + "\""
99     if (m.album.name != album_name):
100         print "FAILED: album_name: \"" + m.album.name + "\""
101         print "\tshould be: \"" + album_name + "\""
102     if (m.album.conductor != conductor):
103         print "FAILED: conductor: \"" + m.album.conductor + "\""
104         print "\tshould be: \"" + conductor + "\""
105     if (m.track_number != track_number):
106         print "FAILED: track_number: \"" + int(m.track_number) + "\""
107         print "\tshould be: \"" + str(track_number) + "\""
108     if (m.title != title):
109         print "FAILED: title: \"" + m.title + "\""
110         print "\tshould be: \"" + title + "\""
111
112 def run_self_test():
113     m = MusicFile.from_filename("./Mozart - " +
114                 "Symphony No 26 in Eb Maj - K161a" + 
115                 " = The Academy of Ancient Music" +
116                 "/01 - Adagio.mp3")
117     self_test_music_file(m,
118                     artist="Mozart",
119                     album_name="Symphony No 26 in Eb Maj - K161a",
120                     conductor="The Academy of Ancient Music",
121                     track_number=1,
122                     title="Adagio")
123
124
125     m = MusicFile.from_filename("./Tchaikovsky - " +
126                 "The Sleeping Beauty - Op. 66" + 
127                 " = Sir Charles Mackerras" +
128                 "/02 - Scene.mp3")
129     self_test_music_file(m,
130                     artist="Tchaikovsky",
131                     album_name="The Sleeping Beauty - Op. 66",
132                     conductor="Sir Charles Mackerras",
133                     track_number=2,
134                     title="Scene")
135
136     # TODO: move John Cage into Comment or secondary author field here.
137     m = MusicFile.from_filename("./Various - " +
138                 "American Classics" +
139                 "/12 - John Cage - Prelude for Meditation.mp3")
140     self_test_music_file(m, 
141                     artist="Various",
142                     album_name="American Classics",
143                     conductor="",
144                     track_number=12,
145                     title="John Cage - Prelude for Meditation")
146
147 # Given a hash H, creates a hash which is the inverse
148 # i.e. if H[k] = v, H'[v] = k
149 def reverse_hash(h):
150     ret = dict()
151     i = h.iteritems()
152     while 1:
153         try:
154             k,v = i.next()
155             ret[v] = k
156         except StopIteration:
157             break
158     return ret
159
160 def my_system(ignore_ret, *cmd):
161     if (verbose == True):
162         print cmd
163     if (dry_run == False):
164         try:
165             my_env = {"MALLOC_CHECK_" : "0", "PATH" : os.environ.get("PATH")}
166             retcode = subprocess.call(cmd, env=my_env, shell=False)
167             if (retcode < 0):
168                 print "ERROR: Child was terminated by signal", -retcode
169             else:
170                 if ((not ignore_ret) and (retcode != 0)):
171                     print "ERROR: Child returned", retcode
172         except OSError, e:
173             print "ERROR: Execution failed:", e
174
175 # CLASSES
176 class FileType(object):
177     def __init__(self, encoding):
178         self.encoding = encoding
179
180 class Album(object):
181     def __init__(self, artist, name, conductor, encoding):
182         if (artist == None):
183             raise MusicFileErr("can't have Album.artist = None")
184         if (name == None):
185             raise MusicFileErr("can't have Album.name = None")
186         self.artist = string.rstrip(artist)
187         self.name = string.rstrip(name)
188         if (conductor):
189             i = conductor.find(' = ')
190             self.conductor = conductor[i+len(' = '):]
191         else:
192             self.conductor = ""
193         self.encoding = string.rstrip(encoding) if encoding else ""
194
195     def from_dirname(dirname):
196         match = dir_name_re.match(dirname)
197         if (not match):
198             raise MusicFileErr("can't parse directory name \"" + 
199                                 dirname + "\"")
200         return Album(match.group('artist'), match.group('album'), 
201                      match.group('conductor'), match.group("encoding"))
202     from_dirname = staticmethod(from_dirname)
203
204     def to_s(self):
205         ret = self.artist + " - " + self.name
206         if (self.conductor != None):
207             ret += " " + self.conductor
208         if (self.encoding != None):
209             ret += " " + self.encoding
210         return ret
211
212 class MusicFileErr(Exception):
213     pass
214
215 class MusicFile(object):
216     id3v2_to_attrib = { 'TIT2' : 'self.title',
217                         'TPE1' : 'self.album.artist',
218                         'TALB' : 'self.album.name',
219                         'TRCK' : 'str(self.track_number)',
220                         'TPE3' : 'self.album.conductor',
221                         #'TYER' : 'year'
222                     }
223     attrib_to_id3v2 = reverse_hash(id3v2_to_attrib)
224
225     def __init__(self, filename, album, title, track_number):
226         self.filename = filename
227         self.album = album
228         self.title = title
229         self.track_number = int(track_number)
230
231     def from_filename(filename):
232         match = music_file_name_re.match(filename)
233         if (not match):
234             raise MusicFileErr("can't parse music file name \"" + 
235                             filename + "\"")
236         album = Album.from_dirname(match.group('dir_name'))
237         return MusicFile(filename, album, 
238                         match.group('track_name'),
239                         match.group('track_number'))
240     from_filename = staticmethod(from_filename)
241
242     def to_s(self):
243         ret = self.album.to_s() + "/" + \
244                 ("%02d" % self.track_number) + " - " + self.title
245         return ret
246
247     def clear_tags(self):
248         my_system(True, id3v2_wrapper, "--delete-v1", self.filename)
249         my_system(True, id3v2_wrapper, "--delete-v2", self.filename)
250
251     def add_tag(self, att, expr):
252         attribute = "--" + att
253         my_system(False, "id3v2", attribute, expr, self.filename)
254
255     def set_tags(self):
256         i = self.id3v2_to_attrib.iteritems()
257         while 1:
258             try:
259                 att,expr = i.next()
260                 self.add_tag(att, eval(expr))
261             except StopIteration:
262                 break
263 # CODE
264
265 ## Make sure that id3v2 is installed
266 if not verify_program_installed(["id3v2", "--version"]):
267     print "You must install the id3v2 program to run this script."
268     sys.exit(1)
269
270 ## Find id3v2_wrapper.sh
271 id3v2_wrapper = find_companion_script('id3v2_wrapper.sh')
272
273 ## Parse options
274 def Usage():
275     print os.path.basename(sys.argv[0]) + ": the mp3 tagging program"
276     print
277     print "Usage: " + os.path.basename(sys.argv[0]) + \
278             " [-h][-d][-s] [dirs]"
279     print "-h: this help message"
280     print "-d: dry-run mode"
281     print "-s: self-test"
282     print "dirs: directories to search for albums."
283     print "This program skips dirs with \"[LL]\" in the name."
284     sys.exit(1)
285
286 try:
287     optlist, dirs = getopt.getopt(sys.argv[1:], ':dhi:sv')
288 except getopt.GetoptError:
289     Usage()
290
291 for opt in optlist:
292     if opt[0] == '-h':
293         Usage()
294     if opt[0] == '-d':
295         dry_run = True
296     if opt[0] == '-v':
297         verbose = True
298     if opt[0] == '-s':
299         self_test = True
300
301 if (self_test):
302     run_self_test()
303     sys.exit(0)
304
305 for dir in dirs:
306     if (re.search("\[LL\]", dir)):
307         print "skipping \"" + dir + "\"..."
308         continue
309     # Assume that paths without a directory prefix are local
310     if ((dir[0] != "/") and (dir.find("./") != 0)):
311         dir = "./" + dir
312
313     # Validate that 'dir' is a directory and we can access the entries
314     # Note: this does not protect against having nested directories with
315     # bad permissions
316     try:
317         entries = os.listdir(dir)
318     except:
319         print "ERROR: cannot stat entries of \"" + dir + "\""
320         continue
321
322     # Process all files in the directory
323     if (verbose):
324         print "******** find -L " + dir + " -noleaf"
325     proc = subprocess.Popen(['find', '-L', dir, '-noleaf'],\
326             stdout=subprocess.PIPE)
327     line = proc.stdout.readline()
328     while line != '':
329         file_name = line.strip()
330         if (music_file_re.match(file_name)):
331             try:
332                 m = MusicFile.from_filename(file_name)
333                 m.clear_tags()
334                 m.set_tags()
335                 if (verbose):
336                     print "SUCCESS: " + file_name
337                 total_albums = total_albums + 1
338             except MusicFileErr, e:
339                 print "ERROR: " + str(e)
340         line = proc.stdout.readline()
341     if (verbose):
342         print "********"
343
344 if (dry_run):
345     print "(dry run)",
346 print "Successfully processed " + str(total_albums) + " total mp3s"