openstreetmap.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """OpenStreetMap (Map)
  3. """
  4. import re
  5. import urllib.parse
  6. from functools import partial
  7. from flask_babel import gettext
  8. from searx.data import OSM_KEYS_TAGS, CURRENCIES
  9. from searx.external_urls import get_external_url
  10. from searx.engines.wikidata import send_wikidata_query, sparql_string_escape, get_thumbnail
  11. from searx.result_types import Answer
  12. # about
  13. about = {
  14. "website": 'https://www.openstreetmap.org/',
  15. "wikidata_id": 'Q936',
  16. "official_api_documentation": 'http://wiki.openstreetmap.org/wiki/Nominatim',
  17. "use_official_api": True,
  18. "require_api_key": False,
  19. "results": 'JSON',
  20. }
  21. # engine dependent config
  22. categories = ['map']
  23. paging = False
  24. language_support = True
  25. send_accept_language_header = True
  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'
  32. wikidata_image_sparql = """
  33. select ?item ?itemLabel ?image ?sign ?symbol ?website ?wikipediaName
  34. where {
  35. hint:Query hint:optimizer "None".
  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. params['url'] = base_url + search_string.format(query=urllib.parse.urlencode({'q': query}))
  119. return params
  120. def response(resp):
  121. results = []
  122. nominatim_json = resp.json()
  123. user_language = resp.search_params['language']
  124. l = re.findall(r"from\s+(.*)\s+to\s+(.+)", resp.search_params["query"])
  125. if not l:
  126. l = re.findall(r"\s*(.*)\s+to\s+(.+)", resp.search_params["query"])
  127. if l:
  128. point1, point2 = [urllib.parse.quote_plus(p) for p in l[0]]
  129. Answer(
  130. results=results,
  131. answer=gettext('Show route in map ..'),
  132. url=f"{route_url}/?point={point1}&point={point2}",
  133. )
  134. # simplify the code below: make sure extratags is a dictionary
  135. for result in nominatim_json:
  136. if not isinstance(result.get('extratags'), dict):
  137. result["extratags"] = {}
  138. # fetch data from wikidata
  139. fetch_wikidata(nominatim_json, user_language)
  140. # create results
  141. for result in nominatim_json:
  142. title, address = get_title_address(result)
  143. # ignore result without title
  144. if not title:
  145. continue
  146. url, osm, geojson = get_url_osm_geojson(result)
  147. thumbnail = get_thumbnail(get_img_src(result))
  148. links, link_keys = get_links(result, user_language)
  149. data = get_data(result, user_language, link_keys)
  150. results.append(
  151. {
  152. 'template': 'map.html',
  153. 'title': title,
  154. 'address': address,
  155. 'address_label': get_key_label('addr', user_language),
  156. 'url': url,
  157. 'osm': osm,
  158. 'geojson': geojson,
  159. 'thumbnail': thumbnail,
  160. 'links': links,
  161. 'data': data,
  162. 'type': get_tag_label(result.get('category'), result.get('type', ''), user_language),
  163. 'type_icon': result.get('icon'),
  164. 'content': '',
  165. 'longitude': result['lon'],
  166. 'latitude': result['lat'],
  167. 'boundingbox': result['boundingbox'],
  168. }
  169. )
  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_language):
  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. extratags = result['extratags']
  187. # ignore brand:wikidata
  188. wd_id = extratags.get('wikidata', extratags.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. extratags = result['extratags']
  288. if not img_src and extratags.get('image'):
  289. img_src = extratags['image']
  290. del extratags['image']
  291. if not img_src and extratags.get('wikimedia_commons'):
  292. img_src = get_external_url('wikimedia_image', extratags['wikimedia_commons'])
  293. del 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. extratags = result['extratags']
  300. if not extratags:
  301. # minor optimization : no need to check VALUE_TO_LINK if extratags is empty
  302. return links, link_keys
  303. for k, mapping_function in VALUE_TO_LINK.items():
  304. raw_value = extratags.get(k)
  305. if not raw_value:
  306. continue
  307. url, url_label = mapping_function(raw_value)
  308. if url.startswith('https://wikidata.org'):
  309. url_label = result.get('wikidata', {}).get('itemLabel') or url_label
  310. links.append(
  311. {
  312. 'label': get_key_label(k, user_language),
  313. 'url': url,
  314. 'url_label': url_label,
  315. }
  316. )
  317. link_keys.add(k)
  318. return links, link_keys
  319. def get_data(result, user_language, ignore_keys):
  320. """Return key, value of result['extratags']
  321. Must be call after get_links
  322. Note: the values are not translated
  323. """
  324. data = []
  325. for k, v in result['extratags'].items():
  326. if k in ignore_keys:
  327. continue
  328. if get_key_rank(k) is None:
  329. continue
  330. k_label = get_key_label(k, user_language)
  331. if k_label:
  332. data.append(
  333. {
  334. 'label': k_label,
  335. 'key': k,
  336. 'value': v,
  337. }
  338. )
  339. data.sort(key=lambda entry: (get_key_rank(entry['key']), entry['label']))
  340. return data
  341. def get_key_rank(k):
  342. """Get OSM key rank
  343. The rank defines in which order the key are displayed in the HTML result
  344. """
  345. key_rank = KEY_RANKS.get(k)
  346. if key_rank is None:
  347. # "payment:*" in KEY_ORDER matches "payment:cash", "payment:debit card", etc...
  348. key_rank = KEY_RANKS.get(k.split(':')[0] + ':*')
  349. return key_rank
  350. def get_label(labels, lang):
  351. """Get label from labels in OSM_KEYS_TAGS
  352. in OSM_KEYS_TAGS, labels have key == '*'
  353. """
  354. tag_label = labels.get(lang.lower())
  355. if tag_label is None:
  356. # example: if 'zh-hk' is not found, check 'zh'
  357. tag_label = labels.get(lang.split('-')[0])
  358. if tag_label is None and lang != 'en':
  359. # example: if 'zh' is not found, check 'en'
  360. tag_label = labels.get('en')
  361. if tag_label is None and len(labels.values()) > 0:
  362. # example: if still not found, use the first entry
  363. tag_label = labels.values()[0]
  364. return tag_label
  365. def get_tag_label(tag_category, tag_name, lang):
  366. """Get tag label from OSM_KEYS_TAGS"""
  367. tag_name = '' if tag_name is None else tag_name
  368. tag_labels = OSM_KEYS_TAGS['tags'].get(tag_category, {}).get(tag_name, {})
  369. return get_label(tag_labels, lang)
  370. def get_key_label(key_name, lang):
  371. """Get key label from OSM_KEYS_TAGS"""
  372. if key_name.startswith('currency:'):
  373. # currency:EUR --> get the name from the CURRENCIES variable
  374. # see https://wiki.openstreetmap.org/wiki/Key%3Acurrency
  375. # and for example https://taginfo.openstreetmap.org/keys/currency:EUR#values
  376. # but there is also currency=EUR (currently not handled)
  377. # https://taginfo.openstreetmap.org/keys/currency#values
  378. currency = key_name.split(':')
  379. if len(currency) > 1:
  380. o = CURRENCIES['iso4217'].get(currency[1])
  381. if o:
  382. return get_label(o, lang).lower()
  383. return currency[1]
  384. labels = OSM_KEYS_TAGS['keys']
  385. for k in key_name.split(':') + ['*']:
  386. labels = labels.get(k)
  387. if labels is None:
  388. return None
  389. return get_label(labels, lang)