lib.py 6.9 KB

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