openstreetmap.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """OpenStreetMap (Map)
  4. """
  5. import re
  6. from json import loads
  7. from urllib.parse import urlencode
  8. from functools import partial
  9. from flask_babel import gettext
  10. from searx.data import OSM_KEYS_TAGS, CURRENCIES
  11. from searx.utils import searx_useragent
  12. from searx.external_urls import get_external_url
  13. from searx.engines.wikidata import send_wikidata_query, sparql_string_escape, get_thumbnail
  14. # about
  15. about = {
  16. "website": 'https://www.openstreetmap.org/',
  17. "wikidata_id": 'Q936',
  18. "official_api_documentation": 'http://wiki.openstreetmap.org/wiki/Nominatim',
  19. "use_official_api": True,
  20. "require_api_key": False,
  21. "results": 'JSON',
  22. }
  23. # engine dependent config
  24. categories = ['map']
  25. paging = False
  26. language_support = 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. accept_language = 'en' if params['language'] == 'all' else params['language']
  125. params['headers']['Accept-Language'] = accept_language
  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. fetch_wikidata(nominatim_json, user_language)
  140. for result in nominatim_json:
  141. title, address = get_title_address(result)
  142. # ignore result without title
  143. if not title:
  144. continue
  145. url, osm, geojson = get_url_osm_geojson(result)
  146. img_src = get_thumbnail(get_img_src(result))
  147. links, link_keys = get_links(result, user_language)
  148. data = get_data(result, user_language, link_keys)
  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. def get_wikipedia_image(raw_value):
  171. if not raw_value:
  172. return None
  173. return get_external_url('wikimedia_image', raw_value)
  174. def fetch_wikidata(nominatim_json, user_language):
  175. """Update nominatim_json using the result of an unique to wikidata
  176. For result in nominatim_json:
  177. If result['extratags']['wikidata'] or r['extratags']['wikidata link']:
  178. Set result['wikidata'] to { 'image': ..., 'image_sign':..., 'image_symbal':... }
  179. Set result['extratags']['wikipedia'] if not defined
  180. Set result['extratags']['contact:website'] if not defined
  181. """
  182. wikidata_ids = []
  183. wd_to_results = {}
  184. for result in nominatim_json:
  185. e = result.get("extratags")
  186. if e:
  187. # ignore brand:wikidata
  188. wd_id = e.get("wikidata", e.get("wikidata link"))
  189. if wd_id and wd_id not in wikidata_ids:
  190. wikidata_ids.append("wd:" + wd_id)
  191. wd_to_results.setdefault(wd_id, []).append(result)
  192. if wikidata_ids:
  193. user_language = 'en' if user_language == 'all' else user_language.split('-')[0]
  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_language)
  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_language + ':' + 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. osm_type = result.get('osm_type', result.get('type'))
  263. if 'osm_id' not in result:
  264. # see https://github.com/osm-search/Nominatim/issues/1521
  265. # query example: "EC1M 5RF London"
  266. url = result_lat_lon_url.format(lat=result['lat'], lon=result['lon'], zoom=12)
  267. osm = {}
  268. else:
  269. url = result_id_url.format(osm_type=osm_type, osm_id=result['osm_id'])
  270. osm = {'type': osm_type, 'id': result['osm_id']}
  271. geojson = result.get('geojson')
  272. # if no geojson is found and osm_type is a node, add geojson Point
  273. if not geojson and osm_type == 'node':
  274. geojson = {'type': 'Point', 'coordinates': [result['lon'], result['lat']]}
  275. return url, osm, geojson
  276. def get_img_src(result):
  277. """Get image URL from either wikidata or r['extratags']"""
  278. # wikidata
  279. img_src = None
  280. if 'wikidata' in result:
  281. img_src = result['wikidata']['image']
  282. if not img_src:
  283. img_src = result['wikidata']['image_symbol']
  284. if not img_src:
  285. img_src = result['wikidata']['image_sign']
  286. # img_src
  287. if not img_src and result.get('extratags', {}).get('image'):
  288. img_src = result['extratags']['image']
  289. del result['extratags']['image']
  290. if not img_src and result.get('extratags', {}).get('wikimedia_commons'):
  291. img_src = get_external_url('wikimedia_image', result['extratags']['wikimedia_commons'])
  292. del result['extratags']['wikimedia_commons']
  293. return img_src
  294. def get_links(result, user_language):
  295. """Return links from result['extratags']"""
  296. links = []
  297. link_keys = set()
  298. for k, mapping_function in VALUE_TO_LINK.items():
  299. raw_value = result['extratags'].get(k)
  300. if raw_value:
  301. url, url_label = mapping_function(raw_value)
  302. if url.startswith('https://wikidata.org'):
  303. url_label = result.get('wikidata', {}).get('itemLabel') or url_label
  304. links.append(
  305. {
  306. 'label': get_key_label(k, user_language),
  307. 'url': url,
  308. 'url_label': url_label,
  309. }
  310. )
  311. link_keys.add(k)
  312. return links, link_keys
  313. def get_data(result, user_language, ignore_keys):
  314. """Return key, value of result['extratags']
  315. Must be call after get_links
  316. Note: the values are not translated
  317. """
  318. data = []
  319. for k, v in result['extratags'].items():
  320. if k in ignore_keys:
  321. continue
  322. if get_key_rank(k) is None:
  323. continue
  324. k_label = get_key_label(k, user_language)
  325. if k_label:
  326. data.append(
  327. {
  328. 'label': k_label,
  329. 'key': k,
  330. 'value': v,
  331. }
  332. )
  333. data.sort(key=lambda entry: (get_key_rank(entry['key']), entry['label']))
  334. return data
  335. def get_key_rank(k):
  336. """Get OSM key rank
  337. The rank defines in which order the key are displayed in the HTML result
  338. """
  339. key_rank = KEY_RANKS.get(k)
  340. if key_rank is None:
  341. # "payment:*" in KEY_ORDER matches "payment:cash", "payment:debit card", etc...
  342. key_rank = KEY_RANKS.get(k.split(':')[0] + ':*')
  343. return key_rank
  344. def get_label(labels, lang):
  345. """Get label from labels in OSM_KEYS_TAGS
  346. in OSM_KEYS_TAGS, labels have key == '*'
  347. """
  348. tag_label = labels.get(lang.lower())
  349. if tag_label is None:
  350. # example: if 'zh-hk' is not found, check 'zh'
  351. tag_label = labels.get(lang.split('-')[0])
  352. if tag_label is None and lang != 'en':
  353. # example: if 'zh' is not found, check 'en'
  354. tag_label = labels.get('en')
  355. if tag_label is None and len(labels.values()) > 0:
  356. # example: if still not found, use the first entry
  357. tag_label = labels.values()[0]
  358. return tag_label
  359. def get_tag_label(tag_category, tag_name, lang):
  360. """Get tag label from OSM_KEYS_TAGS"""
  361. tag_name = '' if tag_name is None else tag_name
  362. tag_labels = OSM_KEYS_TAGS['tags'].get(tag_category, {}).get(tag_name, {})
  363. return get_label(tag_labels, lang)
  364. def get_key_label(key_name, lang):
  365. """Get key label from OSM_KEYS_TAGS"""
  366. if key_name.startswith('currency:'):
  367. # currency:EUR --> get the name from the CURRENCIES variable
  368. # see https://wiki.openstreetmap.org/wiki/Key%3Acurrency
  369. # and for exampe https://taginfo.openstreetmap.org/keys/currency:EUR#values
  370. # but there is also currency=EUR (currently not handled)
  371. # https://taginfo.openstreetmap.org/keys/currency#values
  372. currency = key_name.split(':')
  373. if len(currency) > 1:
  374. o = CURRENCIES['iso4217'].get(currency)
  375. if o:
  376. return get_label(o, lang).lower()
  377. return currency
  378. labels = OSM_KEYS_TAGS['keys']
  379. for k in key_name.split(':') + ['*']:
  380. labels = labels.get(k)
  381. if labels is None:
  382. return None
  383. return get_label(labels, lang)