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