papiez_ipsum/src/papiezator/pope_utils.py

69 lines
1.6 KiB
Python

from papiezator.models import Pope, PerfectPope, decimal_places
from PIL import Image
from io import BytesIO # FIXME:
def select_best_pope(aspect_ratio):
""" (float) -> Pope
"""
pp = PerfectPope.objects.filter(aspect_ratio=aspect_ratio)
if pp:
return pp[0].pope
lte = Pope.objects.filter(aspect_ratio__lte=aspect_ratio).order_by('-aspect_ratio')[0:1]
gte = Pope.objects.filter(aspect_ratio__gte=aspect_ratio).order_by('aspect_ratio')[0:1]
if gte and lte:
r_lte = abs(aspect_ratio - lte[0].aspect_ratio) # FIXME:
r_gte = abs(aspect_ratio - gte[0].aspect_ratio)
if r_lte >= r_gte:
return_pope = habemus_papam(aspect_ratio, gte[0])
else:
return_pope = habemus_papam(aspect_ratio, lte[0])
elif gte:
return_pope = gte[0]
elif lte:
return_pope = lte[0]
else:
return None
return return_pope
def habemus_papam(aspect_ratio, pope):
pp = PerfectPope(aspect_ratio=aspect_ratio, pope=pope)
pp.save() # FIXME:
return pope
def unpopable(width, height):
if width == 0 or height == 0:
return True
if (width+height) > 9000:
return True
return False
def read_pope(width, height, pope):
""" (int, int, Pope) -> bytes
"""
im = Image.open(pope.path)
im = im.resize((width, height))
f = BytesIO() # FIXME: ceriously.
im.save(f, "jpeg")
f.seek(0)
return f.read()
def parse_pope(path):
im = Image.open(path)
width, height = im.size
aspect_ratio = round(width/height, decimal_places)
return Pope(path=path, width=width, height=height, aspect_ratio=aspect_ratio)