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/>.
17 from __future__
import print_function
29 from mediagoblin
import mg_globals
as mgg
30 from mediagoblin
.db
.models
import Location
31 from mediagoblin
.processing
import (
32 BadMediaFail
, FilenameBuilder
,
33 MediaProcessor
, ProcessingManager
,
34 request_from_args
, get_process_filename
,
35 store_public
, copy_original
)
36 from mediagoblin
.tools
.exif
import exif_fix_image_orientation
, \
37 extract_exif
, clean_exif
, get_gps_data
, get_useful
, \
38 exif_image_needs_rotation
40 _log
= logging
.getLogger(__name__
)
43 'NEAREST': Image
.NEAREST
,
44 'BILINEAR': Image
.BILINEAR
,
45 'BICUBIC': Image
.BICUBIC
,
46 'ANTIALIAS': Image
.ANTIALIAS
}
48 MEDIA_TYPE
= 'mediagoblin.media_types.image'
51 def resize_image(entry
, resized
, keyname
, target_name
, new_size
,
52 exif_tags
, workdir
, quality
, filter):
54 Store a resized version of an image and return its pathname.
57 proc_state -- the processing state for the image to resize
58 resized -- an image from Image.open() of the original image being resized
59 keyname -- Under what key to save in the db.
60 target_name -- public file path for the new resized image
61 exif_tags -- EXIF data for the original image
62 workdir -- directory path for storing converted image files
63 new_size -- 2-tuple size for the resized image
64 quality -- level of compression used when resizing images
65 filter -- One of BICUBIC, BILINEAR, NEAREST, ANTIALIAS
67 resized
= exif_fix_image_orientation(resized
, exif_tags
) # Fix orientation
70 resize_filter
= PIL_FILTERS
[filter.upper()]
72 raise Exception('Filter "{0}" not found, choose one of {1}'.format(
73 six
.text_type(filter),
74 u
', '.join(PIL_FILTERS
.keys())))
76 resized
.thumbnail(new_size
, resize_filter
)
78 # Copy the new file to the conversion subdir, then remotely.
79 tmp_resized_filename
= os
.path
.join(workdir
, target_name
)
80 resized
.save(tmp_resized_filename
, quality
=quality
)
81 store_public(entry
, keyname
, tmp_resized_filename
, target_name
)
83 # store the thumb/medium info
84 image_info
= {'width': new_size
[0],
85 'height': new_size
[1],
89 entry
.set_file_metadata(keyname
, **image_info
)
92 def resize_tool(entry
,
93 force
, keyname
, orig_file
, target_name
,
94 conversions_subdir
, exif_tags
, quality
, filter, new_size
=None):
95 # Use the default size if new_size was not given
97 max_width
= mgg
.global_config
['media:' + keyname
]['max_width']
98 max_height
= mgg
.global_config
['media:' + keyname
]['max_height']
99 new_size
= (max_width
, max_height
)
101 # If thumb or medium is already the same quality and size, then don't
103 if _skip_resizing(entry
, keyname
, new_size
, quality
, filter):
104 _log
.info('{0} of same size and quality already in use, skipping '
105 'resizing of media {1}.'.format(keyname
, entry
.id))
108 # If the size of the original file exceeds the specified size for the desized
109 # file, a target_name file is created and later associated with the media
111 # Also created if the file needs rotation, or if forced.
113 im
= Image
.open(orig_file
)
117 or im
.size
[0] > new_size
[0]\
118 or im
.size
[1] > new_size
[1]\
119 or exif_image_needs_rotation(exif_tags
):
121 entry
, im
, six
.text_type(keyname
), target_name
,
123 exif_tags
, conversions_subdir
,
127 def _skip_resizing(entry
, keyname
, size
, quality
, filter):
129 Determines wither the saved thumb or medium is of the same quality and size
131 image_info
= entry
.get_file_metadata(keyname
)
138 if image_info
.get('width') != size
[0]:
141 elif image_info
.get('height') != size
[1]:
144 elif image_info
.get('filter') != filter:
147 elif image_info
.get('quality') != quality
:
153 SUPPORTED_FILETYPES
= ['png', 'gif', 'jpg', 'jpeg', 'tiff']
156 def sniff_handler(media_file
, filename
):
157 _log
.info('Sniffing {0}'.format(MEDIA_TYPE
))
158 name
, ext
= os
.path
.splitext(filename
)
159 clean_ext
= ext
[1:].lower() # Strip the . from ext and make lowercase
161 if clean_ext
in SUPPORTED_FILETYPES
:
162 _log
.info('Found file extension in supported filetypes')
165 _log
.debug('Media present, extension not found in {0}'.format(
166 SUPPORTED_FILETYPES
))
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
['plugins'][
183 '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, 'conversions')
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
, file):
228 """ Extract all the metadata from the image and store """
229 # Extract GPS data and store in Location
230 gps_data
= get_gps_data(self
.exif_tags
)
233 Location
.create({"position": gps_data
}, self
.entry
)
235 # Insert exif data into database
236 exif_all
= clean_exif(self
.exif_tags
)
239 self
.entry
.media_data_init(exif_all
=exif_all
)
241 # Extract file metadata
243 im
= Image
.open(self
.process_filename
)
249 "height": im
.size
[1],
252 self
.entry
.set_file_metadata(file, **metadata
)
255 class InitialProcessor(CommonImageProcessor
):
257 Initial processing step for new images
260 description
= "Initial processing"
263 def media_is_eligible(cls
, entry
=None, state
=None):
265 Determine if this media type is eligible for processing
267 if entry
is None and state
is None:
268 raise ValueError("Must specify either entry or state")
273 "unprocessed", "failed")
275 ###############################
276 # Command line interface things
277 ###############################
280 def generate_parser(cls
):
281 parser
= argparse
.ArgumentParser(
282 description
=cls
.description
,
288 metavar
=('max_width', 'max_height'),
294 metavar
=('max_width', 'max_height'),
299 choices
=['BICUBIC', 'BILINEAR', 'NEAREST', 'ANTIALIAS'])
304 help='level of compression used when resizing images')
309 def args_to_request(cls
, args
):
310 return request_from_args(
311 args
, ['size', 'thumb_size', 'filter', 'quality'])
313 def process(self
, size
=None, thumb_size
=None, quality
=None, filter=None):
315 self
.generate_medium_if_applicable(size
=size
, filter=filter,
317 self
.generate_thumb(size
=thumb_size
, filter=filter, quality
=quality
)
319 self
.extract_metadata('original')
320 self
.delete_queue_file()
323 class Resizer(CommonImageProcessor
):
325 Resizing process steps for processed media
328 description
= 'Resize image'
332 def media_is_eligible(cls
, entry
=None, state
=None):
334 Determine if this media type is eligible for processing
336 if entry
is None and state
is None:
337 raise ValueError("Must specify either entry or state")
341 return state
in 'processed'
343 ###############################
344 # Command line interface things
345 ###############################
348 def generate_parser(cls
):
349 parser
= argparse
.ArgumentParser(
350 description
=cls
.description
,
356 metavar
=('max_width', 'max_height'),
361 choices
=['BICUBIC', 'BILINEAR', 'NEAREST', 'ANTIALIAS'])
366 help='level of compression used when resizing images')
370 choices
=['medium', 'thumb'])
375 def args_to_request(cls
, args
):
376 return request_from_args(
377 args
, ['size', 'file', 'quality', 'filter'])
379 def process(self
, file, size
=None, filter=None, quality
=None):
382 self
.generate_medium_if_applicable(size
=size
, filter=filter,
384 elif file == 'thumb':
385 self
.generate_thumb(size
=size
, filter=filter, quality
=quality
)
387 self
.extract_metadata(file)
389 class MetadataProcessing(CommonImageProcessor
):
390 """ Extraction and storage of media's metadata for processed images """
392 name
= 'metadatabuilder'
393 description
= 'Add or update image metadata'
396 def media_is_eligible(cls
, entry
=None, state
=None):
397 if entry
is None and state
is None:
398 raise ValueError("Must specify either entry or state")
403 return state
== 'processed'
406 def generate_parser(cls
):
407 parser
= argparse
.ArgumentParser(
408 description
=cls
.description
,
414 choices
=['original', 'medium', 'thumb']
420 def args_to_request(cls
, args
):
421 return request_from_args(args
, ['file'])
423 def process(self
, file):
425 self
.extract_metadata(file)
427 class ImageProcessingManager(ProcessingManager
):
429 super(ImageProcessingManager
, self
).__init
__()
430 self
.add_processor(InitialProcessor
)
431 self
.add_processor(Resizer
)
432 self
.add_processor(MetadataProcessing
)
434 if __name__
== '__main__':
438 pp
= pprint
.PrettyPrinter()
440 result
= extract_exif(sys
.argv
[1])
441 gps
= get_gps_data(result
)
442 clean
= clean_exif(result
)
443 useful
= get_useful(clean
)
445 print(pp
.pprint(clean
))