openstreetmap.py 16 KB

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