Created
September 27, 2013 11:09
-
-
Save andreasvc/6727072 to your computer and use it in GitHub Desktop.
Generate image with plot & rating for each movie in a directory. Useful for media players etc. Each directory in the current path is treated as the name of a movie,
and data for it is obtained from IMDB (through an unofficial API).
A PNG file is created with a plot summary using Python Imaging
and stored in that directory as 'info.png'.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Generate image with plot & rating for each movie in a directory. """ | |
from __future__ import print_function | |
import os | |
import re | |
import sys | |
import glob | |
import json | |
import time | |
import urllib | |
import textwrap | |
from PIL import Image, ImageFont, ImageDraw | |
USAGE = """Usage: %s | |
Each directory in the current path is treated as the name of a movie, | |
and data for it is obtained from IMDB (through an unofficial API). | |
A PNG file is created with a plot summary using Python Imaging | |
and stored in that directory as 'info.png'.""" % sys.argv[0] | |
FONTFILE = '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono.ttf' | |
FONTSIZE = 40 | |
TEXTWIDTH = 65 | |
YEARRE = re.compile('[ .([{]?((?:19|20)[0-9][0-9])') | |
def getplot(path): | |
""" Fetch data and return as list of lines """ | |
match = YEARRE.search(path) | |
title = path[:match.start()] if match else path | |
title = title.replace('.', ' ') | |
print('Path: %s; title: %s; year: %s' % ( | |
path, title, match.group(1) if match else 'N/A')) | |
url = 'http://www.omdbapi.com/?plot=full&t=%s' % (urllib.quote(title)) | |
if match: | |
url += '&y=' + match.group(1) | |
data = json.loads(urllib.urlopen(url).read()) | |
header = ['Rating %s; length: %s; title: %s' % ( | |
data.get('imdbRating', '-'), data.get('Runtime', '-'), title)] | |
return header + textwrap.wrap(data.get('Plot', '-'), width=TEXTWIDTH) | |
def makeimage(lines, filename): | |
""" Render lines and write to given filename. """ | |
image = Image.new('1', (1920, 1080), 0) | |
draw = ImageDraw.Draw(image) | |
font = ImageFont.truetype(FONTFILE, FONTSIZE) | |
xmargin = 150 | |
yoffset = 60 | |
for line in lines: | |
draw.text((xmargin, yoffset), line, 1, font=font) | |
yoffset += font.getsize(line)[1] | |
image.save(filename) | |
def main(): | |
""" Main loop. """ | |
if '--help' in sys.argv: | |
print(USAGE) | |
return | |
for path in glob.glob('*/'): | |
filename = os.path.join(path, 'info.png') | |
if not os.path.exists(filename): | |
path = os.path.basename(os.path.dirname(path)) | |
makeimage(getplot(path), filename) | |
time.sleep(2) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment