random_street_view.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import random
  2. import logging
  3. import asyncio
  4. from .shared import aiohttp_client, point_has_streetview, reverse_geocode
  5. RSV_URL = "https://randomstreetview.com/data"
  6. VALID_COUNTRIES = ("ad", "au", "ar", "bd", "be", "bt", "bw",
  7. "br", "bg", "kh", "ca", "cl", "hr", "co",
  8. "cz", "dk", "ae", "ee", "fi", "fr", "de",
  9. "gr", "hu", "hk", "is", "id", "ie", "it",
  10. "il", "jp", "lv", "lt", "my", "mx", "nl",
  11. "nz", "no", "pe", "pl", "pt", "ro", "ru",
  12. "sg", "sk", "si", "za", "kr", "es", "sz",
  13. "se", "ch", "tw", "th", "ua", "gb", "us")
  14. logger = logging.getLogger(__name__)
  15. async def call_random_street_view(country_lock):
  16. """
  17. Returns an array of (some number of) tuples, each being (latitude, longitude).
  18. All points will be valid streetview coordinates, in the country indicated by
  19. country_lock. No size guarantee is given on the returned array - it could be empty.
  20. This function calls the streetview metadata endpoint - there is no quota consumed.
  21. """
  22. try:
  23. async with aiohttp_client.post(RSV_URL, data={"country": country_lock.lower()}) as response:
  24. rsv_js = await response.json(content_type=None)
  25. except:
  26. logger.exception("Failed RSV call")
  27. return []
  28. if not rsv_js["success"]:
  29. return []
  30. points = []
  31. async def add_point_if_valid(point):
  32. if await point_has_streetview(point["lat"], point["lng"]):
  33. country_code = await reverse_geocode(point["lat"], point["lng"])
  34. points.append((country_code or country_lock, point["lat"], point["lng"]))
  35. await asyncio.gather(*[add_point_if_valid(p) for p in rsv_js["locations"]])
  36. return points