Debian Codegraph @

scripts/tag_lyrics.py

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # needs mutagen
5 # grabbed from: http://code.activestate.com/recipes/577138-embed-lyrics-into-mp3-files-using-mutagen-uslt-tag/
6 # simplified to only work on one file and get lyrics from stdin
7 # I suspect this is public domain code. Just a usage example of the mutagen lib.
8
9 import os
10 import sys
11 import codecs
12 from mutagen.mp3 import MP3
13 from mutagen.id3 import ID3NoHeaderError
14 from mutagen.id3 import ID3, USLT
15
16 TEXT_ENCODING = 'utf8'
17 TEXT_LANG = 'XXX'
18 TEXT_DESC = ''
19
20 # get workdir from first arg or use current dir
21 if (len(sys.argv) > 1):
22 fname = sys.argv[1]
23 print("fname=" + fname)
24 else:
25 print('Give me at least a file name to work on, plus the lyrics from stdin')
26 print('Optionally, you can provide the language (3 lowercase letters) of the lyrics and a description')
27 sys.exit()
28
29 if (len(sys.argv) > 2):
30 TEXT_LANG = sys.argv[2]
31
32 if (len(sys.argv) > 3):
33 TEXT_DESC = sys.argv[3]
34
35 print("reading lyrics from standard input ...")
36
37 lyrics = sys.stdin.read().strip()
38
39 # try to find the right encoding
40 for enc in ('utf8','iso-8859-1','iso-8859-15','cp1252','cp1251','latin1'):
41 try:
42 lyrics = lyrics.decode(enc)
43 TEXT_DESC = TEXT_DESC.decode(enc)
44 print(enc, end=" ")
45 break
46 except:
47 pass
48
49 print("Adding lyrics to " + fname)
50 print("Language: " + TEXT_LANG)
51 print("Description: " + TEXT_DESC)
52
53 # create ID3 tag if not exists
54 try:
55 tags = ID3(fname)
56 except ID3NoHeaderError:
57 print("Adding ID3 header;", end=" ")
58 tags = ID3()
59
60 # remove old unsychronized lyrics
61 if len(tags.getall(u"USLT::'"+TEXT_LANG+"'")) != 0:
62 print("Removing Lyrics.")
63 tags.delall(u"USLT::'"+TEXT_LANG+"'")
64 #tags.save(fname) # hm, why?
65
66 #tags.add(USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics))
67 # apparently the description is important when more than one
68 # USLT frames are present
69 #tags[u"USLT::'eng'"] = (USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics))
70 tags[u"USLT::'"+TEXT_LANG+"'"] = (USLT(encoding=3, lang=TEXT_LANG, desc=TEXT_DESC, text=lyrics))
71 print('Added USLT frame to', fname)
72
73 tags.save(fname)
74
75 print('Done')
76