Advertisement
aum7

updateatlas.py

Jun 16th, 2024
610
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.87 KB | None | 0 0
  1. import sqlite3
  2. import requests
  3. import time
  4. import logging
  5.  
  6. # Configure logging
  7. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  8.  
  9. def get_cities(db_path):
  10.     conn = sqlite3.connect(db_path)
  11.     cur = conn.cursor()
  12.     cur.execute("SELECT _idx, name, latitude, longitude FROM GeoNames WHERE elevation = 0 ORDER BY _idx")
  13. #    cur.execute(
  14. #        "SELECT _idx, name, latitude, longitude FROM GeoNames WHERE elevation IS NULL ORDER BY _idx"
  15. #    )
  16. #    cur.execute(
  17. #        "SELECT _idx, name, latitude, longitude, timezone FROM GeoNames WHERE elevation IS NULL ORDER BY _idx"
  18. #    )
  19.     cities = cur.fetchall()
  20.     conn.close()
  21.     return cities
  22.  
  23. def get_elevations(locations):
  24.     locations_str = '|'.join([f"{lat},{lon}" for lat, lon in locations])
  25.     url = f"https://api.open-elevation.com/api/v1/lookup?locations={locations_str}"
  26.     logging.info(f"Requesting elevations from API: {url}")  # Add this line for logging
  27.     try:
  28.         response = requests.get(url, timeout=10)
  29.         response.raise_for_status()  # Raise an error for bad status codes
  30.         elevations = response.json()['results']
  31.         return [elevation['elevation'] for elevation in elevations]
  32.     except requests.exceptions.RequestException as e:
  33.         logging.error(f"Error fetching elevations: {e}")
  34.         return [None] * len(locations)
  35.  
  36.  
  37. def update_elevation(db_path, city_id, elevation):
  38.     try:
  39.         conn = sqlite3.connect(db_path)
  40.         cur = conn.cursor()
  41.         cur.execute("UPDATE GeoNames SET elevation = ? WHERE _idx = ?", (elevation, city_id))
  42.         conn.commit()
  43.     except sqlite3.Error as e:
  44.         logging.error(f"Error updating database: {e}")
  45.     finally:
  46.         conn.close()
  47.  
  48. def save_cities_to_file(cities, filename):
  49.     with open(filename, 'w') as file:
  50.         for city in cities:
  51.             file.write(f"{city[0]}, {city[1]}, {city[2]}, {city[3]}\n")
  52.  
  53. def main(db_path):
  54.     cities = get_cities(db_path)
  55.     save_cities_to_file(cities, 'cities.txt')  # Save cities to a text file
  56.     batch_size = 1000  # Adjust batch size according to your needs and API limitations
  57.     for i in range(0, len(cities), batch_size):
  58.         batch = cities[i:i+batch_size]
  59.         locations = [(lat, lon) for _, _, lat, lon in batch]
  60.         elevations = get_elevations(locations)
  61.         for (city_id, name, lat, lon), elevation in zip(batch, elevations):
  62.             if elevation is not None:
  63.                 update_elevation(db_path, city_id, elevation)
  64.                 logging.info(f"Updated city: {name} (ID: {city_id}) with elevation: {elevation} meters")
  65.             else:
  66.                 logging.warning(f"Failed to get elevation for city: {name} (ID: {city_id})")
  67.         time.sleep(1)  # To avoid hitting the API rate limit
  68.  
  69. if __name__ == "__main__":
  70.     db_path = "/media/.../atlas.db.bu/atlas.db"
  71.     main(db_path)
  72.  
Tags: update atlas
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement