openstreetmap.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. OpenStreetMap (Map)
  4. """
  5. # lint: pylint
  6. # pylint: disable=missing-function-docstring
  7. import re
  8. from json import loads
  9. from urllib.parse import urlencode
  10. from functools import partial
  11. from flask_babel import gettext
  12. from searx.data import OSM_KEYS_TAGS, CURRENCIES
  13. from searx.utils import searx_useragent
  14. from searx.external_urls import get_external_url
  15. from searx.engines.wikidata import send_wikidata_query, sparql_string_escape
  16. # about
  17. about = {
  18. "website": 'https://www.openstreetmap.org/',
  19. "wikidata_id": 'Q936',
  20. "official_api_documentation": 'http://wiki.openstreetmap.org/wiki/Nominatim',
  21. "use_official_api": True,
  22. "require_api_key": False,
  23. "results": 'JSON',
  24. }
  25. # engine dependent config
  26. categories = ['map']
  27. paging = False
  28. # search-url
  29. base_url = 'https://nominatim.openstreetmap.org/'
  30. search_string = 'search?{query}&polygon_geojson=1&format=jsonv2&addressdetails=1&extratags=1&dedupe=1'
  31. result_id_url = 'https://openstreetmap.org/{osm_type}/{osm_id}'
  32. result_lat_lon_url = 'https://www.openstreetmap.org/?mlat={lat}&mlon={lon}&zoom={zoom}&layers=M'
  33. 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
  34. route_re = re.compile('(?:from )?(.+) to (.+)')
  35. wikidata_image_sparql = """
  36. select ?item ?itemLabel ?image ?sign ?symbol ?website ?wikipediaName
  37. where {
  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. return params
  125. def response(resp):
  126. """get response from search-request"""
  127. results = []
  128. nominatim_json = loads(resp.text)
  129. user_language = resp.search_params['language']
  130. if resp.search_params['route']:
  131. results.append(
  132. {
  133. 'answer': gettext('Get directions'),
  134. 'url': route_url.format(*resp.search_params['route'].groups()),
  135. }
  136. )
  137. fetch_wikidata(nominatim_json, user_language)
  138. # parse results
  139. for result in nominatim_json:
  140. title, address = get_title_address(result)
  141. # ignore result without title
  142. if not title:
  143. continue
  144. url, osm, geojson = get_url_osm_geojson(result)
  145. img_src = get_img_src(result)
  146. links, link_keys = get_links(result, user_language)
  147. data = get_data(result, user_language, link_keys)
  148. # append result
  149. results.append(
  150. {
  151. 'template': 'map.html',
  152. 'title': title,
  153. 'address': address,
  154. 'address_label': get_key_label('addr', user_language),
  155. 'url': url,
  156. 'osm': osm,
  157. 'geojson': geojson,
  158. 'img_src': img_src,
  159. 'links': links,
  160. 'data': data,
  161. 'type': get_tag_label(result.get('category'), result.get('type', ''), user_language),
  162. 'type_icon': result.get('icon'),
  163. 'content': '',
  164. 'longitude': result['lon'],
  165. 'latitude': result['lat'],
  166. 'boundingbox': result['boundingbox'],
  167. }
  168. )
  169. # return results
  170. return results
  171. def get_wikipedia_image(raw_value):
  172. if not raw_value:
  173. return None
  174. return get_external_url('wikimedia_image', raw_value)
  175. def fetch_wikidata(nominatim_json, user_langage):
  176. """Update nominatim_json using the result of an unique to wikidata
  177. For result in nominatim_json:
  178. If result['extratags']['wikidata'] or r['extratags']['wikidata link']:
  179. Set result['wikidata'] to { 'image': ..., 'image_sign':..., 'image_symbal':... }
  180. Set result['extratags']['wikipedia'] if not defined
  181. Set result['extratags']['contact:website'] if not defined
  182. """
  183. wikidata_ids = []
  184. wd_to_results = {}
  185. for result in nominatim_json:
  186. e = result.get("extratags")
  187. if e:
  188. # ignore brand:wikidata
  189. wd_id = e.get("wikidata", e.get("wikidata link"))
  190. if wd_id and wd_id not in wikidata_ids:
  191. wikidata_ids.append("wd:" + wd_id)
  192. wd_to_results.setdefault(wd_id, []).append(result)
  193. if wikidata_ids:
  194. wikidata_ids_str = " ".join(wikidata_ids)
  195. query = wikidata_image_sparql.replace('%WIKIDATA_IDS%', sparql_string_escape(wikidata_ids_str)).replace(
  196. '%LANGUAGE%', sparql_string_escape(user_langage)
  197. )
  198. wikidata_json = send_wikidata_query(query)
  199. for wd_result in wikidata_json.get('results', {}).get('bindings', {}):
  200. wd_id = wd_result['item']['value'].replace('http://www.wikidata.org/entity/', '')
  201. for result in wd_to_results.get(wd_id, []):
  202. result['wikidata'] = {
  203. 'itemLabel': wd_result['itemLabel']['value'],
  204. 'image': get_wikipedia_image(wd_result.get('image', {}).get('value')),
  205. 'image_sign': get_wikipedia_image(wd_result.get('sign', {}).get('value')),
  206. 'image_symbol': get_wikipedia_image(wd_result.get('symbol', {}).get('value')),
  207. }
  208. # overwrite wikipedia link
  209. wikipedia_name = wd_result.get('wikipediaName', {}).get('value')
  210. if wikipedia_name:
  211. result['extratags']['wikipedia'] = user_langage + ':' + wikipedia_name
  212. # get website if not already defined
  213. website = wd_result.get('website', {}).get('value')
  214. if (
  215. website
  216. and not result['extratags'].get('contact:website')
  217. and not result['extratags'].get('website')
  218. ):
  219. result['extratags']['contact:website'] = website
  220. def get_title_address(result):
  221. """Return title and address
  222. title may be None
  223. """
  224. address_raw = result.get('address')
  225. address_name = None
  226. address = {}
  227. # get name
  228. if (
  229. result['category'] == 'amenity'
  230. or result['category'] == 'shop'
  231. or result['category'] == 'tourism'
  232. or result['category'] == 'leisure'
  233. ):
  234. if address_raw.get('address29'):
  235. # https://github.com/osm-search/Nominatim/issues/1662
  236. address_name = address_raw.get('address29')
  237. else:
  238. address_name = address_raw.get(result['category'])
  239. elif result['type'] in address_raw:
  240. address_name = address_raw.get(result['type'])
  241. # add rest of adressdata, if something is already found
  242. if address_name:
  243. title = address_name
  244. address.update(
  245. {
  246. 'name': address_name,
  247. 'house_number': address_raw.get('house_number'),
  248. 'road': address_raw.get('road'),
  249. 'locality': address_raw.get(
  250. 'city', address_raw.get('town', address_raw.get('village')) # noqa
  251. ), # noqa
  252. 'postcode': address_raw.get('postcode'),
  253. 'country': address_raw.get('country'),
  254. 'country_code': address_raw.get('country_code'),
  255. }
  256. )
  257. else:
  258. title = result.get('display_name')
  259. return title, address
  260. def get_url_osm_geojson(result):
  261. """Get url, osm and geojson
  262. """
  263. osm_type = result.get('osm_type', result.get('type'))
  264. if 'osm_id' not in result:
  265. # see https://github.com/osm-search/Nominatim/issues/1521
  266. # query example: "EC1M 5RF London"
  267. url = result_lat_lon_url.format(lat=result['lat'], lon=result['lon'], zoom=12)
  268. osm = {}
  269. else:
  270. url = result_id_url.format(osm_type=osm_type, osm_id=result['osm_id'])
  271. osm = {'type': osm_type, 'id': result['osm_id']}
  272. geojson = result.get('geojson')
  273. # if no geojson is found and osm_type is a node, add geojson Point
  274. if not geojson and osm_type == 'node':
  275. geojson = {'type': 'Point', 'coordinates': [result['lon'], result['lat']]}
  276. return url, osm, geojson
  277. def get_img_src(result):
  278. """Get image URL from either wikidata or r['extratags']"""
  279. # wikidata
  280. img_src = None
  281. if 'wikidata' in result:
  282. img_src = result['wikidata']['image']
  283. if not img_src:
  284. img_src = result['wikidata']['image_symbol']
  285. if not img_src:
  286. img_src = result['wikidata']['image_sign']
  287. # img_src
  288. if not img_src and result.get('extratags', {}).get('image'):
  289. img_src = result['extratags']['image']
  290. del result['extratags']['image']
  291. if not img_src and result.get('extratags', {}).get('wikimedia_commons'):
  292. img_src = get_external_url('wikimedia_image', result['extratags']['wikimedia_commons'])
  293. del result['extratags']['wikimedia_commons']
  294. return img_src
  295. def get_links(result, user_language):
  296. """Return links from result['extratags']"""
  297. links = []
  298. link_keys = set()
  299. for k, mapping_function in VALUE_TO_LINK.items():
  300. raw_value = result['extratags'].get(k)
  301. if raw_value:
  302. url, url_label = mapping_function(raw_value)
  303. if url.startswith('https://wikidata.org'):
  304. url_label = result.get('wikidata', {}).get('itemLabel') or url_label
  305. links.append(
  306. {
  307. 'label': get_key_label(k, user_language),
  308. 'url': url,
  309. 'url_label': url_label,
  310. }
  311. )
  312. link_keys.add(k)
  313. return links, link_keys
  314. def get_data(result, user_language, ignore_keys):
  315. """Return key, value of result['extratags']
  316. Must be call after get_links
  317. Note: the values are not translated
  318. """
  319. data = []
  320. for k, v in result['extratags'].items():
  321. if k in ignore_keys:
  322. continue
  323. if get_key_rank(k) is None:
  324. continue
  325. k_label = get_key_label(k, user_language)
  326. if k_label:
  327. data.append(
  328. {
  329. 'label': k_label,
  330. 'key': k,
  331. 'value': v,
  332. }
  333. )
  334. data.sort(key=lambda entry: (get_key_rank(entry['key']), entry['label']))
  335. return data
  336. def get_key_rank(k):
  337. """Get OSM key rank
  338. The rank defines in which order the key are displayed in the HTML result
  339. """
  340. key_rank = KEY_RANKS.get(k)
  341. if key_rank is None:
  342. # "payment:*" in KEY_ORDER matches "payment:cash", "payment:debit card", etc...
  343. key_rank = KEY_RANKS.get(k.split(':')[0] + ':*')
  344. return key_rank
  345. def get_label(labels, lang):
  346. """Get label from labels in OSM_KEYS_TAGS
  347. in OSM_KEYS_TAGS, labels have key == '*'
  348. """
  349. tag_label = labels.get(lang.lower())
  350. if tag_label is None:
  351. # example: if 'zh-hk' is not found, check 'zh'
  352. tag_label = labels.get(lang.split('-')[0])
  353. if tag_label is None and lang != 'en':
  354. # example: if 'zh' is not found, check 'en'
  355. tag_label = labels.get('en')
  356. if tag_label is None and len(labels.values()) > 0:
  357. # example: if still not found, use the first entry
  358. tag_label = labels.values()[0]
  359. return tag_label
  360. def get_tag_label(tag_category, tag_name, lang):
  361. """Get tag label from OSM_KEYS_TAGS"""
  362. tag_name = '' if tag_name is None else tag_name
  363. tag_labels = OSM_KEYS_TAGS['tags'].get(tag_category, {}).get(tag_name, {})
  364. return get_label(tag_labels, lang)
  365. def get_key_label(key_name, lang):
  366. """Get key label from OSM_KEYS_TAGS"""
  367. if key_name.startswith('currency:'):
  368. # currency:EUR --> get the name from the CURRENCIES variable
  369. # see https://wiki.openstreetmap.org/wiki/Key%3Acurrency
  370. # and for exampe https://taginfo.openstreetmap.org/keys/currency:EUR#values
  371. # but there is also currency=EUR (currently not handled)
  372. # https://taginfo.openstreetmap.org/keys/currency#values
  373. currency = key_name.split(':')
  374. if len(currency) > 1:
  375. o = CURRENCIES['iso4217'].get(currency)
  376. if o:
  377. return get_label(o, lang).lower()
  378. return currency
  379. labels = OSM_KEYS_TAGS['keys']
  380. for k in key_name.split(':') + ['*']:
  381. labels = labels.get(k)
  382. if labels is None:
  383. return None
  384. return get_label(labels, lang)