.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
openstreetmap.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""OpenStreetMap (Map)
3
4"""
5
6import re
7from json import loads
8from urllib.parse import urlencode
9from functools import partial
10
11from flask_babel import gettext
12
13from searx.data import OSM_KEYS_TAGS, CURRENCIES
14from searx.utils import searx_useragent
15from searx.external_urls import get_external_url
16from searx.engines.wikidata import send_wikidata_query, sparql_string_escape, get_thumbnail
17
18# about
19about = {
20 "website": 'https://www.openstreetmap.org/',
21 "wikidata_id": 'Q936',
22 "official_api_documentation": 'http://wiki.openstreetmap.org/wiki/Nominatim',
23 "use_official_api": True,
24 "require_api_key": False,
25 "results": 'JSON',
26}
27
28# engine dependent config
29categories = ['map']
30paging = False
31language_support = True
32send_accept_language_header = True
33
34# search-url
35base_url = 'https://nominatim.openstreetmap.org/'
36search_string = 'search?{query}&polygon_geojson=1&format=jsonv2&addressdetails=1&extratags=1&dedupe=1'
37result_id_url = 'https://openstreetmap.org/{osm_type}/{osm_id}'
38result_lat_lon_url = 'https://www.openstreetmap.org/?mlat={lat}&mlon={lon}&zoom={zoom}&layers=M'
39
40route_url = 'https://graphhopper.com/maps/?point={}&point={}&locale=en-US&vehicle=car&weighting=fastest&turn_costs=true&use_miles=false&layer=Omniscale' # pylint: disable=line-too-long
41route_re = re.compile('(?:from )?(.+) to (.+)')
42
43wikidata_image_sparql = """
44select ?item ?itemLabel ?image ?sign ?symbol ?website ?wikipediaName
45where {
46 hint:Query hint:optimizer "None".
47 values ?item { %WIKIDATA_IDS% }
48 OPTIONAL { ?item wdt:P18|wdt:P8517|wdt:P4291|wdt:P5252|wdt:P3451|wdt:P4640|wdt:P5775|wdt:P2716|wdt:P1801|wdt:P4896 ?image }
49 OPTIONAL { ?item wdt:P1766|wdt:P8505|wdt:P8667 ?sign }
50 OPTIONAL { ?item wdt:P41|wdt:P94|wdt:P154|wdt:P158|wdt:P2910|wdt:P4004|wdt:P5962|wdt:P8972 ?symbol }
51 OPTIONAL { ?item wdt:P856 ?website }
52 SERVICE wikibase:label {
53 bd:serviceParam wikibase:language "%LANGUAGE%,en".
54 ?item rdfs:label ?itemLabel .
55 }
56 OPTIONAL {
57 ?wikipediaUrl schema:about ?item;
58 schema:isPartOf/wikibase:wikiGroup "wikipedia";
59 schema:name ?wikipediaName;
60 schema:inLanguage "%LANGUAGE%" .
61 }
62}
63ORDER by ?item
64"""
65
66
67# key value that are link: mapping functions
68# 'mapillary': P1947
69# but https://github.com/kartaview/openstreetcam.org/issues/60
70# but https://taginfo.openstreetmap.org/keys/kartaview ...
72 http = 'http://'
73 if value.startswith(http):
74 value = 'https://' + value[len(http) :]
75 return (value, value)
76
77
79 value = value.split(';')[0]
80 return (value, value)
81
82
84 value = value.split(':', 1)
85 return ('https://{0}.wikipedia.org/wiki/{1}'.format(*value), '{1} ({0})'.format(*value))
86
87
88def value_with_prefix(prefix, value):
89 return (prefix + value, value)
90
91
92VALUE_TO_LINK = {
93 'website': value_to_website_link,
94 'contact:website': value_to_website_link,
95 'email': partial(value_with_prefix, 'mailto:'),
96 'contact:email': partial(value_with_prefix, 'mailto:'),
97 'contact:phone': partial(value_with_prefix, 'tel:'),
98 'phone': partial(value_with_prefix, 'tel:'),
99 'fax': partial(value_with_prefix, 'fax:'),
100 'contact:fax': partial(value_with_prefix, 'fax:'),
101 'contact:mastodon': value_to_https_link,
102 'facebook': value_to_https_link,
103 'contact:facebook': value_to_https_link,
104 'contact:foursquare': value_to_https_link,
105 'contact:instagram': value_to_https_link,
106 'contact:linkedin': value_to_https_link,
107 'contact:pinterest': value_to_https_link,
108 'contact:telegram': value_to_https_link,
109 'contact:tripadvisor': value_to_https_link,
110 'contact:twitter': value_to_https_link,
111 'contact:yelp': value_to_https_link,
112 'contact:youtube': value_to_https_link,
113 'contact:webcam': value_to_website_link,
114 'wikipedia': value_wikipedia_link,
115 'wikidata': partial(value_with_prefix, 'https://wikidata.org/wiki/'),
116 'brand:wikidata': partial(value_with_prefix, 'https://wikidata.org/wiki/'),
117}
118KEY_ORDER = [
119 'cuisine',
120 'organic',
121 'delivery',
122 'delivery:covid19',
123 'opening_hours',
124 'opening_hours:covid19',
125 'fee',
126 'payment:*',
127 'currency:*',
128 'outdoor_seating',
129 'bench',
130 'wheelchair',
131 'level',
132 'building:levels',
133 'bin',
134 'public_transport',
135 'internet_access:ssid',
136]
137KEY_RANKS = {k: i for i, k in enumerate(KEY_ORDER)}
138
139
140def request(query, params):
141 """do search-request"""
142 params['url'] = base_url + search_string.format(query=urlencode({'q': query}))
143 params['route'] = route_re.match(query)
144 params['headers']['User-Agent'] = searx_useragent()
145 if 'Accept-Language' not in params['headers']:
146 params['headers']['Accept-Language'] = 'en'
147 return params
148
149
150def response(resp):
151 """get response from search-request"""
152 results = []
153 nominatim_json = loads(resp.text)
154 user_language = resp.search_params['language']
155
156 if resp.search_params['route']:
157 results.append(
158 {
159 'answer': gettext('Get directions'),
160 'url': route_url.format(*resp.search_params['route'].groups()),
161 }
162 )
163
164 # simplify the code below: make sure extratags is a dictionary
165 for result in nominatim_json:
166 if not isinstance(result.get('extratags'), dict):
167 result["extratags"] = {}
168
169 # fetch data from wikidata
170 fetch_wikidata(nominatim_json, user_language)
171
172 # create results
173 for result in nominatim_json:
174 title, address = get_title_address(result)
175
176 # ignore result without title
177 if not title:
178 continue
179
180 url, osm, geojson = get_url_osm_geojson(result)
181 img_src = get_thumbnail(get_img_src(result))
182 links, link_keys = get_links(result, user_language)
183 data = get_data(result, user_language, link_keys)
184
185 results.append(
186 {
187 'template': 'map.html',
188 'title': title,
189 'address': address,
190 'address_label': get_key_label('addr', user_language),
191 'url': url,
192 'osm': osm,
193 'geojson': geojson,
194 'img_src': img_src,
195 'links': links,
196 'data': data,
197 'type': get_tag_label(result.get('category'), result.get('type', ''), user_language),
198 'type_icon': result.get('icon'),
199 'content': '',
200 'longitude': result['lon'],
201 'latitude': result['lat'],
202 'boundingbox': result['boundingbox'],
203 }
204 )
205
206 return results
207
208
209def get_wikipedia_image(raw_value):
210 if not raw_value:
211 return None
212 return get_external_url('wikimedia_image', raw_value)
213
214
215def fetch_wikidata(nominatim_json, user_language):
216 """Update nominatim_json using the result of an unique to wikidata
217
218 For result in nominatim_json:
219 If result['extratags']['wikidata'] or r['extratags']['wikidata link']:
220 Set result['wikidata'] to { 'image': ..., 'image_sign':..., 'image_symbal':... }
221 Set result['extratags']['wikipedia'] if not defined
222 Set result['extratags']['contact:website'] if not defined
223 """
224 wikidata_ids = []
225 wd_to_results = {}
226 for result in nominatim_json:
227 extratags = result['extratags']
228 # ignore brand:wikidata
229 wd_id = extratags.get('wikidata', extratags.get('wikidata link'))
230 if wd_id and wd_id not in wikidata_ids:
231 wikidata_ids.append('wd:' + wd_id)
232 wd_to_results.setdefault(wd_id, []).append(result)
233
234 if wikidata_ids:
235 user_language = 'en' if user_language == 'all' else user_language.split('-')[0]
236 wikidata_ids_str = " ".join(wikidata_ids)
237 query = wikidata_image_sparql.replace('%WIKIDATA_IDS%', sparql_string_escape(wikidata_ids_str)).replace(
238 '%LANGUAGE%', sparql_string_escape(user_language)
239 )
240 wikidata_json = send_wikidata_query(query)
241 for wd_result in wikidata_json.get('results', {}).get('bindings', {}):
242 wd_id = wd_result['item']['value'].replace('http://www.wikidata.org/entity/', '')
243 for result in wd_to_results.get(wd_id, []):
244 result['wikidata'] = {
245 'itemLabel': wd_result['itemLabel']['value'],
246 'image': get_wikipedia_image(wd_result.get('image', {}).get('value')),
247 'image_sign': get_wikipedia_image(wd_result.get('sign', {}).get('value')),
248 'image_symbol': get_wikipedia_image(wd_result.get('symbol', {}).get('value')),
249 }
250 # overwrite wikipedia link
251 wikipedia_name = wd_result.get('wikipediaName', {}).get('value')
252 if wikipedia_name:
253 result['extratags']['wikipedia'] = user_language + ':' + wikipedia_name
254 # get website if not already defined
255 website = wd_result.get('website', {}).get('value')
256 if (
257 website
258 and not result['extratags'].get('contact:website')
259 and not result['extratags'].get('website')
260 ):
261 result['extratags']['contact:website'] = website
262
263
265 """Return title and address
266
267 title may be None
268 """
269 address_raw = result.get('address')
270 address_name = None
271 address = {}
272
273 # get name
274 if (
275 result['category'] == 'amenity'
276 or result['category'] == 'shop'
277 or result['category'] == 'tourism'
278 or result['category'] == 'leisure'
279 ):
280 if address_raw.get('address29'):
281 # https://github.com/osm-search/Nominatim/issues/1662
282 address_name = address_raw.get('address29')
283 else:
284 address_name = address_raw.get(result['category'])
285 elif result['type'] in address_raw:
286 address_name = address_raw.get(result['type'])
287
288 # add rest of adressdata, if something is already found
289 if address_name:
290 title = address_name
291 address.update(
292 {
293 'name': address_name,
294 'house_number': address_raw.get('house_number'),
295 'road': address_raw.get('road'),
296 'locality': address_raw.get(
297 'city', address_raw.get('town', address_raw.get('village')) # noqa
298 ), # noqa
299 'postcode': address_raw.get('postcode'),
300 'country': address_raw.get('country'),
301 'country_code': address_raw.get('country_code'),
302 }
303 )
304 else:
305 title = result.get('display_name')
306
307 return title, address
308
309
311 """Get url, osm and geojson"""
312 osm_type = result.get('osm_type', result.get('type'))
313 if 'osm_id' not in result:
314 # see https://github.com/osm-search/Nominatim/issues/1521
315 # query example: "EC1M 5RF London"
316 url = result_lat_lon_url.format(lat=result['lat'], lon=result['lon'], zoom=12)
317 osm = {}
318 else:
319 url = result_id_url.format(osm_type=osm_type, osm_id=result['osm_id'])
320 osm = {'type': osm_type, 'id': result['osm_id']}
321
322 geojson = result.get('geojson')
323 # if no geojson is found and osm_type is a node, add geojson Point
324 if not geojson and osm_type == 'node':
325 geojson = {'type': 'Point', 'coordinates': [result['lon'], result['lat']]}
326
327 return url, osm, geojson
328
329
330def get_img_src(result):
331 """Get image URL from either wikidata or r['extratags']"""
332 # wikidata
333 img_src = None
334 if 'wikidata' in result:
335 img_src = result['wikidata']['image']
336 if not img_src:
337 img_src = result['wikidata']['image_symbol']
338 if not img_src:
339 img_src = result['wikidata']['image_sign']
340
341 # img_src
342 extratags = result['extratags']
343 if not img_src and extratags.get('image'):
344 img_src = extratags['image']
345 del extratags['image']
346 if not img_src and extratags.get('wikimedia_commons'):
347 img_src = get_external_url('wikimedia_image', extratags['wikimedia_commons'])
348 del extratags['wikimedia_commons']
349
350 return img_src
351
352
353def get_links(result, user_language):
354 """Return links from result['extratags']"""
355 links = []
356 link_keys = set()
357 extratags = result['extratags']
358 if not extratags:
359 # minor optimization : no need to check VALUE_TO_LINK if extratags is empty
360 return links, link_keys
361 for k, mapping_function in VALUE_TO_LINK.items():
362 raw_value = extratags.get(k)
363 if not raw_value:
364 continue
365 url, url_label = mapping_function(raw_value)
366 if url.startswith('https://wikidata.org'):
367 url_label = result.get('wikidata', {}).get('itemLabel') or url_label
368 links.append(
369 {
370 'label': get_key_label(k, user_language),
371 'url': url,
372 'url_label': url_label,
373 }
374 )
375 link_keys.add(k)
376 return links, link_keys
377
378
379def get_data(result, user_language, ignore_keys):
380 """Return key, value of result['extratags']
381
382 Must be call after get_links
383
384 Note: the values are not translated
385 """
386 data = []
387 for k, v in result['extratags'].items():
388 if k in ignore_keys:
389 continue
390 if get_key_rank(k) is None:
391 continue
392 k_label = get_key_label(k, user_language)
393 if k_label:
394 data.append(
395 {
396 'label': k_label,
397 'key': k,
398 'value': v,
399 }
400 )
401 data.sort(key=lambda entry: (get_key_rank(entry['key']), entry['label']))
402 return data
403
404
406 """Get OSM key rank
407
408 The rank defines in which order the key are displayed in the HTML result
409 """
410 key_rank = KEY_RANKS.get(k)
411 if key_rank is None:
412 # "payment:*" in KEY_ORDER matches "payment:cash", "payment:debit card", etc...
413 key_rank = KEY_RANKS.get(k.split(':')[0] + ':*')
414 return key_rank
415
416
417def get_label(labels, lang):
418 """Get label from labels in OSM_KEYS_TAGS
419
420 in OSM_KEYS_TAGS, labels have key == '*'
421 """
422 tag_label = labels.get(lang.lower())
423 if tag_label is None:
424 # example: if 'zh-hk' is not found, check 'zh'
425 tag_label = labels.get(lang.split('-')[0])
426 if tag_label is None and lang != 'en':
427 # example: if 'zh' is not found, check 'en'
428 tag_label = labels.get('en')
429 if tag_label is None and len(labels.values()) > 0:
430 # example: if still not found, use the first entry
431 tag_label = labels.values()[0]
432 return tag_label
433
434
435def get_tag_label(tag_category, tag_name, lang):
436 """Get tag label from OSM_KEYS_TAGS"""
437 tag_name = '' if tag_name is None else tag_name
438 tag_labels = OSM_KEYS_TAGS['tags'].get(tag_category, {}).get(tag_name, {})
439 return get_label(tag_labels, lang)
440
441
442def get_key_label(key_name, lang):
443 """Get key label from OSM_KEYS_TAGS"""
444 if key_name.startswith('currency:'):
445 # currency:EUR --> get the name from the CURRENCIES variable
446 # see https://wiki.openstreetmap.org/wiki/Key%3Acurrency
447 # and for example https://taginfo.openstreetmap.org/keys/currency:EUR#values
448 # but there is also currency=EUR (currently not handled)
449 # https://taginfo.openstreetmap.org/keys/currency#values
450 currency = key_name.split(':')
451 if len(currency) > 1:
452 o = CURRENCIES['iso4217'].get(currency[1])
453 if o:
454 return get_label(o, lang).lower()
455 return currency[1]
456
457 labels = OSM_KEYS_TAGS['keys']
458 for k in key_name.split(':') + ['*']:
459 labels = labels.get(k)
460 if labels is None:
461 return None
462 return get_label(labels, lang)
value_with_prefix(prefix, value)
get_data(result, user_language, ignore_keys)
get_links(result, user_language)
get_tag_label(tag_category, tag_name, lang)
fetch_wikidata(nominatim_json, user_language)