-
Notifications
You must be signed in to change notification settings - Fork 0
/
exif-google-gps.py
287 lines (228 loc) · 8.47 KB
/
exif-google-gps.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#!/usr/bin/env python
import argparse
import json
import logging
import os.path
import pickle
import sys
import time
from datetime import (
datetime,
timedelta
)
from fractions import Fraction
import piexif
LOG_FMT = '[%(levelname)s] %(message)s'
class JpegFile():
def __init__(self, path, logger=None):
self.path = path
self._ts = None
self._exif = None
@property
def timestamp(self):
if self._ts is None:
self._ts = self._get_timestmap()
return self._ts
@property
def exif(self):
if self._exif is None:
self._exif = piexif.load(self.path)
return self._exif
@property
def has_geo(self):
try:
return (
piexif.GPSIFD.GPSLatitude in self.exif['GPS'] or
piexif.GPSIFD.GPSLongitude in self.exif['GPS'])
except KeyError:
return False
def write_lat_lng(self, lat, lng):
# Some code copied from:
# https://gist.github.com/c060604/8a51f8999be12fc2be498e9ca56adc72
def to_deg(value, loc):
"""convert decimal coordinates into degrees, munutes and seconds tuple
Keyword arguments: value is float gps-value, loc is direction list["S", "N"] or ["W", "E"]
return: tuple like (25, 13, 48.343 ,'N')
"""
if value < 0:
loc_value = loc[0]
elif value > 0:
loc_value = loc[1]
else:
loc_value = ""
abs_value = abs(value)
deg = int(abs_value)
t1 = (abs_value - deg) * 60
min = int(t1)
sec = round((t1 - min) * 60, 5)
return (deg, min, sec, loc_value)
def change_to_rational(number):
"""convert a number to rational
Keyword arguments: number
return: tuple like (1, 2), (numerator, denominator)
"""
f = Fraction(str(number))
return (f.numerator, f.denominator)
lat_deg = to_deg(lat, ["S", "N"])
lng_deg = to_deg(lng, ["W", "E"])
exiv_lat = (
change_to_rational(lat_deg[0]),
change_to_rational(lat_deg[1]),
change_to_rational(lat_deg[2]))
exiv_lng = (
change_to_rational(lng_deg[0]),
change_to_rational(lng_deg[1]),
change_to_rational(lng_deg[2]))
self.exif['GPS'] = {
piexif.GPSIFD.GPSVersionID: (2, 0, 0, 0),
# piexif.GPSIFD.GPSAltitudeRef: 1,
# piexif.GPSIFD.GPSAltitude: change_to_rational(round(altitude)),
piexif.GPSIFD.GPSLatitudeRef: lat_deg[3],
piexif.GPSIFD.GPSLatitude: exiv_lat,
piexif.GPSIFD.GPSLongitudeRef: lng_deg[3],
piexif.GPSIFD.GPSLongitude: exiv_lng,
}
piexif.insert(piexif.dump(self.exif), self.path)
def _get_timestmap(self):
# Code ripped from ocdutils: http://github.com/ldotlopez/ocdutils
t = {
'original': (piexif.ExifIFD.DateTimeOriginal,
piexif.ExifIFD.OffsetTimeOriginal),
'digitized': (piexif.ExifIFD.DateTimeDigitized,
piexif.ExifIFD.OffsetTimeDigitized),
}
for (key, (dt_tag, offset_tag)) in t.items():
try:
dt = self.exif['Exif'][dt_tag].decode('ascii')
except KeyError:
t[key] = None
continue
delta = timedelta()
if dt.find(' 24:') > 0:
dt = dt.replace(' 24:', ' 00:')
delta = datetime.timedelta(days=1)
dt = datetime.strptime(dt, '%Y:%m:%d %H:%M:%S')
dt = dt + delta
t[key] = dt
if not any(t.values()):
msg = "exif tags not found"
raise ValueError(msg)
if all(t.values()) and t['original'] != t['digitized']:
msg = "original:{original} != digitized:{digitized}"
msg = msg.format(original=t['original'], digitized=t['digitized'])
raise ValueError(msg)
dt = t['digitized'] or t['original']
return int(time.mktime(dt.timetuple()))
def __unicode__(self):
return self.path
def __repr__(self):
return str.__repr__(self.path)
class GeoData():
def __init__(self, locations_json=None):
name, _ = os.path.splitext(locations_json)
dump_file = name + '.bin'
try:
with open(dump_file, 'rb') as fh:
self._d = pickle.load(fh)
except IOError:
self._d = set()
with open(locations_json, 'r', encoding='utf-8') as fh:
for location in json.load(fh)['locations']:
self.save(location)
with open(dump_file, 'wb+') as fh:
fh.write(self.dump())
def save(self, location):
self._d.add(
(int(location['timestampMs']) / 1000,
location['latitudeE7'] / 10000000,
location['longitudeE7'] / 10000000)
)
def search(self, ts, max_delta):
def check_bounds(ts_):
return True
if len(self._d) < 2:
raise ValueError('No data available')
for idx in range(0, len(self._d) - 1):
delta_prev = self._d[idx][0] - ts
delta_post = self._d[idx+1][0] - ts
if not (delta_prev <= 0 and delta_post >= 0):
continue
if delta_prev > max_delta and delta_post > max_delta:
raise ValueError('Max delta')
if abs(delta_prev) < abs(delta_post):
return self._d[idx][1], self._d[idx][2]
else:
return self._d[idx+1][1], self._d[idx+1][2]
raise ValueError(ts)
def compile(self):
if not isinstance(self._d, list):
self._d = sorted(self._d)
def dump(self):
self.compile()
return pickle.dumps(self._d)
def main():
parser = argparse.ArgumentParser(
description=("Write GPS EXIF tags using data from Google location "
"history.\n"
"\n"
"It's recommended to use the '-n' option before real "
"usage in order to check results.\n"
"\n"
"If the output shows approximate locations but not the "
"apropiates (ie. it shows places where you have been "
"before or after the picture was taken) try the "
"--offset option"))
parser.add_argument(
'-g', '--geo',
required=True,
help=("Google location history file. "
"Download from: https://takeout.google.com/"))
parser.add_argument(
'-o', '--offset',
help="Time offset in seconds",
default='0')
parser.add_argument(
'--max-delta',
default=60*15, # 15 minutes
help=("Max desviation between JPG exif datetime and data from "
"location history file"))
parser.add_argument(
'-n', '--dry_run',
action='store_true',
help="Don't write GPS data, just print what would be done")
parser.add_argument(
'-v', '--verbose',
action='store_true',
help="Enable debug messages")
parser.add_argument(
'files',
nargs='+',
help="JPGs to process")
args = parser.parse_args(sys.argv[1:])
args.offset = int(args.offset)
if args.verbose:
logging.basicConfig(format=LOG_FMT, level=logging.DEBUG)
else:
logging.basicConfig(format=LOG_FMT, level=logging.WARNING)
geo = GeoData(args.geo)
for jpg in args.files:
jpg = JpegFile(jpg)
lat, lng = geo.search(jpg.timestamp + args.offset,
max_delta=args.max_delta)
if args.dry_run or args.verbose:
msg = ('[{f}] {dt} ({lat}, {lng}) '
'https://www.google.com/maps?z=14&q=loc:{lat},{lng}')
msg = msg.format(
dt=datetime.strftime(
datetime.fromtimestamp(jpg.timestamp + args.offset), '%c'),
f=jpg, ts=jpg.timestamp, lat=lat, lng=lng)
logging.info(msg)
if not args.dry_run:
if jpg.has_geo:
msg = "skipping: '{jpg}' already has GPS data. try --force"
msg = msg.format(jpg=str(jpg))
logging.info(msg)
continue
jpg.write_lat_lng(lat, lng)
if __name__ == '__main__':
main()