99be848f521074be3f31e657016f8122da24895e
[mediagoblin.git] / mediagoblin / media_types / image / processing.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
3 #
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.
8 #
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.
13 #
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/>.
16
17 import Image
18 import os
19 import logging
20
21 from mediagoblin import mg_globals as mgg
22 from mediagoblin.decorators import get_workbench
23 from mediagoblin.processing import BadMediaFail, \
24 create_pub_filepath, FilenameBuilder
25 from mediagoblin.tools.exif import exif_fix_image_orientation, \
26 extract_exif, clean_exif, get_gps_data, get_useful, \
27 exif_image_needs_rotation
28
29 _log = logging.getLogger(__name__)
30
31 PIL_FILTERS = {
32 'NEAREST': Image.NEAREST,
33 'BILINEAR': Image.BILINEAR,
34 'BICUBIC': Image.BICUBIC,
35 'ANTIALIAS': Image.ANTIALIAS}
36
37
38 def resize_image(entry, filename, new_path, exif_tags, workdir, new_size,
39 size_limits=(0, 0)):
40 """
41 Store a resized version of an image and return its pathname.
42
43 Arguments:
44 entry -- the entry for the image to resize
45 filename -- the filename of the original image being resized
46 new_path -- public file path for the new resized image
47 exif_tags -- EXIF data for the original image
48 workdir -- directory path for storing converted image files
49 new_size -- 2-tuple size for the resized image
50 """
51 try:
52 resized = Image.open(filename)
53 except IOError:
54 raise BadMediaFail()
55 resized = exif_fix_image_orientation(resized, exif_tags) # Fix orientation
56
57 filter_config = \
58 mgg.global_config['media_type:mediagoblin.media_types.image']\
59 ['resize_filter']
60
61 try:
62 resize_filter = PIL_FILTERS[filter_config.upper()]
63 except KeyError:
64 raise Exception('Filter "{0}" not found, choose one of {1}'.format(
65 unicode(filter_config),
66 u', '.join(PIL_FILTERS.keys())))
67
68 resized.thumbnail(new_size, resize_filter)
69
70 # Copy the new file to the conversion subdir, then remotely.
71 tmp_resized_filename = os.path.join(workdir, new_path[-1])
72 with file(tmp_resized_filename, 'w') as resized_file:
73 resized.save(resized_file)
74 mgg.public_store.copy_local_to_storage(tmp_resized_filename, new_path)
75
76
77 SUPPORTED_FILETYPES = ['png', 'gif', 'jpg', 'jpeg']
78
79
80 def sniff_handler(media_file, **kw):
81 if kw.get('media') is not None: # That's a double negative!
82 name, ext = os.path.splitext(kw['media'].filename)
83 clean_ext = ext[1:].lower() # Strip the . from ext and make lowercase
84
85 if clean_ext in SUPPORTED_FILETYPES:
86 _log.info('Found file extension in supported filetypes')
87 return True
88 else:
89 _log.debug('Media present, extension not found in {0}'.format(
90 SUPPORTED_FILETYPES))
91 else:
92 _log.warning('Need additional information (keyword argument \'media\')'
93 ' to be able to handle sniffing')
94
95 return False
96
97
98 @get_workbench
99 def process_image(entry, workbench=None):
100 """Code to process an image. Will be run by celery.
101
102 A Workbench() represents a local tempory dir. It is automatically
103 cleaned up when this function exits.
104 """
105 # Conversions subdirectory to avoid collisions
106 conversions_subdir = os.path.join(
107 workbench.dir, 'conversions')
108 os.mkdir(conversions_subdir)
109 queued_filepath = entry.queued_media_file
110 queued_filename = workbench.localized_file(
111 mgg.queue_store, queued_filepath,
112 'source')
113 name_builder = FilenameBuilder(queued_filename)
114
115 # EXIF extraction
116 exif_tags = extract_exif(queued_filename)
117 gps_data = get_gps_data(exif_tags)
118
119 # Always create a small thumbnail
120 thumb_filepath = create_pub_filepath(
121 entry, name_builder.fill('{basename}.thumbnail{ext}'))
122 resize_image(entry, queued_filename, thumb_filepath,
123 exif_tags, conversions_subdir,
124 (mgg.global_config['media:thumb']['max_width'],
125 mgg.global_config['media:thumb']['max_height']))
126
127 # If the size of the original file exceeds the specified size of a `medium`
128 # file, a `.medium.jpg` files is created and later associated with the media
129 # entry.
130 medium = Image.open(queued_filename)
131 if medium.size[0] > mgg.global_config['media:medium']['max_width'] \
132 or medium.size[1] > mgg.global_config['media:medium']['max_height'] \
133 or exif_image_needs_rotation(exif_tags):
134 medium_filepath = create_pub_filepath(
135 entry, name_builder.fill('{basename}.medium{ext}'))
136 resize_image(
137 entry, queued_filename, medium_filepath,
138 exif_tags, conversions_subdir,
139 (mgg.global_config['media:medium']['max_width'],
140 mgg.global_config['media:medium']['max_height']))
141 else:
142 medium_filepath = None
143
144 # Copy our queued local workbench to its final destination
145 original_filepath = create_pub_filepath(
146 entry, name_builder.fill('{basename}{ext}'))
147 mgg.public_store.copy_local_to_storage(queued_filename, original_filepath)
148
149 # Remove queued media file from storage and database
150 mgg.queue_store.delete_file(queued_filepath)
151 entry.queued_media_file = []
152
153 # Insert media file information into database
154 media_files_dict = entry.setdefault('media_files', {})
155 media_files_dict[u'thumb'] = thumb_filepath
156 media_files_dict[u'original'] = original_filepath
157 if medium_filepath:
158 media_files_dict[u'medium'] = medium_filepath
159
160 # Insert exif data into database
161 exif_all = clean_exif(exif_tags)
162
163 if len(exif_all):
164 entry.media_data_init(exif_all=exif_all)
165
166 if len(gps_data):
167 for key in list(gps_data.keys()):
168 gps_data['gps_' + key] = gps_data.pop(key)
169 entry.media_data_init(**gps_data)
170
171
172 if __name__ == '__main__':
173 import sys
174 import pprint
175
176 pp = pprint.PrettyPrinter()
177
178 result = extract_exif(sys.argv[1])
179 gps = get_gps_data(result)
180 clean = clean_exif(result)
181 useful = get_useful(clean)
182
183 print pp.pprint(
184 clean)