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