openstreetmap.py 15 KB

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