papiez_ipsum/src/papiezator/pope_utils.py

77 lines
1.9 KiB
Python

from papiezator.models import Pope, PopeImage, PerfectPope, DECIMAL_PLACES
from PIL import Image
from io import BytesIO # FIXME:
from django.core.exceptions import ObjectDoesNotExist
def select_best_pope(aspect_ratio, pope):
""" (float, pope) -> PopeImage
"""
pp = PerfectPope.objects.filter(aspect_ratio=aspect_ratio, pope=pope)
if pp:
return pp[0].image
lte = PopeImage.objects.filter(aspect_ratio__lte=aspect_ratio, pope=pope).order_by('-aspect_ratio')[0:1]
gte = PopeImage.objects.filter(aspect_ratio__gte=aspect_ratio, pope=pope).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], pope)
else:
return_pope = habemus_papam(aspect_ratio, lte[0], pope)
elif gte:
return_pope = gte[0]
elif lte:
return_pope = lte[0]
else:
return None
return return_pope
def habemus_papam(aspect_ratio, image, pope):
pp = PerfectPope(aspect_ratio=aspect_ratio, image=image, pope=pope)
pp.save() # FIXME:
return image
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 PopeImage(path=path, width=width, height=height, aspect_ratio=aspect_ratio)
def pope_or_death(p, **kwargs):
try:
x = p.objects.get(**kwargs)
except ObjectDoesNotExist:
x = None
return x