forked from theatlantic/django-cropduster
/
models.py
286 lines (211 loc) · 7.69 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
from django.db import models
from django.conf import settings
import os
from cropduster import utils
from PIL import Image as pil
from south.modelsinspector import add_introspection_rules
from django.core.exceptions import ValidationError
CROPDUSTER_UPLOAD_PATH = getattr(settings, 'CROPDUSTER_UPLOAD_PATH', "")
IMAGE_SAVE_PARAMS = {"quality" :95}
GENERATION_CHOICES = (
(0, "Manually Crop"),
(1, "Auto-Crop"),
(2, "Auto-Size"),
)
try:
from caching.base import CachingMixin, CachingManager
except ImportError:
class CachingMixin(object):
pass
CachingManager = models.Manager
class SizeSet(CachingMixin, models.Model):
objects = CachingManager()
name = models.CharField(max_length=255, db_index=True)
slug = models.SlugField(max_length=50, null=False,)
def __unicode__(self):
return u"%s" % self.name
def get_size_by_ratio(self, created=False):
""" Shorthand to get all the unique ratios for display in the admin,
rather than show every possible thumbnail
"""
size_query = Size.objects.all().filter(size_set__id=self.id)
# Whether to only get the image sizes that have been created
if created:
size_query = size_query.filter(create_on_request=False)
size_query.query.group_by = ["aspect_ratio"]
try:
return size_query
except ValueError:
return None
class SizeManager(CachingManager):
def get_size_by_ratio(self, size_set, aspect_ratio_id):
size_query = Size.objects.all().only("aspect_ratio").filter(size_set=size_set, auto_size=0).order_by("-aspect_ratio")
size_query.query.group_by = ["aspect_ratio"]
try:
size = size_query[aspect_ratio_id]
# get the largest size with this aspect ratio
return Size.objects.all().filter(size_set=size_set, aspect_ratio=size.aspect_ratio, auto_size=0).order_by("-width")[0]
except:
return None
class Size(CachingMixin, models.Model):
objects = SizeManager()
name = models.CharField(max_length=255, db_index=True)
slug = models.SlugField(max_length=50, null=False,)
height = models.PositiveIntegerField(blank=True, null=True)
width = models.PositiveIntegerField(blank=True, null=True)
auto_size = models.PositiveIntegerField("Thumbnail Generation", default=0, choices=GENERATION_CHOICES)
size_set = models.ForeignKey(SizeSet)
aspect_ratio = models.FloatField(default=1)
create_on_request = models.BooleanField("Crop on request", default=False)
def clean(self):
if not (self.width or self.height):
raise ValidationError("Size requires either a width, a height, or both")
elif GENERATION_CHOICES[self.auto_size][1] == "Auto-Crop" and not (self.width and self.height):
"""
Raise a validation error if one of the sizes is not set for cropping.
Auto-size is the only one that can take a missing size.
"""
raise ValidationError("Auto-crop requires both sizes be specified")
def save(self, *args, **kwargs):
self.aspect_ratio = utils.aspect_ratio(self.width, self.height)
super(Size, self).save(*args, **kwargs)
class Meta:
db_table = "cropduster_size"
def __unicode__(self):
return u"%s: %sx%s" % (self.name, self.width, self.height)
class Crop(CachingMixin, models.Model):
class Meta:
db_table = "cropduster_crop"
unique_together = (("size", "image"),)
objects = CachingManager()
crop_x = models.PositiveIntegerField(default=0, blank=True, null=True)
crop_y = models.PositiveIntegerField(default=0, blank=True, null=True)
crop_w = models.PositiveIntegerField(default=0, blank=True, null=True)
crop_h = models.PositiveIntegerField(default=0, blank=True, null=True)
size = models.ForeignKey(
"cropduster.Size",
related_name = "size",
verbose_name = "sizes",
)
image = models.ForeignKey(
"cropduster.Image",
related_name = "images",
verbose_name = "images",
)
def __unicode__(self):
return u"%s: %sx%s" % (self.image.image, self.size.width, self.size.height)
def save(self, *args, **kwargs):
super(Crop, self).save(*args, **kwargs)
if self.size:
# get all the manually cropped sizes with the same aspect ratio as this crop/size
sizes = Size.objects.all().filter(
aspect_ratio=self.size.aspect_ratio,
size_set=self.size.size_set,
auto_size=0,
create_on_request=False
).order_by("-width")
if sizes:
# create the cropped image
cropped_image = utils.create_cropped_image(
self.image.image.path,
self.crop_x,
self.crop_y,
self.crop_w,
self.crop_h
)
# loop through the other sizes of the same aspect ratio, and create those crops
for size in sizes:
thumbnail = utils.rescale(cropped_image, size.width, size.height, crop=size.auto_size)
if not os.path.exists(self.image.folder_path):
os.makedirs(self.image.folder_path)
thumbnail.save(self.image.thumbnail_path(size.slug), **IMAGE_SAVE_PARAMS)
class Image(CachingMixin, models.Model):
objects = CachingManager()
image = models.ImageField(
upload_to=settings.CROPDUSTER_UPLOAD_PATH + "%Y/%m/%d",
max_length=255,
db_index=True
)
size_set = models.ForeignKey(
SizeSet,
)
attribution = models.CharField(max_length=255, blank=True, null=True)
caption = models.CharField(max_length=255, blank=True, null=True)
def save(self, *args, **kwargs):
super(Image, self).save(*args, **kwargs)
# get all the auto sized thumbnails and create them
sizes = self.size_set.size_set.all().filter(
auto_size__in=[1,2],
create_on_request=False
)
for size in sizes:
self.create_individual_thumbnail(size)
def create_individual_thumbnail(self, size):
auto_crop = True if size.auto_size == 1 else False
if size.auto_size == 0:
try:
crop = Crop.objects.get(size=size, image=self)
cropped_image = utils.create_cropped_image(
self.image.path,
crop.crop_x,
crop.crop_y,
crop.crop_w,
crop.crop_h
)
except Crop.DoesNotExist:
# auto-crop if no crop is defined
cropped_image = pil.open(self.image.path)
auto_crop = True
else:
cropped_image = pil.open(self.image.path)
thumbnail = utils.rescale(cropped_image, size.width, size.height, crop=auto_crop)
if not os.path.exists(self.folder_path):
os.makedirs(self.folder_path)
thumbnail.save(self.thumbnail_path(size.slug), **IMAGE_SAVE_PARAMS)
class Meta:
db_table = "cropduster_image"
verbose_name = "Image"
verbose_name_plural = "Image"
@property
def extension(self):
file_root, extension = os.path.splitext(self.image.path)
return extension
@property
def folder_path(self):
file_path, file = os.path.split(self.image.path)
file_root, extension = os.path.splitext(file)
return u"%s" % os.path.join(file_path, file_root)
def thumbnail_path(self, size_slug):
file_path, file = os.path.split(self.image.path)
file_root, extension = os.path.splitext(file)
return u"%s" % os.path.join(file_path, file_root, size_slug) + extension
@property
def folder_url(self):
file_path, file = os.path.split(self.image.url)
file_root, extension = os.path.splitext(file)
return u"%s" % os.path.join(file_path, file_root)
def thumbnail_url(self, size_slug):
file_path, file = os.path.split(self.image.url)
file_root, extension = os.path.splitext(file)
return u"%s" % os.path.join(file_path, file_root, size_slug) + extension
def has_size(self, size_slug):
try:
size = self.size_set.size_set.get(slug=size_slug)
return True
except Size.DoesNotExist:
return False
def __unicode__(self):
if self.image:
return u"%s" % self.image.url
else:
return ""
def get_absolute_url(self):
return settings.STATIC_URL + self.image
class CropDusterField(models.ForeignKey):
pass
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^cropduster\.models\.CropDusterField"])