-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvcf2gpx.py
More file actions
190 lines (179 loc) · 7.65 KB
/
Copy pathvcf2gpx.py
File metadata and controls
190 lines (179 loc) · 7.65 KB
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
import vobject
import requests
import time
import sys
import re
import datetime
import colorama
from colorama import Fore, Style
colorama.init(autoreset=True)
def clean_address_part(part):
if not part:
return ''
part = part.replace('\\n', ', ').replace('^n', ', ')
return part.strip()
def parse_geo(geo_value):
geo_value = geo_value.strip()
if geo_value.lower().startswith('geo:'):
geo_value = geo_value[4:]
geo_value = geo_value.replace('\\,', ',').replace(';', ',').replace(' ', '')
m = re.match(r'^(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)$', geo_value)
if m:
return float(m.group(1)), float(m.group(2))
return None, None
def extract_geo_from_vcard(v):
for prop in v.getChildren():
if prop.name.upper() == 'GEO':
return parse_geo(prop.value)
if 'geo' in v.contents:
geo_val = v.contents['geo'][0].value
return parse_geo(geo_val)
if 'GEO' in v.contents:
geo_val = v.contents['GEO'][0].value
return parse_geo(geo_val)
return None, None
def geocode_mapbox(address, api_key, debug=False):
if not api_key:
return None, None
url = f'https://api.mapbox.com/geocoding/v5/mapbox.places/{requests.utils.quote(address)}.json'
params = {
'access_token': api_key,
'limit': 1,
'language': 'en',
'types': 'address'
}
if debug:
req = requests.Request('GET', url, params=params).prepare()
print(f"DEBUG: Mapbox URL: {req.url}" + Style.RESET_ALL)
r = requests.get(url, params=params)
data = r.json()
if r.ok and data.get('features'):
feature = data['features'][0]
lon, lat = feature['center']
return lat, lon
else:
if debug:
print(f"DEBUG: Address not found by Mapbox: {address}" + Style.RESET_ALL)
if 'message' in data:
print(f"DEBUG: Mapbox message: {data['message']}" + Style.RESET_ALL)
return None, None
def geocode_nominatim(address, debug=False):
url = "https://nominatim.openstreetmap.org/search"
params = {
"q": address,
"format": "json",
"limit": 1,
"addressdetails": 0,
}
headers = {
"User-Agent": "vcf2gpx/1.0"
}
if debug:
req = requests.Request('GET', url, params=params, headers=headers).prepare()
print(f"DEBUG: Nominatim URL: {req.url}" + Style.RESET_ALL)
r = requests.get(url, params=params, headers=headers)
if r.ok:
results = r.json()
if results:
lat = float(results[0]["lat"])
lon = float(results[0]["lon"])
return lat, lon
return None, None
def vcf2gpx(vcf_path, gpx_path, api_key, debug=False):
count_geo = 0
count_mapbox = 0
count_nominatim = 0
count_notfound = 0
count_noprecise = 0
total_geocoded = 0
with open(vcf_path, 'r', encoding='utf-8') as f:
vcards = vobject.readComponents(f)
points = []
for v in vcards:
name = v.fn.value if hasattr(v, 'fn') else "No name"
lat, lon = extract_geo_from_vcard(v)
if lat is not None and lon is not None:
print(Fore.GREEN + f"Geocoded (GEO): {name} -> {lat}, {lon}" + Style.RESET_ALL)
count_geo += 1
total_geocoded += 1
elif not hasattr(v, 'adr') or not v.adr or not getattr(v.adr, 'value', None):
print(Fore.RED + f"Address not specified in source file: {name}" + Style.RESET_ALL, file=sys.stderr)
count_noprecise += 1
continue
else:
adr = v.adr.value
if hasattr(adr, 'label') and adr.label:
address = clean_address_part(adr.label)
else:
parts = [
clean_address_part(adr.street),
clean_address_part(adr.code),
clean_address_part(adr.city),
clean_address_part(adr.region),
clean_address_part(adr.country)
]
address = ', '.join([p for p in parts if p])
if not address or len(address.split(',')) < 2:
if debug:
print(f"DEBUG: Address too incomplete, ignored: {address}" + Style.RESET_ALL)
print(Fore.RED + f"Not found: {name} ({address})" + Style.RESET_ALL, file=sys.stderr)
count_notfound += 1
continue
lat, lon = None, None
if api_key:
lat, lon = geocode_mapbox(address, api_key, debug=debug)
if lat and lon:
print(Fore.GREEN + f"Geocoded (Mapbox): {name} -> {lat}, {lon}" + Style.RESET_ALL)
count_mapbox += 1
total_geocoded += 1
else:
lat, lon = geocode_nominatim(address, debug=debug)
if lat and lon:
print(Fore.GREEN + f"Geocoded (Nominatim): {name} -> {lat}, {lon}" + Style.RESET_ALL)
count_nominatim += 1
total_geocoded += 1
else:
print(Fore.RED + f"Not found: {name} ({address})" + Style.RESET_ALL, file=sys.stderr)
count_notfound += 1
else:
lat, lon = geocode_nominatim(address, debug=debug)
if lat and lon:
print(Fore.GREEN + f"Geocoded (Nominatim): {name} -> {lat}, {lon}" + Style.RESET_ALL)
count_nominatim += 1
total_geocoded += 1
else:
print(Fore.RED + f"Not found: {name} ({address})" + Style.RESET_ALL, file=sys.stderr)
count_notfound += 1
time.sleep(0.2)
if lat is not None and lon is not None:
points.append((name, lat, lon))
# Add the metadata block with description in English
geocoding_date = datetime.datetime.now().strftime('%A, %d %B %Y')
with open(gpx_path, 'w', encoding='utf-8') as gpx:
gpx.write('<?xml version="1.0" encoding="UTF-8"?>\n')
gpx.write('<gpx version="1.1" creator="VCF to GPX">\n')
gpx.write(' <metadata>\n')
gpx.write(' <name>Geocoded contacts</name>\n')
gpx.write(f' <desc>Waypoints geocoded from exported addresses on {geocoding_date}, by VCF to GPX script.</desc>\n')
gpx.write(' </metadata>\n')
for name, lat, lon in points:
safe_name = name.replace('&', '_').replace('<', '_').replace('>', '_').replace('"', '_')
gpx.write(f' <wpt lat="{lat}" lon="{lon}"><name>{safe_name}</name></wpt>\n')
gpx.write('</gpx>\n')
print()
print(Fore.GREEN + f"{total_geocoded} addresses geocoded (including {count_mapbox} with Mapbox, {count_nominatim} with Nominatim, and {count_geo} with coordinates included in vCard)." + Style.RESET_ALL)
print(Fore.RED + f"{count_notfound} addresses not found." + Style.RESET_ALL)
print(Fore.RED + f"{count_noprecise} addresses not specified in source file." + Style.RESET_ALL)
if __name__ == "__main__":
debug = False
args = sys.argv[1:]
if '--debug' in args:
debug = True
args.remove('--debug')
if len(args) == 2:
vcf2gpx(args[0], args[1], None, debug=debug)
elif len(args) == 3:
vcf2gpx(args[0], args[1], args[2], debug=debug)
else:
print("Usage: python3 vcf2gpx.py file.vcf file.gpx [YOUR_MAPBOX_TOKEN] [--debug]")
sys.exit(1)