openstreetmap.py 15 KB

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