forked from dmsza/json2kml
-
Notifications
You must be signed in to change notification settings - Fork 1
/
csv2kml.py
executable file
·87 lines (68 loc) · 1.96 KB
/
csv2kml.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
#!/usr/bin/env python3
"""
Extract Google Place IDs from Google Takeout
Usage: extract.py favorites.csv > out.kml
Author: Devin Bayer <[email protected]>
Repo: https://github.com/akvadrako/json2kml
License: GPL 3.0
"""
import sys, csv, re
from mako.template import Template
from dataclasses import dataclass
from urllib.request import urlopen
from os.path import expanduser
from json import loads
def log(code, *args):
sys.stderr.write('%8.8s | ' % code)
sys.stderr.write(' '.join(str(a) for a in args) + '\n')
@dataclass
class place:
name: str
note: str
url: str
comment: str
address = ''
lat = 0.0
long = 0.0
path = sys.argv[1]
places = []
apikey = open(expanduser('~/.private/google-api')).read().strip()
failed_fd = open('failed.csv', 'a')
reader = csv.reader(open(path), delimiter=',', quotechar='"')
for row in reader:
log('row', *row[:2])
if row == 'Title Note URL Comment'.split():
continue
p = place(*row)
p.lat = 0.0
p.long = 0.0
p.address = None
m = re.match(r'.*google.com/maps/place/.*/data=.*!1s(0x[0-9a-fx:]+)', p.url)
if not m:
log('nomatch', p.url)
csv.writer(failed_fd).writerow(row)
continue
ftid = m.group(1)
log('match', ftid)
resp = urlopen(f'https://maps.googleapis.com/maps/api/place/details/json?key={apikey}&ftid={ftid}')
data = loads(resp.read())
if data['status'] != 'OK':
log('error', data)
csv.writer(failed_fd).writerow(row + ['error: ' + data['status']])
continue
try:
r = data['result']
p.address = r['formatted_address']
p.lat = r['geometry']['location']['lat']
p.long = r['geometry']['location']['lng']
log('addr', p.address, p.lat, p.long)
except Exception as e:
log('error', e, data)
raise
places.append(p)
temp = Template(filename='template.kml.mako')
print(temp.render(
path=path,
places=places,
))
failed_fd.close()