openstreetmap.py 15 KB

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