lib.py 11 KB

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