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