1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25 from mediagoblin
import mg_globals
as mgg
26 from mediagoblin
.processing
import (
27 BadMediaFail
, FilenameBuilder
,
28 MediaProcessor
, ProcessingManager
,
29 request_from_args
, get_process_filename
,
30 store_public
, copy_original
)
31 from mediagoblin
.tools
.exif
import exif_fix_image_orientation
, \
32 extract_exif
, clean_exif
, get_gps_data
, get_useful
, \
33 exif_image_needs_rotation
35 _log
= logging
.getLogger(__name__
)
38 'NEAREST': Image
.NEAREST
,
39 'BILINEAR': Image
.BILINEAR
,
40 'BICUBIC': Image
.BICUBIC
,
41 'ANTIALIAS': Image
.ANTIALIAS
}
43 MEDIA_TYPE
= 'mediagoblin.media_types.image'
46 def resize_image(entry
, resized
, keyname
, target_name
, new_size
,
47 exif_tags
, workdir
, quality
, filter):
49 Store a resized version of an image and return its pathname.
52 proc_state -- the processing state for the image to resize
53 resized -- an image from Image.open() of the original image being resized
54 keyname -- Under what key to save in the db.
55 target_name -- public file path for the new resized image
56 exif_tags -- EXIF data for the original image
57 workdir -- directory path for storing converted image files
58 new_size -- 2-tuple size for the resized image
59 quality -- level of compression used when resizing images
60 filter -- One of BICUBIC, BILINEAR, NEAREST, ANTIALIAS
62 resized
= exif_fix_image_orientation(resized
, exif_tags
) # Fix orientation
65 resize_filter
= PIL_FILTERS
[filter.upper()]
67 raise Exception('Filter "{0}" not found, choose one of {1}'.format(
69 u
', '.join(PIL_FILTERS
.keys())))
71 resized
.thumbnail(new_size
, resize_filter
)
73 # Copy the new file to the conversion subdir, then remotely.
74 tmp_resized_filename
= os
.path
.join(workdir
, target_name
)
75 with
file(tmp_resized_filename
, 'w') as resized_file
:
76 resized
.save(resized_file
, quality
=quality
)
77 store_public(entry
, keyname
, tmp_resized_filename
, target_name
)
79 # store the thumb/medium info
80 image_info
= {'width': new_size
[0],
81 'height': new_size
[1],
85 entry
.set_file_metadata(keyname
, **image_info
)
88 def resize_tool(entry
,
89 force
, keyname
, orig_file
, target_name
,
90 conversions_subdir
, exif_tags
, quality
, filter, new_size
=None):
91 # Use the default size if new_size was not given
93 max_width
= mgg
.global_config
['media:' + keyname
]['max_width']
94 max_height
= mgg
.global_config
['media:' + keyname
]['max_height']
95 new_size
= (max_width
, max_height
)
97 # If thumb or medium is already the same quality and size, then don't
99 if _skip_resizing(entry
, keyname
, new_size
, quality
, filter):
100 _log
.info('{0} of same size and quality already in use, skipping '
101 'resizing of media {1}.'.format(keyname
, entry
.id))
104 # If the size of the original file exceeds the specified size for the desized
105 # file, a target_name file is created and later associated with the media
107 # Also created if the file needs rotation, or if forced.
109 im
= Image
.open(orig_file
)
113 or im
.size
[0] > new_size
[0]\
114 or im
.size
[1] > new_size
[1]\
115 or exif_image_needs_rotation(exif_tags
):
117 entry
, im
, unicode(keyname
), target_name
,
119 exif_tags
, conversions_subdir
,
123 def _skip_resizing(entry
, keyname
, size
, quality
, filter):
125 Determines wither the saved thumb or medium is of the same quality and size
127 image_info
= entry
.get_file_metadata(keyname
)
134 if image_info
.get('width') != size
[0]:
137 elif image_info
.get('height') != size
[1]:
140 elif image_info
.get('filter') != filter:
143 elif image_info
.get('quality') != quality
:
149 SUPPORTED_FILETYPES
= ['png', 'gif', 'jpg', 'jpeg', 'tiff']
152 def sniff_handler(media_file
, **kw
):
153 _log
.info('Sniffing {0}'.format(MEDIA_TYPE
))
154 if kw
.get('media') is not None: # That's a double negative!
155 name
, ext
= os
.path
.splitext(kw
['media'].filename
)
156 clean_ext
= ext
[1:].lower() # Strip the . from ext and make lowercase
158 if clean_ext
in SUPPORTED_FILETYPES
:
159 _log
.info('Found file extension in supported filetypes')
162 _log
.debug('Media present, extension not found in {0}'.format(
163 SUPPORTED_FILETYPES
))
165 _log
.warning('Need additional information (keyword argument \'media\')'
166 ' to be able to handle sniffing')
171 class CommonImageProcessor(MediaProcessor
):
173 Provides a base for various media processing steps
175 # list of acceptable file keys in order of prefrence for reprocessing
176 acceptable_files
= ['original', 'medium']
178 def common_setup(self
):
180 Set up the workbench directory and pull down the original file
182 self
.image_config
= mgg
.global_config
[
183 'media_type:mediagoblin.media_types.image']
185 ## @@: Should this be two functions?
186 # Conversions subdirectory to avoid collisions
187 self
.conversions_subdir
= os
.path
.join(
188 self
.workbench
.dir, 'convirsions')
189 os
.mkdir(self
.conversions_subdir
)
191 # Pull down and set up the processing file
192 self
.process_filename
= get_process_filename(
193 self
.entry
, self
.workbench
, self
.acceptable_files
)
194 self
.name_builder
= FilenameBuilder(self
.process_filename
)
197 self
.exif_tags
= extract_exif(self
.process_filename
)
199 def generate_medium_if_applicable(self
, size
=None, quality
=None,
202 quality
= self
.image_config
['quality']
204 filter = self
.image_config
['resize_filter']
206 resize_tool(self
.entry
, False, 'medium', self
.process_filename
,
207 self
.name_builder
.fill('{basename}.medium{ext}'),
208 self
.conversions_subdir
, self
.exif_tags
, quality
,
211 def generate_thumb(self
, size
=None, quality
=None, filter=None):
213 quality
= self
.image_config
['quality']
215 filter = self
.image_config
['resize_filter']
217 resize_tool(self
.entry
, True, 'thumb', self
.process_filename
,
218 self
.name_builder
.fill('{basename}.thumbnail{ext}'),
219 self
.conversions_subdir
, self
.exif_tags
, quality
,
222 def copy_original(self
):
224 self
.entry
, self
.process_filename
,
225 self
.name_builder
.fill('{basename}{ext}'))
227 def extract_metadata(self
):
228 # Is there any GPS data
229 gps_data
= get_gps_data(self
.exif_tags
)
231 # Insert exif data into database
232 exif_all
= clean_exif(self
.exif_tags
)
235 self
.entry
.media_data_init(exif_all
=exif_all
)
238 for key
in list(gps_data
.keys()):
239 gps_data
['gps_' + key
] = gps_data
.pop(key
)
240 self
.entry
.media_data_init(**gps_data
)
243 class InitialProcessor(CommonImageProcessor
):
245 Initial processing step for new images
248 description
= "Initial processing"
251 def media_is_eligible(cls
, entry
=None, state
=None):
253 Determine if this media type is eligible for processing
258 "unprocessed", "failed")
260 ###############################
261 # Command line interface things
262 ###############################
265 def generate_parser(cls
):
266 parser
= argparse
.ArgumentParser(
267 description
=cls
.description
,
273 metavar
=('max_width', 'max_height'),
279 metavar
=('max_width', 'max_height'),
284 choices
=['BICUBIC', 'BILINEAR', 'NEAREST', 'ANTIALIAS'])
289 help='level of compression used when resizing images')
294 def args_to_request(cls
, args
):
295 return request_from_args(
296 args
, ['size', 'thumb_size', 'filter', 'quality'])
298 def process(self
, size
=None, thumb_size
=None, quality
=None, filter=None):
300 self
.generate_medium_if_applicable(size
=size
, filter=filter,
302 self
.generate_thumb(size
=thumb_size
, filter=filter, quality
=quality
)
304 self
.extract_metadata()
305 self
.delete_queue_file()
308 class Resizer(CommonImageProcessor
):
310 Resizing process steps for processed media
313 description
= 'Resize image'
317 def media_is_eligible(cls
, entry
=None, state
=None):
319 Determine if this media type is eligible for processing
323 return state
in 'processed'
325 ###############################
326 # Command line interface things
327 ###############################
330 def generate_parser(cls
):
331 parser
= argparse
.ArgumentParser(
332 description
=cls
.description
,
338 metavar
=('max_width', 'max_height'),
343 choices
=['BICUBIC', 'BILINEAR', 'NEAREST', 'ANTIALIAS'])
348 help='level of compression used when resizing images')
352 choices
=['medium', 'thumb'])
357 def args_to_request(cls
, args
):
358 return request_from_args(
359 args
, ['size', 'file', 'quality', 'filter'])
361 def process(self
, file, size
=None, filter=None, quality
=None):
364 self
.generate_medium_if_applicable(size
=size
, filter=filter,
366 elif file == 'thumb':
367 self
.generate_thumb(size
=size
, filter=filter, quality
=quality
)
370 class ImageProcessingManager(ProcessingManager
):
372 super(self
.__class
__, self
).__init
__()
373 self
.add_processor(InitialProcessor
)
374 self
.add_processor(Resizer
)
377 if __name__
== '__main__':
381 pp
= pprint
.PrettyPrinter()
383 result
= extract_exif(sys
.argv
[1])
384 gps
= get_gps_data(result
)
385 clean
= clean_exif(result
)
386 useful
= get_useful(clean
)