summaryrefslogtreecommitdiff
path: root/coverart.py
blob: 8de49e9c346ffbe8ccde1fb9a8fdbc0211edc426 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python2

import db, mutagen, os
from config import config
from PIL import Image

try:
	import cStringIO as StringIO
except ImportError:
	import StringIO

def get_coverart(album, ignorecache = False):
	covercache_dir = config.get('covercache_dir')
	covercache = os.path.join(covercache_dir, '%d.jpg' % album.id)

	def makecover(fileobj):
		im = Image.open(fileobj)
		im.thumbnail((128, 128), Image.ANTIALIAS)
		im.save(covercache)
		return covercache

	if not ignorecache and os.path.exists(covercache):
		return covercache

	if not len(album.tracks):
		return

	track = album.tracks[0]
	try:
		f = mutagen.File(track.get_path())
	except:
		f = None
	if hasattr(f, 'pictures') and len(f.pictures):
		p = f.pictures[0]
		s = StringIO.StringIO(p.data)
		return makecover(s)

	dirname = os.path.dirname(track.get_path())
	files = os.listdir(dirname)
	files.sort()
	cover = []
	for f in files:
		filename = os.path.join(dirname, f)
		if os.path.isdir(filename) and f.lower() in ('scans', 'jpg', 'jpeg', 'img', 'image', 'cover', 'covers'):
			files.extend(os.path.join(f, x) for x in os.listdir(filename))
			files.sort()
		if not os.path.isfile(filename):
			continue
		extensions = ('.jpg', '.jpeg', '.png', '.bmp')
		root, ext = os.path.splitext(f)
		# Ignore non-image files
		if not ext.lower() in extensions:
			continue
		if os.path.split(root)[-1].lower() in ('cover', 'cover-large', 'cover-front'):
			cover.insert(0, f)
		elif 'cover' in f.lower() and not len(cover):
			cover.append(f)
		elif not len(cover):
			cover.append(f)

	while len(cover):
		filename = os.path.join(dirname, cover.pop(0))
		return makecover(open(filename, 'rb'))

def main():
	session = db.Session()
	for album in session.query(db.Album):
		get_coverart(album, True)

if __name__ == '__main__':
	main()