openstreetmap.py 15 KB

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