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
27 from mediagoblin
import mg_globals
as mgg
28 from mediagoblin
.processing
import (
29 BadMediaFail
, FilenameBuilder
,
30 MediaProcessor
, ProcessingManager
,
31 request_from_args
, get_process_filename
,
32 store_public
, copy_original
)
33 from mediagoblin
.tools
.exif
import exif_fix_image_orientation
, \
34 extract_exif
, clean_exif
, get_gps_data
, get_useful
, \
35 exif_image_needs_rotation
37 _log
= logging
.getLogger(__name__
)
40 'NEAREST': Image
.NEAREST
,
41 'BILINEAR': Image
.BILINEAR
,
42 'BICUBIC': Image
.BICUBIC
,
43 'ANTIALIAS': Image
.ANTIALIAS
}
45 MEDIA_TYPE
= 'mediagoblin.media_types.image'
48 def resize_image(entry
, resized
, keyname
, target_name
, new_size
,
49 exif_tags
, workdir
, quality
, filter):
51 Store a resized version of an image and return its pathname.
54 proc_state -- the processing state for the image to resize
55 resized -- an image from Image.open() of the original image being resized
56 keyname -- Under what key to save in the db.
57 target_name -- public file path for the new resized image
58 exif_tags -- EXIF data for the original image
59 workdir -- directory path for storing converted image files
60 new_size -- 2-tuple size for the resized image
61 quality -- level of compression used when resizing images
62 filter -- One of BICUBIC, BILINEAR, NEAREST, ANTIALIAS
64 resized
= exif_fix_image_orientation(resized
, exif_tags
) # Fix orientation
67 resize_filter
= PIL_FILTERS
[filter.upper()]
69 raise Exception('Filter "{0}" not found, choose one of {1}'.format(
71 u
', '.join(PIL_FILTERS
.keys())))
73 resized
.thumbnail(new_size
, resize_filter
)
75 # Copy the new file to the conversion subdir, then remotely.
76 tmp_resized_filename
= os
.path
.join(workdir
, target_name
)
77 with
file(tmp_resized_filename
, 'w') as resized_file
:
78 resized
.save(resized_file
, quality
=quality
)
79 store_public(entry
, keyname
, tmp_resized_filename
, target_name
)
81 # store the thumb/medium info
82 image_info
= {'width': new_size
[0],
83 'height': new_size
[1],
87 entry
.set_file_metadata(keyname
, **image_info
)
90 def resize_tool(entry
,
91 force
, keyname
, orig_file
, target_name
,
92 conversions_subdir
, exif_tags
, quality
, filter, new_size
=None):
93 # Use the default size if new_size was not given
95 max_width
= mgg
.global_config
['media:' + keyname
]['max_width']
96 max_height
= mgg
.global_config
['media:' + keyname
]['max_height']
97 new_size
= (max_width
, max_height
)
99 # If thumb or medium is already the same quality and size, then don't
101 if _skip_resizing(entry
, keyname
, new_size
, quality
, filter):
102 _log
.info('{0} of same size and quality already in use, skipping '
103 'resizing of media {1}.'.format(keyname
, entry
.id))
106 # If the size of the original file exceeds the specified size for the desized
107 # file, a target_name file is created and later associated with the media
109 # Also created if the file needs rotation, or if forced.
111 im
= Image
.open(orig_file
)
115 or im
.size
[0] > new_size
[0]\
116 or im
.size
[1] > new_size
[1]\
117 or exif_image_needs_rotation(exif_tags
):
119 entry
, im
, unicode(keyname
), target_name
,
121 exif_tags
, conversions_subdir
,
125 def _skip_resizing(entry
, keyname
, size
, quality
, filter):
127 Determines wither the saved thumb or medium is of the same quality and size
129 image_info
= entry
.get_file_metadata(keyname
)
136 if image_info
.get('width') != size
[0]:
139 elif image_info
.get('height') != size
[1]:
142 elif image_info
.get('filter') != filter:
145 elif image_info
.get('quality') != quality
:
151 SUPPORTED_FILETYPES
= ['png', 'gif', 'jpg', 'jpeg', 'tiff']
154 def sniff_handler(media_file
, filename
):
155 _log
.info('Sniffing {0}'.format(MEDIA_TYPE
))
156 name
, ext
= os
.path
.splitext(filename
)
157 clean_ext
= ext
[1:].lower() # Strip the . from ext and make lowercase
159 if clean_ext
in SUPPORTED_FILETYPES
:
160 _log
.info('Found file extension in supported filetypes')
163 _log
.debug('Media present, extension not found in {0}'.format(
164 SUPPORTED_FILETYPES
))
169 class CommonImageProcessor(MediaProcessor
):
171 Provides a base for various media processing steps
173 # list of acceptable file keys in order of prefrence for reprocessing
174 acceptable_files
= ['original', 'medium']
176 def common_setup(self
):
178 Set up the workbench directory and pull down the original file
180 self
.image_config
= mgg
.global_config
['plugins'][
181 'mediagoblin.media_types.image']
183 ## @@: Should this be two functions?
184 # Conversions subdirectory to avoid collisions
185 self
.conversions_subdir
= os
.path
.join(
186 self
.workbench
.dir, 'conversions')
187 os
.mkdir(self
.conversions_subdir
)
189 # Pull down and set up the processing file
190 self
.process_filename
= get_process_filename(
191 self
.entry
, self
.workbench
, self
.acceptable_files
)
192 self
.name_builder
= FilenameBuilder(self
.process_filename
)
195 self
.exif_tags
= extract_exif(self
.process_filename
)
197 def generate_medium_if_applicable(self
, size
=None, quality
=None,
200 quality
= self
.image_config
['quality']
202 filter = self
.image_config
['resize_filter']
204 resize_tool(self
.entry
, False, 'medium', self
.process_filename
,
205 self
.name_builder
.fill('{basename}.medium{ext}'),
206 self
.conversions_subdir
, self
.exif_tags
, quality
,
209 def generate_thumb(self
, size
=None, quality
=None, filter=None):
211 quality
= self
.image_config
['quality']
213 filter = self
.image_config
['resize_filter']
215 resize_tool(self
.entry
, True, 'thumb', self
.process_filename
,
216 self
.name_builder
.fill('{basename}.thumbnail{ext}'),
217 self
.conversions_subdir
, self
.exif_tags
, quality
,
220 def copy_original(self
):
222 self
.entry
, self
.process_filename
,
223 self
.name_builder
.fill('{basename}{ext}'))
225 def extract_metadata(self
):
226 # Is there any GPS data
227 gps_data
= get_gps_data(self
.exif_tags
)
229 # Insert exif data into database
230 exif_all
= clean_exif(self
.exif_tags
)
233 self
.entry
.media_data_init(exif_all
=exif_all
)
236 for key
in list(gps_data
.keys()):
237 gps_data
['gps_' + key
] = gps_data
.pop(key
)
238 self
.entry
.media_data_init(**gps_data
)
241 class InitialProcessor(CommonImageProcessor
):
243 Initial processing step for new images
246 description
= "Initial processing"
249 def media_is_eligible(cls
, entry
=None, state
=None):
251 Determine if this media type is eligible for processing
256 "unprocessed", "failed")
258 ###############################
259 # Command line interface things
260 ###############################
263 def generate_parser(cls
):
264 parser
= argparse
.ArgumentParser(
265 description
=cls
.description
,
271 metavar
=('max_width', 'max_height'),
277 metavar
=('max_width', 'max_height'),
282 choices
=['BICUBIC', 'BILINEAR', 'NEAREST', 'ANTIALIAS'])
287 help='level of compression used when resizing images')
292 def args_to_request(cls
, args
):
293 return request_from_args(
294 args
, ['size', 'thumb_size', 'filter', 'quality'])
296 def process(self
, size
=None, thumb_size
=None, quality
=None, filter=None):
298 self
.generate_medium_if_applicable(size
=size
, filter=filter,
300 self
.generate_thumb(size
=thumb_size
, filter=filter, quality
=quality
)
302 self
.extract_metadata()
303 self
.delete_queue_file()
306 class Resizer(CommonImageProcessor
):
308 Resizing process steps for processed media
311 description
= 'Resize image'
315 def media_is_eligible(cls
, entry
=None, state
=None):
317 Determine if this media type is eligible for processing
321 return state
in 'processed'
323 ###############################
324 # Command line interface things
325 ###############################
328 def generate_parser(cls
):
329 parser
= argparse
.ArgumentParser(
330 description
=cls
.description
,
336 metavar
=('max_width', 'max_height'),
341 choices
=['BICUBIC', 'BILINEAR', 'NEAREST', 'ANTIALIAS'])
346 help='level of compression used when resizing images')
350 choices
=['medium', 'thumb'])
355 def args_to_request(cls
, args
):
356 return request_from_args(
357 args
, ['size', 'file', 'quality', 'filter'])
359 def process(self
, file, size
=None, filter=None, quality
=None):
362 self
.generate_medium_if_applicable(size
=size
, filter=filter,
364 elif file == 'thumb':
365 self
.generate_thumb(size
=size
, filter=filter, quality
=quality
)
368 class ImageProcessingManager(ProcessingManager
):
370 super(self
.__class
__, self
).__init
__()
371 self
.add_processor(InitialProcessor
)
372 self
.add_processor(Resizer
)
375 if __name__
== '__main__':
379 pp
= pprint
.PrettyPrinter()
381 result
= extract_exif(sys
.argv
[1])
382 gps
= get_gps_data(result
)
383 clean
= clean_exif(result
)
384 useful
= get_useful(clean
)
386 print(pp
.pprint(clean
))