111 lines
2.8 KiB
Python
111 lines
2.8 KiB
Python
from papiezator.models import PopeImage, PerfectPope, DECIMAL_PLACES
|
|
from PIL import Image
|
|
from io import BytesIO
|
|
from django.core.exceptions import ObjectDoesNotExist
|
|
from papiezator.papiezator_settings import REDIS_TTL, SAGE_REDIS
|
|
|
|
try:
|
|
from redis import Redis
|
|
from redis.exceptions import ConnectionError as RedisConnectionError
|
|
redis = Redis()
|
|
except ImportError:
|
|
redis = None
|
|
|
|
|
|
def habemus_papam(func):
|
|
"""Your friendly, pointless decorator ;3
|
|
|
|
"""
|
|
|
|
def inner(aspect_ratio, pope):
|
|
pp = PerfectPope.objects.filter(aspect_ratio=aspect_ratio, pope=pope)
|
|
if pp: return pp[0].image
|
|
|
|
PopeImage = func(aspect_ratio, pope)
|
|
pp = PerfectPope(aspect_ratio=aspect_ratio, image=PopeImage, pope=pope)
|
|
pp.save()
|
|
return PopeImage
|
|
|
|
return inner
|
|
|
|
|
|
@habemus_papam
|
|
def select_best_pope(aspect_ratio, pope):
|
|
""" (float, Pope) -> PopeImage
|
|
|
|
"""
|
|
# popes below and above this ratio
|
|
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:
|
|
p = min(
|
|
[lte[0], gte[0]],
|
|
key=lambda x: abs(aspect_ratio - x.aspect_ratio)
|
|
)
|
|
return p
|
|
|
|
# if there are no popes above or below this ratio # do i want to get rid of this?
|
|
elif gte: return gte[0]
|
|
elif lte: return lte[0]
|
|
else: return None
|
|
|
|
|
|
def unpopable(width, height):
|
|
if width == 0 or height == 0:
|
|
return True
|
|
if (width+height) >= 9001:
|
|
return True
|
|
return False
|
|
|
|
|
|
def redis_me(func,):
|
|
def inner(*args, **kwargs):
|
|
if not redis or SAGE_REDIS:
|
|
return func(*args, **kwargs)
|
|
|
|
try:
|
|
image = redis.get(args)
|
|
if not image:
|
|
image = func(*args, **kwargs)
|
|
redis.set(args, image) # FIXME: perhaps some better key value?
|
|
redis.expire(args, REDIS_TTL)
|
|
return image
|
|
except RedisConnectionError:
|
|
return func(*args, **kwargs)
|
|
|
|
return inner
|
|
|
|
|
|
@redis_me
|
|
def read_pope(width, height, pope_image):
|
|
""" (int, int, PopeImage) -> bytes
|
|
get pope for display
|
|
"""
|
|
im = Image.open(pope_image.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
|