external_urls.py 2.5 KB

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