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