Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit eedfec0

Browse files
committed
Initial commit of music-autoplaylists.
1 parent 9977e59 commit eedfec0

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

python2.7/music-autoplaylists.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#!/usr/bin/env python2.7
2+
3+
__author__ = ['[Brandon Amos](http://bamos.github.io)']
4+
__date__ = '2015.04.09'
5+
6+
"""
7+
This script (music-autoplaylists.py) automatically creates
8+
M3U playlists from the genre ID3 tags of songs in a directory.
9+
"""
10+
11+
import argparse
12+
import os
13+
import re
14+
import shutil
15+
import sys
16+
from mutagen.easyid3 import EasyID3
17+
from collections import defaultdict
18+
19+
def main():
20+
parser = argparse.ArgumentParser()
21+
parser.add_argument('--musicDir', type=str, default='.')
22+
parser.add_argument('--playlistDir', type=str, default='./playlists/auto')
23+
args = parser.parse_args()
24+
25+
genres = defaultdict(list)
26+
for dpath, dnames, fnames in os.walk(args.musicDir):
27+
if '.git' in dpath: continue
28+
for fname in fnames:
29+
if os.path.splitext(fname)[1] != '.mp3': continue
30+
p = os.path.abspath(os.path.join(dpath, fname))
31+
audio = EasyID3(p)
32+
if 'genre' in audio:
33+
assert(len(audio['genre']) == 1)
34+
genre = toNeat(str(audio['genre'][0]))
35+
else:
36+
genre = 'Unknown'
37+
genres[genre].append(p)
38+
39+
if os.path.exists(args.playlistDir):
40+
shutil.rmtree(args.playlistDir)
41+
os.makedirs(args.playlistDir)
42+
43+
for genre, songs in genres.items():
44+
p = os.path.join(args.playlistDir, genre+'.m3u')
45+
print("Creating playlist: {}".format(p))
46+
with open(p, 'w') as f:
47+
f.write("#EXTM3U\n")
48+
f.write("\n".join(sorted(songs))+"\n")
49+
50+
# Maps a string such as 'The Beatles' to 'the-beatles'.
51+
def toNeat(s):
52+
s = s.lower().replace("&", "and")
53+
54+
# Put spaces between and remove blank characters.
55+
blankCharsPad = r"()\[\],.\\\?\#/\!\$\:\;"
56+
blankCharsNoPad = r"'\""
57+
s = re.sub(r"([" + blankCharsPad + r"])([^ ])", "\\1 \\2", s)
58+
s = re.sub("[" + blankCharsPad + blankCharsNoPad + "]", "", s)
59+
60+
# Replace spaces with a single dash.
61+
s = re.sub(r"[ \*\_]+", "-", s)
62+
s = re.sub("-+", "-", s)
63+
s = re.sub("^-*", "", s)
64+
s = re.sub("-*$", "", s)
65+
66+
# Ensure the string is only alphanumeric with '-', '+', and '='.
67+
search = re.search("[^0-9a-z\-\+\=]", s)
68+
if search:
69+
print("Error: Unrecognized character in '" + s + "'")
70+
sys.exit(-42)
71+
return s
72+
73+
if __name__ == '__main__':
74+
main()

0 commit comments

Comments
 (0)