external_urls.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. def get_imdb_url_id(imdb_item_id):
  11. id_prefix = imdb_item_id[:2]
  12. return IMDB_PREFIX_TO_URL_ID.get(id_prefix)
  13. def get_external_url(url_id, item_id, alternative="default"):
  14. """Return an external URL or None if url_id is not found.
  15. url_id can take value from data/external_urls.json
  16. The "imdb_id" value is automaticaly converted according to the item_id value.
  17. If item_id is None, the raw URL with the $1 is returned.
  18. """
  19. if url_id == 'imdb_id' and item_id is not None:
  20. url_id = get_imdb_url_id(item_id)
  21. url_description = EXTERNAL_URLS.get(url_id)
  22. if url_description:
  23. url_template = url_description["urls"].get(alternative)
  24. if url_template is not None:
  25. if item_id is not None:
  26. return url_template.replace('$1', item_id)
  27. else:
  28. return url_template
  29. return None
  30. def get_earth_coordinates_url(latitude, longitude, osm_zoom, alternative='default'):
  31. url = get_external_url('map', None, alternative)\
  32. .replace('${latitude}', str(latitude))\
  33. .replace('${longitude}', str(longitude))\
  34. .replace('${zoom}', str(osm_zoom))
  35. return url
  36. def area_to_osm_zoom(area):
  37. """Convert an area in km² into an OSM zoom. Less reliable if the shape is not round.
  38. logarithm regression using these data:
  39. * 9596961 -> 4 (China)
  40. * 3287263 -> 5 (India)
  41. * 643801 -> 6 (France)
  42. * 6028 -> 9
  43. * 1214 -> 10
  44. * 891 -> 12
  45. * 12 -> 13
  46. In WolframAlpha:
  47. >>> log fit {9596961,15},{3287263, 14},{643801,13},{6028,10},{1214,9},{891,7},{12,6}
  48. with 15 = 19-4 (China); 14 = 19-5 (India) and so on
  49. Args:
  50. area (int,float,str): area in km²
  51. Returns:
  52. int: OSM zoom or 19 in area is not a number
  53. """
  54. try:
  55. amount = float(area)
  56. return max(0, min(19, round(19 - 0.688297 * math.log(226.878 * amount))))
  57. except ValueError:
  58. return 19