.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
searx.engines.openstreetmap Namespace Reference

Functions

 value_to_https_link (value)
 
 value_to_website_link (value)
 
 value_wikipedia_link (value)
 
 value_with_prefix (prefix, value)
 
 request (query, params)
 
 response (resp)
 
 get_wikipedia_image (raw_value)
 
 fetch_wikidata (nominatim_json, user_language)
 
 get_title_address (result)
 
 get_url_osm_geojson (result)
 
 get_img_src (result)
 
 get_links (result, user_language)
 
 get_data (result, user_language, ignore_keys)
 
 get_key_rank (k)
 
 get_label (labels, lang)
 
 get_tag_label (tag_category, tag_name, lang)
 
 get_key_label (key_name, lang)
 

Variables

dict about
 
list categories = ['map']
 
bool paging = False
 
bool language_support = True
 
bool send_accept_language_header = True
 
str base_url = 'https://nominatim.openstreetmap.org/'
 
str search_string = 'search?{query}&polygon_geojson=1&format=jsonv2&addressdetails=1&extratags=1&dedupe=1'
 
str result_id_url = 'https://openstreetmap.org/{osm_type}/{osm_id}'
 
str result_lat_lon_url = 'https://www.openstreetmap.org/?mlat={lat}&mlon={lon}&zoom={zoom}&layers=M'
 
str route_url = 'https://graphhopper.com/maps/?point={}&point={}&locale=en-US&vehicle=car&weighting=fastest&turn_costs=true&use_miles=false&layer=Omniscale'
 
 route_re = re.compile('(?:from )?(.+) to (.+)')
 
str wikidata_image_sparql
 
dict VALUE_TO_LINK
 
list KEY_ORDER
 
dict KEY_RANKS = {k: i for i, k in enumerate(KEY_ORDER)}
 

Detailed Description

OpenStreetMap (Map)

Function Documentation

◆ fetch_wikidata()

searx.engines.openstreetmap.fetch_wikidata ( nominatim_json,
user_language )
Update nominatim_json using the result of an unique to wikidata

For result in nominatim_json:
    If result['extratags']['wikidata'] or r['extratags']['wikidata link']:
        Set result['wikidata'] to { 'image': ..., 'image_sign':..., 'image_symbal':... }
        Set result['extratags']['wikipedia'] if not defined
        Set result['extratags']['contact:website'] if not defined

Definition at line 215 of file openstreetmap.py.

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

References searx.engines.openstreetmap.get_wikipedia_image().

Referenced by searx.engines.openstreetmap.response().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ get_data()

searx.engines.openstreetmap.get_data ( result,
user_language,
ignore_keys )
Return key, value of result['extratags']

Must be call after get_links

Note: the values are not translated

Definition at line 379 of file openstreetmap.py.

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

References searx.engines.openstreetmap.get_key_rank().

Referenced by searx.engines.openstreetmap.response().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ get_img_src()

searx.engines.openstreetmap.get_img_src ( result)
Get image URL from either wikidata or r['extratags']

Definition at line 330 of file openstreetmap.py.

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

Referenced by searx.engines.openstreetmap.response().

+ Here is the caller graph for this function:

◆ get_key_label()

searx.engines.openstreetmap.get_key_label ( key_name,
lang )
Get key label from OSM_KEYS_TAGS

Definition at line 442 of file openstreetmap.py.

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)

References searx.engines.openstreetmap.get_label().

+ Here is the call graph for this function:

◆ get_key_rank()

searx.engines.openstreetmap.get_key_rank ( k)
Get OSM key rank

The rank defines in which order the key are displayed in the HTML result

Definition at line 405 of file openstreetmap.py.

405def get_key_rank(k):
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

Referenced by searx.engines.openstreetmap.get_data().

+ Here is the caller graph for this function:

◆ get_label()

searx.engines.openstreetmap.get_label ( labels,
lang )
Get label from labels in OSM_KEYS_TAGS

in OSM_KEYS_TAGS, labels have key == '*'

Definition at line 417 of file openstreetmap.py.

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

Referenced by searx.engines.openstreetmap.get_key_label(), and searx.engines.openstreetmap.get_tag_label().

+ Here is the caller graph for this function:

◆ get_links()

searx.engines.openstreetmap.get_links ( result,
user_language )
Return links from result['extratags']

Definition at line 353 of file openstreetmap.py.

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

Referenced by searx.engines.openstreetmap.response().

+ Here is the caller graph for this function:

◆ get_tag_label()

searx.engines.openstreetmap.get_tag_label ( tag_category,
tag_name,
lang )
Get tag label from OSM_KEYS_TAGS

Definition at line 435 of file openstreetmap.py.

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

References searx.engines.openstreetmap.get_label().

Referenced by searx.engines.openstreetmap.response().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ get_title_address()

searx.engines.openstreetmap.get_title_address ( result)
Return title and address

title may be None

Definition at line 264 of file openstreetmap.py.

264def get_title_address(result):
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

Referenced by searx.engines.openstreetmap.response().

+ Here is the caller graph for this function:

◆ get_url_osm_geojson()

searx.engines.openstreetmap.get_url_osm_geojson ( result)
Get url, osm and geojson

Definition at line 310 of file openstreetmap.py.

310def get_url_osm_geojson(result):
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

Referenced by searx.engines.openstreetmap.response().

+ Here is the caller graph for this function:

◆ get_wikipedia_image()

searx.engines.openstreetmap.get_wikipedia_image ( raw_value)

Definition at line 209 of file openstreetmap.py.

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

Referenced by searx.engines.openstreetmap.fetch_wikidata().

+ Here is the caller graph for this function:

◆ request()

searx.engines.openstreetmap.request ( query,
params )
do search-request

Definition at line 140 of file openstreetmap.py.

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

◆ response()

searx.engines.openstreetmap.response ( resp)
get response from search-request

Definition at line 150 of file openstreetmap.py.

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 thumbnail = 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 'thumbnail': thumbnail,
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

References searx.engines.openstreetmap.fetch_wikidata(), searx.engines.openstreetmap.get_data(), searx.engines.openstreetmap.get_img_src(), searx.engines.openstreetmap.get_links(), searx.engines.openstreetmap.get_tag_label(), searx.engines.openstreetmap.get_title_address(), and searx.engines.openstreetmap.get_url_osm_geojson().

+ Here is the call graph for this function:

◆ value_to_https_link()

searx.engines.openstreetmap.value_to_https_link ( value)

Definition at line 71 of file openstreetmap.py.

71def value_to_https_link(value):
72 http = 'http://'
73 if value.startswith(http):
74 value = 'https://' + value[len(http) :]
75 return (value, value)
76
77

◆ value_to_website_link()

searx.engines.openstreetmap.value_to_website_link ( value)

Definition at line 78 of file openstreetmap.py.

78def value_to_website_link(value):
79 value = value.split(';')[0]
80 return (value, value)
81
82

◆ value_wikipedia_link()

searx.engines.openstreetmap.value_wikipedia_link ( value)

Definition at line 83 of file openstreetmap.py.

83def value_wikipedia_link(value):
84 value = value.split(':', 1)
85 return ('https://{0}.wikipedia.org/wiki/{1}'.format(*value), '{1} ({0})'.format(*value))
86
87

References searx.format.

◆ value_with_prefix()

searx.engines.openstreetmap.value_with_prefix ( prefix,
value )

Definition at line 88 of file openstreetmap.py.

88def value_with_prefix(prefix, value):
89 return (prefix + value, value)
90
91

Variable Documentation

◆ about

dict searx.engines.openstreetmap.about
Initial value:
1= {
2 "website": 'https://www.openstreetmap.org/',
3 "wikidata_id": 'Q936',
4 "official_api_documentation": 'http://wiki.openstreetmap.org/wiki/Nominatim',
5 "use_official_api": True,
6 "require_api_key": False,
7 "results": 'JSON',
8}

Definition at line 19 of file openstreetmap.py.

◆ base_url

str searx.engines.openstreetmap.base_url = 'https://nominatim.openstreetmap.org/'

Definition at line 35 of file openstreetmap.py.

◆ categories

list searx.engines.openstreetmap.categories = ['map']

Definition at line 29 of file openstreetmap.py.

◆ KEY_ORDER

list searx.engines.openstreetmap.KEY_ORDER
Initial value:
1= [
2 'cuisine',
3 'organic',
4 'delivery',
5 'delivery:covid19',
6 'opening_hours',
7 'opening_hours:covid19',
8 'fee',
9 'payment:*',
10 'currency:*',
11 'outdoor_seating',
12 'bench',
13 'wheelchair',
14 'level',
15 'building:levels',
16 'bin',
17 'public_transport',
18 'internet_access:ssid',
19]

Definition at line 118 of file openstreetmap.py.

◆ KEY_RANKS

dict searx.engines.openstreetmap.KEY_RANKS = {k: i for i, k in enumerate(KEY_ORDER)}

Definition at line 137 of file openstreetmap.py.

◆ language_support

bool searx.engines.openstreetmap.language_support = True

Definition at line 31 of file openstreetmap.py.

◆ paging

bool searx.engines.openstreetmap.paging = False

Definition at line 30 of file openstreetmap.py.

◆ result_id_url

str searx.engines.openstreetmap.result_id_url = 'https://openstreetmap.org/{osm_type}/{osm_id}'

Definition at line 37 of file openstreetmap.py.

◆ result_lat_lon_url

str searx.engines.openstreetmap.result_lat_lon_url = 'https://www.openstreetmap.org/?mlat={lat}&mlon={lon}&zoom={zoom}&layers=M'

Definition at line 38 of file openstreetmap.py.

◆ route_re

searx.engines.openstreetmap.route_re = re.compile('(?:from )?(.+) to (.+)')

Definition at line 41 of file openstreetmap.py.

◆ route_url

str searx.engines.openstreetmap.route_url = 'https://graphhopper.com/maps/?point={}&point={}&locale=en-US&vehicle=car&weighting=fastest&turn_costs=true&use_miles=false&layer=Omniscale'

Definition at line 40 of file openstreetmap.py.

◆ search_string

str searx.engines.openstreetmap.search_string = 'search?{query}&polygon_geojson=1&format=jsonv2&addressdetails=1&extratags=1&dedupe=1'

Definition at line 36 of file openstreetmap.py.

◆ send_accept_language_header

bool searx.engines.openstreetmap.send_accept_language_header = True

Definition at line 32 of file openstreetmap.py.

◆ VALUE_TO_LINK

dict searx.engines.openstreetmap.VALUE_TO_LINK
Initial value:
1= {
2 'website': value_to_website_link,
3 'contact:website': value_to_website_link,
4 'email': partial(value_with_prefix, 'mailto:'),
5 'contact:email': partial(value_with_prefix, 'mailto:'),
6 'contact:phone': partial(value_with_prefix, 'tel:'),
7 'phone': partial(value_with_prefix, 'tel:'),
8 'fax': partial(value_with_prefix, 'fax:'),
9 'contact:fax': partial(value_with_prefix, 'fax:'),
10 'contact:mastodon': value_to_https_link,
11 'facebook': value_to_https_link,
12 'contact:facebook': value_to_https_link,
13 'contact:foursquare': value_to_https_link,
14 'contact:instagram': value_to_https_link,
15 'contact:linkedin': value_to_https_link,
16 'contact:pinterest': value_to_https_link,
17 'contact:telegram': value_to_https_link,
18 'contact:tripadvisor': value_to_https_link,
19 'contact:twitter': value_to_https_link,
20 'contact:yelp': value_to_https_link,
21 'contact:youtube': value_to_https_link,
22 'contact:webcam': value_to_website_link,
23 'wikipedia': value_wikipedia_link,
24 'wikidata': partial(value_with_prefix, 'https://wikidata.org/wiki/'),
25 'brand:wikidata': partial(value_with_prefix, 'https://wikidata.org/wiki/'),
26}

Definition at line 92 of file openstreetmap.py.

◆ wikidata_image_sparql

str searx.engines.openstreetmap.wikidata_image_sparql
Initial value:
1= """
2select ?item ?itemLabel ?image ?sign ?symbol ?website ?wikipediaName
3where {
4 hint:Query hint:optimizer "None".
5 values ?item { %WIKIDATA_IDS% }
6 OPTIONAL { ?item wdt:P18|wdt:P8517|wdt:P4291|wdt:P5252|wdt:P3451|wdt:P4640|wdt:P5775|wdt:P2716|wdt:P1801|wdt:P4896 ?image }
7 OPTIONAL { ?item wdt:P1766|wdt:P8505|wdt:P8667 ?sign }
8 OPTIONAL { ?item wdt:P41|wdt:P94|wdt:P154|wdt:P158|wdt:P2910|wdt:P4004|wdt:P5962|wdt:P8972 ?symbol }
9 OPTIONAL { ?item wdt:P856 ?website }
10 SERVICE wikibase:label {
11 bd:serviceParam wikibase:language "%LANGUAGE%,en".
12 ?item rdfs:label ?itemLabel .
13 }
14 OPTIONAL {
15 ?wikipediaUrl schema:about ?item;
16 schema:isPartOf/wikibase:wikiGroup "wikipedia";
17 schema:name ?wikipediaName;
18 schema:inLanguage "%LANGUAGE%" .
19 }
20}
21ORDER by ?item
22"""

Definition at line 43 of file openstreetmap.py.