external_urls.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=missing-module-docstring
  3. import math
  4. from searx.data import EXTERNAL_URLS
  5. IMDB_PREFIX_TO_URL_ID = {
  6. 'tt': 'imdb_title',
  7. 'mn': 'imdb_name',
  8. 'ch': 'imdb_character',
  9. 'co': 'imdb_company',
  10. 'ev': 'imdb_event',
  11. }
  12. HTTP_WIKIMEDIA_IMAGE = 'http://commons.wikimedia.org/wiki/Special:FilePath/'
  13. def get_imdb_url_id(imdb_item_id):
  14. id_prefix = imdb_item_id[:2]
  15. return IMDB_PREFIX_TO_URL_ID.get(id_prefix)
  16. def get_wikimedia_image_id(url):
  17. if url.startswith(HTTP_WIKIMEDIA_IMAGE):
  18. return url[len(HTTP_WIKIMEDIA_IMAGE) :]
  19. if url.startswith('File:'):
  20. return url[len('File:') :]
  21. return url
  22. def get_external_url(url_id, item_id, alternative="default"):
  23. """Return an external URL or None if url_id is not found.
  24. url_id can take value from data/external_urls.json
  25. The "imdb_id" value is automatically converted according to the item_id value.
  26. If item_id is None, the raw URL with the $1 is returned.
  27. """
  28. if item_id is not None:
  29. if url_id == 'imdb_id':
  30. url_id = get_imdb_url_id(item_id)
  31. elif url_id == 'wikimedia_image':
  32. item_id = get_wikimedia_image_id(item_id)
  33. url_description = EXTERNAL_URLS.get(url_id)
  34. if url_description:
  35. url_template = url_description["urls"].get(alternative)
  36. if url_template is not None:
  37. if item_id is not None:
  38. return url_template.replace('$1', item_id)
  39. return url_template
  40. return None
  41. def get_earth_coordinates_url(latitude, longitude, osm_zoom, alternative='default'):
  42. url = (
  43. get_external_url('map', None, alternative)
  44. .replace('${latitude}', str(latitude))
  45. .replace('${longitude}', str(longitude))
  46. .replace('${zoom}', str(osm_zoom))
  47. )
  48. return url
  49. def area_to_osm_zoom(area):
  50. """Convert an area in km² into an OSM zoom. Less reliable if the shape is not round.
  51. logarithm regression using these data:
  52. * 9596961 -> 4 (China)
  53. * 3287263 -> 5 (India)
  54. * 643801 -> 6 (France)
  55. * 6028 -> 9
  56. * 1214 -> 10
  57. * 891 -> 12
  58. * 12 -> 13
  59. In WolframAlpha:
  60. >>> log fit {9596961,15},{3287263, 14},{643801,13},{6028,10},{1214,9},{891,7},{12,6}
  61. with 15 = 19-4 (China); 14 = 19-5 (India) and so on
  62. Args:
  63. area (int,float,str): area in km²
  64. Returns:
  65. int: OSM zoom or 19 in area is not a number
  66. """
  67. try:
  68. amount = float(area)
  69. return max(0, min(19, round(19 - 0.688297 * math.log(226.878 * amount))))
  70. except ValueError:
  71. return 19