lib.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. import json
  2. import math
  3. import requests
  4. import haversine
  5. # Google API key, with access to Street View Static API
  6. google_api_key = "AIzaSyAqjCYR6Szph0X0H_iD6O1HenFhL9jySOo"
  7. metadata_url = "https://maps.googleapis.com/maps/api/streetview/metadata"
  8. mapcrunch_url = "http://www.mapcrunch.com/_r/"
  9. rsv_url = "https://randomstreetview.com/data"
  10. def point_has_streetview(lat, lng):
  11. """
  12. Returns True if the streetview metadata endpoint says a given point has
  13. data available, and False otherwise.
  14. This function calls the streetview metadata endpoint - there is no quota consumed.
  15. """
  16. params = {
  17. "key": google_api_key,
  18. "location": f"{lat},{lng}",
  19. }
  20. js = requests.get(metadata_url, params=params).json()
  21. return js["status"] == "OK"
  22. def generate_coord(max_retries=100, only_america=False):
  23. """
  24. Returns (latitude, longitude) of usable coord (where google has data).
  25. This function will attempt at most max_retries calls to map crunch to fetch
  26. candidate points, and will exit as soon as a suitable candidate is found.
  27. This function calls the streetview metadata endpoint - there is no quota consumed.
  28. """
  29. mc_url = mapcrunch_url + ("?c=21" if only_america else "")
  30. for _ in range(max_retries):
  31. points_res = requests.get(mc_url).text
  32. points_js = json.loads(points_res.strip("while(1); "))
  33. if "c=" not in mc_url:
  34. mc_url += f"?c={points_js['country']}" # lock to the first country randomed
  35. for lat, lng in points_js["points"]:
  36. if point_has_streetview(lat, lng):
  37. return (lat, lng)
  38. def call_random_street_view(only_america=False):
  39. """
  40. Returns an array of (some number of) tuples, each being (latitude, longitude).
  41. All points will be valid streetview coordinates. There is no guarantee as to the
  42. length of this array (it may be empty), but it will never be None.
  43. This function calls the streetview metadata endpoint - there is no quota consumed.
  44. """
  45. rsv_js = requests.post(rsv_url, data={"country": "us" if only_america else "all"}).json()
  46. if not rsv_js["success"]:
  47. return []
  48. return [
  49. (point["lat"], point["lng"])
  50. for point in rsv_js["locations"]
  51. if point_has_streetview(point["lat"], point["lng"])
  52. ]
  53. def random_street_view_generator(only_america=False):
  54. """
  55. Returns a generator which will lazily use call_random_street_view to generate new
  56. street view points.
  57. """
  58. points = []
  59. while True:
  60. if len(points) == 0:
  61. points = call_random_street_view(only_america=only_america)
  62. else:
  63. yield points.pop()
  64. mean_earth_radius_km = (6378 + 6357) / 2
  65. # if you're more than 1/4 of the Earth's circumfrence away, you get 0
  66. max_dist_km = (math.pi * mean_earth_radius_km) / 2 # this is about 10,000 km
  67. # if you're within 1/16 of the Earth's circumfrence away, you get at least 1000 points
  68. quarter_of_max_km = max_dist_km / 4 # this is about 2,500 km
  69. # https://www.wolframalpha.com/input/?i=sqrt%28%28%28land+mass+of+earth%29+%2F+7%29%29+%2F+pi%29+in+kilometers
  70. # this is the average "radius" of a continent
  71. # within this radius, you get at least 2000 points
  72. avg_continental_rad_km = 1468.0
  73. # somewhat arbitrarily, if you're within 1000 km, you get at least 3000 points
  74. one_thousand = 1000.0
  75. # https://www.wolframalpha.com/input/?i=sqrt%28%28%28land+mass+of+earth%29+%2F+%28number+of+countries+on+earth%29%29+%2F+pi%29+in+kilometers
  76. # this is the average "radius" of a country
  77. # within this radius, you get at least 4000 points
  78. avg_country_rad_km = 479.7
  79. # if you're within 150m, you get a perfect score of 5000
  80. min_dist_km = 0.15
  81. def score_within(raw_dist, min_dist, max_dist):
  82. """
  83. Gives a score between 0 and 1000, with 1000 for the min_dist and 0 for the max_dist
  84. """
  85. # scale the distance down to [0.0, 1.0], then multiply it by 2 for easing
  86. pd2 = 2 * (raw_dist - min_dist) / (max_dist - min_dist)
  87. # perform a quadratic ease-in-out on pd2
  88. r = (pd2 ** 2) / 2 if pd2 < 1 else 1 - (((2 - pd2) ** 2) / 2)
  89. # use this to ease between 1000 and 0
  90. return int(1000 * (1 - r))
  91. def score(target, guess):
  92. """
  93. Takes in two (latitude, longitude) pairs and produces an int score.
  94. Score is in the (inclusive) range [0, 5000]
  95. Higher scores are closer.
  96. Returns (score, distance in km)
  97. """
  98. dist_km = haversine.haversine(target, guess)
  99. if dist_km <= min_dist_km:
  100. point_score = 5000
  101. elif dist_km <= avg_country_rad_km:
  102. point_score = 4000 + score_within(dist_km, min_dist_km, avg_country_rad_km)
  103. elif dist_km <= one_thousand:
  104. point_score = 3000 + score_within(dist_km, avg_country_rad_km, one_thousand)
  105. elif dist_km <= avg_continental_rad_km:
  106. point_score = 2000 + score_within(dist_km, one_thousand, avg_continental_rad_km)
  107. elif dist_km <= quarter_of_max_km:
  108. point_score = 1000 + score_within(dist_km, avg_continental_rad_km, quarter_of_max_km)
  109. elif dist_km <= max_dist_km:
  110. point_score = score_within(dist_km, quarter_of_max_km, max_dist_km)
  111. else: # dist_km > max_dist_km
  112. point_score = 0
  113. return point_score, dist_km