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