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