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
.db
.models
import MediaEntry
27 from mediagoblin
.processing
import (
28 BadMediaFail
, FilenameBuilder
,
29 MediaProcessor
, ProcessingManager
,
30 request_from_args
, get_orig_filename
,
31 store_public
, copy_original
)
32 from mediagoblin
.submit
.lib
import run_process_media
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
36 from mediagoblin
.tools
.translate
import lazy_pass_to_ugettext
as _
38 _log
= logging
.getLogger(__name__
)
41 'NEAREST': Image
.NEAREST
,
42 'BILINEAR': Image
.BILINEAR
,
43 'BICUBIC': Image
.BICUBIC
,
44 'ANTIALIAS': Image
.ANTIALIAS
}
46 MEDIA_TYPE
= 'mediagoblin.media_types.image'
49 def resize_image(entry
, resized
, keyname
, target_name
, new_size
,
52 Store a resized version of an image and return its pathname.
55 proc_state -- the processing state for the image to resize
56 resized -- an image from Image.open() of the original image being resized
57 keyname -- Under what key to save in the db.
58 target_name -- public file path for the new resized image
59 exif_tags -- EXIF data for the original image
60 workdir -- directory path for storing converted image files
61 new_size -- 2-tuple size for the resized image
63 config
= mgg
.global_config
['media_type:mediagoblin.media_types.image']
65 resized
= exif_fix_image_orientation(resized
, exif_tags
) # Fix orientation
67 filter_config
= config
['resize_filter']
69 resize_filter
= PIL_FILTERS
[filter_config
.upper()]
71 raise Exception('Filter "{0}" not found, choose one of {1}'.format(
72 unicode(filter_config
),
73 u
', '.join(PIL_FILTERS
.keys())))
75 resized
.thumbnail(new_size
, resize_filter
)
77 # Copy the new file to the conversion subdir, then remotely.
78 tmp_resized_filename
= os
.path
.join(workdir
, target_name
)
79 with
file(tmp_resized_filename
, 'w') as resized_file
:
80 resized
.save(resized_file
, quality
=config
['quality'])
81 store_public(entry
, keyname
, tmp_resized_filename
, target_name
)
84 def resize_tool(entry
,
85 force
, keyname
, target_name
,
86 conversions_subdir
, exif_tags
, new_size
=None):
87 # filename -- the filename of the original image being resized
88 filename
= target_name
90 # Use the default size if new_size was not given
92 max_width
= mgg
.global_config
['media:' + keyname
]['max_width']
93 max_height
= mgg
.global_config
['media:' + keyname
]['max_height']
94 new_size
= (max_width
, max_height
)
96 # If the size of the original file exceeds the specified size for the desized
97 # file, a target_name file is created and later associated with the media
99 # Also created if the file needs rotation, or if forced.
101 im
= Image
.open(filename
)
105 or im
.size
[0] > new_size
[0]\
106 or im
.size
[1] > new_size
[1]\
107 or exif_image_needs_rotation(exif_tags
):
109 entry
, im
, unicode(keyname
), target_name
,
111 exif_tags
, conversions_subdir
)
114 SUPPORTED_FILETYPES
= ['png', 'gif', 'jpg', 'jpeg', 'tiff']
117 def sniff_handler(media_file
, **kw
):
118 _log
.info('Sniffing {0}'.format(MEDIA_TYPE
))
119 if kw
.get('media') is not None: # That's a double negative!
120 name
, ext
= os
.path
.splitext(kw
['media'].filename
)
121 clean_ext
= ext
[1:].lower() # Strip the . from ext and make lowercase
123 if clean_ext
in SUPPORTED_FILETYPES
:
124 _log
.info('Found file extension in supported filetypes')
127 _log
.debug('Media present, extension not found in {0}'.format(
128 SUPPORTED_FILETYPES
))
130 _log
.warning('Need additional information (keyword argument \'media\')'
131 ' to be able to handle sniffing')
136 class ProcessImage(object):
137 """Code to process an image. Will be run by celery.
139 A Workbench() represents a local tempory dir. It is automatically
140 cleaned up when this function exits.
142 def __init__(self
, proc_state
=None):
144 self
.proc_state
= proc_state
145 self
.entry
= proc_state
.entry
146 self
.workbench
= proc_state
.workbench
148 # Conversions subdirectory to avoid collisions
149 self
.conversions_subdir
= os
.path
.join(
150 self
.workbench
.dir, 'convirsions')
152 self
.orig_filename
= proc_state
.get_orig_filename()
153 self
.name_builder
= FilenameBuilder(self
.orig_filename
)
156 self
.exif_tags
= extract_exif(self
.orig_filename
)
158 os
.mkdir(self
.conversions_subdir
)
160 def reprocess_action(self
, args
):
162 List the available actions for media in a given state
164 if args
[0].state
== 'processed':
165 print _('\n Available reprocessing actions for processed images:'
166 '\n \t --resize: thumb or medium'
168 '\n \t --size: max_width max_height (defaults to'
172 def _parser(self
, args
):
174 Parses the unknown args from the gmg parser
176 parser
= argparse
.ArgumentParser()
179 choices
=['thumb', 'medium'])
183 metavar
=('max_width', 'max_height'),
186 '--initial_processing',
189 return parser
.parse_args(args
[1])
191 def _check_eligible(self
, entry_args
, reprocess_args
):
193 Check to see if we can actually process the given media as requested
196 if entry_args
.state
== 'processed':
197 if reprocess_args
.initial_processing
:
198 raise Exception(_('You can not run --initial_processing on'
199 ' media that has already been processed.'))
201 if entry_args
.state
== 'failed':
202 if reprocess_args
.resize
:
203 raise Exception(_('You can not run --resize on media that has'
204 ' not been processed.'))
205 if reprocess_args
.size
:
206 _log
.warn('With --initial_processing, the --size flag will be'
209 if entry_args
.state
== 'processing':
210 raise Exception(_('We currently do not support reprocessing on'
211 ' media that is in the "processing" state.'))
213 def initial_processing(self
):
214 # Is there any GPS data
215 gps_data
= get_gps_data(self
.exif_tags
)
217 # Always create a small thumbnail
218 resize_tool(self
.proc_state
, True, 'thumb', self
.orig_filename
,
219 self
.name_builder
.fill('{basename}.thumbnail{ext}'),
220 self
.conversions_subdir
, self
.exif_tags
)
222 # Possibly create a medium
223 resize_tool(self
.proc_state
, False, 'medium', self
.orig_filename
,
224 self
.name_builder
.fill('{basename}.medium{ext}'),
225 self
.conversions_subdir
, self
.exif_tags
)
227 # Copy our queued local workbench to its final destination
228 self
.proc_state
.copy_original(self
.name_builder
.fill('{basename}{ext}'))
230 # Remove queued media file from storage and database
231 self
.proc_state
.delete_queue_file()
233 # Insert exif data into database
234 exif_all
= clean_exif(self
.exif_tags
)
237 self
.entry
.media_data_init(exif_all
=exif_all
)
240 for key
in list(gps_data
.keys()):
241 gps_data
['gps_' + key
] = gps_data
.pop(key
)
242 self
.entry
.media_data_init(**gps_data
)
244 def reprocess(self
, reprocess_info
):
246 This function actually does the reprocessing when called by
247 ProcessMedia in gmg/processing/task.py
251 # Did they specify a size? They must specify either both or none, so
252 # we only need to check if one is present
253 if reprocess_info
.get('max_width'):
254 max_width
= reprocess_info
['max_width']
255 max_height
= reprocess_info
['max_height']
257 new_size
= (max_width
, max_height
)
259 resize_tool(self
.proc_state
, False, reprocess_info
['resize'],
260 self
.name_builder
.fill('{basename}.medium{ext}'),
261 self
.conversions_subdir
, self
.exif_tags
, new_size
)
263 def media_reprocess(self
, args
):
265 This function handles the all of the reprocessing logic, before calling
266 gmg/submit/lib/run_process_media
268 reprocess_args
= self
._parser
(args
)
271 # Can we actually process the given media as requested?
272 self
._check
_eligible
(entry_args
, reprocess_args
)
274 # Do we want to re-try initial processing?
275 if reprocess_args
.initial_processing
:
276 for id in entry_args
.media_id
:
277 entry
= MediaEntry
.query
.filter_by(id=id).first()
278 run_process_media(entry
)
280 # Are we wanting to resize the thumbnail or medium?
281 elif reprocess_args
.resize
:
283 # reprocess all given media entries
284 for id in entry_args
.media_id
:
285 entry
= MediaEntry
.query
.filter_by(id=id).first()
287 # For now we can only reprocess with the original file
288 if not entry
.media_files
.get('original'):
289 raise Exception(_('The original file for this media entry'
292 reprocess_info
= self
._get
_reprocess
_info
(reprocess_args
)
293 run_process_media(entry
, reprocess_info
=reprocess_info
)
295 # If we are here, they forgot to tell us how to reprocess
297 _log
.warn('You must set either --resize or --initial_processing'
298 ' flag to reprocess an image.')
300 def _get_reprocess_info(self
, args
):
301 """ Returns a dict with the info needed for reprocessing"""
302 reprocess_info
= {'resize': args
.resize
}
305 reprocess_info
['max_width'] = args
.size
[0]
306 reprocess_info
['max_height'] = args
.size
[1]
308 return reprocess_info
311 class CommonImageProcessor(MediaProcessor
):
313 Provides a base for various media processing steps
315 # Common resizing step
316 def resize_step(self
):
320 def _add_width_height_args(cls
, parser
):
322 "--width", default
=None,
324 "Width of the resized image (if not using defaults)"))
326 "--height", default
=None,
328 "Height of the resized image (if not using defaults)"))
330 def common_setup(self
):
332 Set up the workbench directory and pull down the original file
334 ## @@: Should this be two functions?
335 # Conversions subdirectory to avoid collisions
336 self
.conversions_subdir
= os
.path
.join(
337 self
.workbench
.dir, 'convirsions')
338 os
.mkdir(self
.conversions_subdir
)
340 # Pull down and set up the original file
341 self
.orig_filename
= get_orig_filename(
342 self
.entry
, self
.workbench
)
343 self
.name_builder
= FilenameBuilder(self
.orig_filename
)
346 self
.exif_tags
= extract_exif(self
.orig_filename
)
349 def generate_medium_if_applicable(self
, size
=None):
350 resize_tool(self
.entry
, False, 'medium', self
.orig_filename
,
351 self
.name_builder
.fill('{basename}.medium{ext}'),
352 self
.conversions_subdir
, self
.exif_tags
)
354 def generate_thumb(self
, size
=None):
355 resize_tool(self
.entry
, True, 'thumb', self
.orig_filename
,
356 self
.name_builder
.fill('{basename}.thumbnail{ext}'),
357 self
.conversions_subdir
, self
.exif_tags
)
359 def copy_original(self
):
361 self
.entry
, self
.orig_filename
,
362 self
.name_builder
.fill('{basename}{ext}'))
364 def extract_metadata(self
):
365 # Is there any GPS data
366 gps_data
= get_gps_data(self
.exif_tags
)
368 # Insert exif data into database
369 exif_all
= clean_exif(self
.exif_tags
)
372 self
.entry
.media_data_init(exif_all
=exif_all
)
375 for key
in list(gps_data
.keys()):
376 gps_data
['gps_' + key
] = gps_data
.pop(key
)
377 self
.entry
.media_data_init(**gps_data
)
380 class InitialProcessor(CommonImageProcessor
):
382 Initial processing step for new images
385 description
= "Initial processing"
388 def media_is_eligible(cls
, entry
):
390 Determine if this media type is eligible for processing
392 return entry
.state
in (
393 "unprocessed", "failed")
395 ###############################
396 # Command line interface things
397 ###############################
400 def generate_parser(cls
):
401 parser
= argparse
.ArgumentParser(
402 description
=cls
.description
,
408 metavar
=('max_width', 'max_height'),
419 def args_to_request(cls
, args
):
420 return request_from_args(
421 args
, ['size', 'thumb_size'])
424 def process(self
, size
=None, thumb_size
=None):
426 self
.generate_medium_if_applicable(size
=size
)
427 self
.generate_thumb(size
=thumb_size
)
428 self
.extract_metadata()
431 class ImageProcessingManager(ProcessingManager
):
433 super(self
.__class
__, self
).__init
__()
434 self
.add_processor(InitialProcessor
)
437 if __name__
== '__main__':
441 pp
= pprint
.PrettyPrinter()
443 result
= extract_exif(sys
.argv
[1])
444 gps
= get_gps_data(result
)
445 clean
= clean_exif(result
)
446 useful
= get_useful(clean
)