1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from random import randint
6 from django import template
7 from django.urls import reverse
8 from django.utils.cache import add_never_cache_headers
9 import sorl.thumbnail.default
10 from catalogue.utils import split_tags
11 from ..engine import CustomCroppingEngine
12 from ..models import Picture
15 register = template.Library()
17 cropper = CustomCroppingEngine()
20 @register.simple_tag()
21 def area_thumbnail_url(area, geometry):
22 def to_square(coords):
23 w = coords[1][0] - coords[0][0]
24 h = coords[1][1] - coords[0][1]
28 return [[coords[0][0] + w/2 - h/2, coords[0][1]],
29 [coords[1][0] - w/2 + h/2, coords[1][1]]]
31 return [[coords[0][0], coords[0][1] + h/2 - w/2],
32 [coords[1][0], coords[1][1] - h/2 + w/2, ]]
34 # so much for sorl extensibility.
35 # what to do about this?
36 _engine = sorl.thumbnail.default.engine
37 sorl.thumbnail.default.engine = cropper
38 coords = to_square(area.get_area_json())
41 th = sorl.thumbnail.default.backend.get_thumbnail(
42 area.picture.image_file,
44 crop="%dpx %dpx %dpx %dpx" % tuple(map(lambda d: max(0, d), tuple(coords[0] + coords[1]))))
45 except ZeroDivisionError:
47 except Exception as e:
48 logging.exception("Error creating a thumbnail for PictureArea")
51 sorl.thumbnail.default.engine = _engine
57 def picture_random_picture(exclude_ids):
58 queryset = Picture.objects.exclude(pk__in=exclude_ids).exclude(image_file='')
59 count = queryset.count()
61 return queryset[randint(0, count - 1)]