20227aa854d58ab886c961342d558a2764058f79
[mediagoblin.git] / mediagoblin / tools / exif.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 EXIF import process_file, Ratio
19 except ImportError:
20 from mediagoblin.tools.extlib.EXIF import process_file, Ratio
21
22 from mediagoblin.processing import BadMediaFail
23 from mediagoblin.tools.translate import pass_to_ugettext as _
24
25 # A list of tags that should be stored for faster access
26 USEFUL_TAGS = [
27 'Image Make',
28 'Image Model',
29 'EXIF FNumber',
30 'EXIF Flash',
31 'EXIF FocalLength',
32 'EXIF ExposureTime',
33 'EXIF ApertureValue',
34 'EXIF ExposureMode',
35 'EXIF ISOSpeedRatings',
36 'EXIF UserComment',
37 ]
38
39
40 def exif_image_needs_rotation(exif_tags):
41 """
42 Returns True if EXIF orientation requires rotation
43 """
44 return 'Image Orientation' in exif_tags \
45 and exif_tags['Image Orientation'].values[0] != 1
46
47
48 def exif_fix_image_orientation(im, exif_tags):
49 """
50 Translate any EXIF orientation to raw orientation
51
52 Cons:
53 - REDUCES IMAGE QUALITY by recompressing it
54
55 Pros:
56 - Prevents neck pain
57 """
58 # Rotate image
59 if 'Image Orientation' in exif_tags:
60 rotation_map = {
61 3: 180,
62 6: 270,
63 8: 90}
64 orientation = exif_tags['Image Orientation'].values[0]
65 if orientation in rotation_map:
66 im = im.rotate(
67 rotation_map[orientation])
68
69 return im
70
71
72 def extract_exif(filename):
73 """
74 Returns EXIF tags found in file at ``filename``
75 """
76 try:
77 with file(filename) as image:
78 return process_file(image, details=False)
79 except IOError:
80 raise BadMediaFail(_('Could not read the image file.'))
81
82
83 def clean_exif(exif):
84 '''
85 Clean the result from anything the database cannot handle
86 '''
87 # Discard any JPEG thumbnail, for database compatibility
88 # and that I cannot see a case when we would use it.
89 # It takes up some space too.
90 disabled_tags = [
91 'Thumbnail JPEGInterchangeFormatLength',
92 'JPEGThumbnail',
93 'Thumbnail JPEGInterchangeFormat']
94
95 return dict((key, _ifd_tag_to_dict(value)) for (key, value)
96 in exif.iteritems() if key not in disabled_tags)
97
98
99 def _ifd_tag_to_dict(tag):
100 '''
101 Takes an IFD tag object from the EXIF library and converts it to a dict
102 that can be stored as JSON in the database.
103 '''
104 data = {
105 'printable': tag.printable,
106 'tag': tag.tag,
107 'field_type': tag.field_type,
108 'field_offset': tag.field_offset,
109 'field_length': tag.field_length,
110 'values': None}
111
112 if isinstance(tag.printable, str):
113 # Force it to be decoded as UTF-8 so that it'll fit into the DB
114 data['printable'] = tag.printable.decode('utf8', 'replace')
115
116 if type(tag.values) == list:
117 data['values'] = [_ratio_to_list(val) if isinstance(val, Ratio) else val
118 for val in tag.values]
119 else:
120 if isinstance(tag.values, str):
121 # Force UTF-8, so that it fits into the DB
122 data['values'] = tag.values.decode('utf8', 'replace')
123 else:
124 data['values'] = tag.values
125
126 return data
127
128
129 def _ratio_to_list(ratio):
130 return [ratio.num, ratio.den]
131
132
133 def get_useful(tags):
134 useful = {}
135 for key, tag in tags.items():
136 if key in USEFUL_TAGS:
137 useful[key] = tag
138
139 return useful
140
141
142 def get_gps_data(tags):
143 """
144 Processes EXIF data returned by EXIF.py
145 """
146 gps_data = {}
147
148 if not 'Image GPSInfo' in tags:
149 return gps_data
150
151 try:
152 dms_data = {
153 'latitude': tags['GPS GPSLatitude'],
154 'longitude': tags['GPS GPSLongitude']}
155
156 for key, dat in dms_data.iteritems():
157 gps_data[key] = (
158 lambda v:
159 float(v[0].num) / float(v[0].den) \
160 + (float(v[1].num) / float(v[1].den) / 60) \
161 + (float(v[2].num) / float(v[2].den) / (60 * 60))
162 )(dat.values)
163
164 if tags['GPS GPSLatitudeRef'].values == 'S':
165 gps_data['latitude'] /= -1
166
167 if tags['GPS GPSLongitudeRef'].values == 'W':
168 gps_data['longitude'] /= -1
169
170 except KeyError:
171 pass
172
173 try:
174 gps_data['direction'] = (
175 lambda d:
176 float(d.num) / float(d.den)
177 )(tags['GPS GPSImgDirection'].values[0])
178 except KeyError:
179 pass
180
181 try:
182 gps_data['altitude'] = (
183 lambda a:
184 float(a.num) / float(a.den)
185 )(tags['GPS GPSAltitude'].values[0])
186 except KeyError:
187 pass
188
189 return gps_data