lib.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. import json
  2. import math
  3. import random
  4. import threading
  5. import collections
  6. import requests
  7. import haversine
  8. # Google API key, with access to Street View Static API
  9. google_api_key = "AIzaSyAqjCYR6Szph0X0H_iD6O1HenFhL9jySOo"
  10. metadata_url = "https://maps.googleapis.com/maps/api/streetview/metadata"
  11. mapcrunch_url = "http://www.mapcrunch.com/_r/"
  12. rsv_url = "https://randomstreetview.com/data"
  13. urban_centers_usa = []
  14. urban_centers_non_usa = []
  15. with open("./urban-centers-usa.csv") as infile:
  16. for line in infile:
  17. lat, lng = line.split(",")
  18. urban_centers_usa.append((float(lat.strip()), float(lng.strip())))
  19. with open("./urban-centers-non-usa.csv") as infile:
  20. for line in infile:
  21. lat, lng = line.split(",")
  22. urban_centers_non_usa.append((float(lat.strip()), float(lng.strip())))
  23. def point_has_streetview(lat, lng):
  24. """
  25. Returns True if the streetview metadata endpoint says a given point has
  26. data available, and False otherwise.
  27. This function calls the streetview metadata endpoint - there is no quota consumed.
  28. """
  29. params = {
  30. "key": google_api_key,
  31. "location": f"{lat},{lng}",
  32. }
  33. js = requests.get(metadata_url, params=params).json()
  34. return js["status"] == "OK"
  35. def generate_coord(max_retries=100, only_america=False):
  36. """
  37. Returns (latitude, longitude) of usable coord (where google has data).
  38. This function will attempt at most max_retries calls to map crunch to fetch
  39. candidate points, and will exit as soon as a suitable candidate is found.
  40. If no suitable candidate is found in this allotted number of retries, None is
  41. returned.
  42. This function calls the streetview metadata endpoint - there is no quota consumed.
  43. """
  44. mc_url = mapcrunch_url + ("?c=21" if only_america else "")
  45. for _ in range(max_retries):
  46. points_res = requests.get(mc_url).text
  47. points_js = json.loads(points_res.strip("while(1); "))
  48. if "c=" not in mc_url:
  49. mc_url += f"?c={points_js['country']}" # lock to the first country randomed
  50. for lat, lng in points_js["points"]:
  51. if point_has_streetview(lat, lng):
  52. return (lat, lng)
  53. def call_random_street_view(only_america=False):
  54. """
  55. Returns an array of (some number of) tuples, each being (latitude, longitude).
  56. All points will be valid streetview coordinates. There is no guarantee as to the
  57. length of this array (it may be empty), but it will never be None.
  58. This function calls the streetview metadata endpoint - there is no quota consumed.
  59. """
  60. rsv_js = requests.post(rsv_url, data={"country": "us" if only_america else "all"}).json()
  61. if not rsv_js["success"]:
  62. return []
  63. return [
  64. (point["lat"], point["lng"])
  65. for point in rsv_js["locations"]
  66. if point_has_streetview(point["lat"], point["lng"])
  67. ]
  68. def random_street_view_generator(only_america=False):
  69. """
  70. Returns a generator which will lazily use call_random_street_view to generate new
  71. street view points.
  72. The returned generator calls the streetview metadata endpoint - there is no quota consumed.
  73. """
  74. points = []
  75. while True:
  76. if len(points) == 0:
  77. points = call_random_street_view(only_america=only_america)
  78. else:
  79. yield points.pop()
  80. def urban_coord(max_retries=10, retries_per_point=30, max_dist_km=25, usa_chance=0.1):
  81. """
  82. Returns (latitude, longitude) of usable coord (where google has data) that is near
  83. a known urban center. Points will be at most max_dist_km kilometers away. This function will
  84. generate at most retries_per_point points around an urban center, and will try at most
  85. max_retries urban centers. If none of the generated points have street view data,
  86. this will return None. Otherwise, it will exit as soon as suitable point is found.
  87. This function calls the streetview metadata endpoint - there is no quota consumed.
  88. """
  89. src = urban_centers_usa if random.random() <= usa_chance else urban_centers_non_usa
  90. for _ in range(max_retries):
  91. # logic adapted from https://stackoverflow.com/a/7835325
  92. # start in a city
  93. (city_lat, city_lng) = random.choice(src)
  94. city_lat_rad = math.radians(city_lat)
  95. sin_lat = math.sin(city_lat_rad)
  96. cos_lat = math.cos(city_lat_rad)
  97. city_lng_rad = math.radians(city_lng)
  98. for _ in range(retries_per_point):
  99. # turn a random direction, and go random distance
  100. dist_km = random.random() * max_dist_km
  101. angle_rad = random.random() * 2 * math.pi
  102. d_over_radius = dist_km / mean_earth_radius_km
  103. sin_dor = math.sin(d_over_radius)
  104. cos_dor = math.cos(d_over_radius)
  105. pt_lat_rad = math.asin(sin_lat * cos_dor + cos_lat * sin_dor * math.cos(angle_rad))
  106. pt_lng_rad = city_lng_rad + math.atan2(math.sin(angle_rad) * sin_dor * cos_lat, cos_dor - sin_lat * math.sin(pt_lat_rad))
  107. pt_lat = math.degrees(pt_lat_rad)
  108. pt_lng = math.degrees(pt_lng_rad)
  109. if point_has_streetview(pt_lat, pt_lng):
  110. return (pt_lat, pt_lng)
  111. class PointSource:
  112. def __init__(self, stock_target):
  113. self.stock = collections.deque()
  114. self.stock_target = stock_target
  115. def _restock_impl(self, n):
  116. """
  117. Returns a list of new points to add to the stock.
  118. Implementations of this method should try to return at least n points for performance.
  119. """
  120. raise NotImplementedError("Subclasses must implement this")
  121. def restock(self, n=None):
  122. n = n if n is not None else self.stock_target - len(self.stock)
  123. if n > 0:
  124. pts = self._restock_impl(n)
  125. self.stock.extend(pts)
  126. diff = n - len(pts)
  127. if diff > 0:
  128. # if implementations of _restock_impl are well behaved, this will
  129. # never actually need to recurse to finish the job.
  130. self.restock(n=diff)
  131. def get_points(self, n=1):
  132. if len(self.stock) >= n:
  133. pts = []
  134. for _ in range(n):
  135. pts.append(self.stock.popleft())
  136. threading.Thread(target=self.restock).start()
  137. return pts
  138. self.restock(n=n)
  139. # this is safe as long as restock does actually add enough new points.
  140. # unless this object is being rapidly drained by another thread,
  141. # this will recur at most once.
  142. return self.get_points(n=n)
  143. class MapCrunchPointSource(PointSource):
  144. def __init__(self, stock_target=20, max_retries=100, only_america=False):
  145. super().__init__(stock_target=stock_target)
  146. self.max_retries = max_retries
  147. self.only_america = only_america
  148. def _restock_impl(self, n):
  149. points = []
  150. while len(points) < n:
  151. pt = generate_coord(
  152. max_retries=self.max_retries,
  153. only_america=self.only_america
  154. )
  155. if pt is not None:
  156. points.append(pt)
  157. class RSVPointSource(PointSource):
  158. def __init__(self, stock_target=20, only_america=False):
  159. super().__init__(stock_target=stock_target)
  160. self.only_america = only_america
  161. def _restock_impl(self, n):
  162. points = []
  163. while len(points) < n:
  164. points.extend(call_random_street_view(only_america=self.only_america))
  165. return points
  166. class UrbanPointSource(PointSource):
  167. def __init__(self, stock_target=20, max_retries=10, retries_per_point=30, max_dist_km=25, usa_chance=0.1):
  168. super().__init__(stock_target=stock_target)
  169. self.max_retries = max_retries
  170. self.retries_per_point = retries_per_point
  171. self.max_dist_km = max_dist_km
  172. self.usa_chance = usa_chance
  173. def _restock_impl(self, n):
  174. points = []
  175. while len(points) < n:
  176. pt = urban_coord(
  177. max_retries=self.max_retries,
  178. retries_per_point=self.retries_per_point,
  179. max_dist_km=self.max_dist_km,
  180. usa_chance=self.usa_chance
  181. )
  182. if pt is not None:
  183. points.append(pt)
  184. mean_earth_radius_km = (6378 + 6357) / 2
  185. # if you're more than 1/4 of the Earth's circumfrence away, you get 0
  186. max_dist_km = (math.pi * mean_earth_radius_km) / 2 # this is about 10,000 km
  187. # if you're within 1/16 of the Earth's circumfrence away, you get at least 1000 points
  188. quarter_of_max_km = max_dist_km / 4 # this is about 2,500 km
  189. # https://www.wolframalpha.com/input/?i=sqrt%28%28%28land+mass+of+earth%29+%2F+7%29%29+%2F+pi%29+in+kilometers
  190. # this is the average "radius" of a continent
  191. # within this radius, you get at least 2000 points
  192. avg_continental_rad_km = 1468.0
  193. # somewhat arbitrarily, if you're within 1000 km, you get at least 3000 points
  194. one_thousand = 1000.0
  195. # 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
  196. # this is the average "radius" of a country
  197. # within this radius, you get at least 4000 points
  198. avg_country_rad_km = 479.7
  199. # if you're within 150m, you get a perfect score of 5000
  200. min_dist_km = 0.15
  201. def score_within(raw_dist, min_dist, max_dist):
  202. """
  203. Gives a score between 0 and 1000, with 1000 for the min_dist and 0 for the max_dist
  204. """
  205. # scale the distance down to [0.0, 1.0], then multiply it by 2 for easing
  206. pd2 = 2 * (raw_dist - min_dist) / (max_dist - min_dist)
  207. # perform a quadratic ease-in-out on pd2
  208. r = (pd2 ** 2) / 2 if pd2 < 1 else 1 - (((2 - pd2) ** 2) / 2)
  209. # use this to ease between 1000 and 0
  210. return int(1000 * (1 - r))
  211. def score(target, guess):
  212. """
  213. Takes in two (latitude, longitude) pairs and produces an int score.
  214. Score is in the (inclusive) range [0, 5000]
  215. Higher scores are closer.
  216. Returns (score, distance in km)
  217. """
  218. dist_km = haversine.haversine(target, guess)
  219. if dist_km <= min_dist_km:
  220. point_score = 5000
  221. elif dist_km <= avg_country_rad_km:
  222. point_score = 4000 + score_within(dist_km, min_dist_km, avg_country_rad_km)
  223. elif dist_km <= one_thousand:
  224. point_score = 3000 + score_within(dist_km, avg_country_rad_km, one_thousand)
  225. elif dist_km <= avg_continental_rad_km:
  226. point_score = 2000 + score_within(dist_km, one_thousand, avg_continental_rad_km)
  227. elif dist_km <= quarter_of_max_km:
  228. point_score = 1000 + score_within(dist_km, avg_continental_rad_km, quarter_of_max_km)
  229. elif dist_km <= max_dist_km:
  230. point_score = score_within(dist_km, quarter_of_max_km, max_dist_km)
  231. else: # dist_km > max_dist_km
  232. point_score = 0
  233. return point_score, dist_km