DataSprint / setup_location.py
sujana05's picture
Upload folder using huggingface_hub
b4ce589 verified
#!/usr/bin/env python3
"""
Location Setup Script for Fleet Optimization Simulator
Easy setup for custom locations using Google Maps API
"""
import sys
import json
from location_config import LocationManager, initialize_location_manager
def setup_custom_location():
"""Interactive setup for custom location"""
print("🌍 Custom Location Setup for Fleet Optimization Simulator")
print("=" * 60)
# Initialize location manager
api_key = "AIzaSyBTA3eACtpCPR9DDi8EhOt1cI7Cy08Mkfg"
manager = LocationManager(api_key)
print("\nChoose setup method:")
print("1. πŸ“ Enter coordinates manually")
print("2. πŸ” Search by address/place name")
print("3. πŸ“‹ Use predefined location")
print("4. ❌ Exit")
choice = input("\nEnter your choice (1-4): ").strip()
if choice == '1':
setup_by_coordinates(manager)
elif choice == '2':
setup_by_address(manager)
elif choice == '3':
setup_predefined(manager)
elif choice == '4':
print("πŸ‘‹ Goodbye!")
return
else:
print("❌ Invalid choice")
return
def setup_by_coordinates(manager):
"""Setup location using coordinates"""
print("\nπŸ“ Manual Coordinate Setup")
print("-" * 30)
try:
name = input("Enter location name (e.g., 'San Francisco'): ").strip()
if not name:
print("❌ Location name is required")
return
lat = float(input("Enter latitude (e.g., 37.7749): "))
lng = float(input("Enter longitude (e.g., -122.4194): "))
# Validate coordinates
if not manager.validate_coordinates(lat, lng):
print("❌ Invalid coordinates. Latitude must be -90 to 90, longitude -180 to 180")
return
# Get location info
location_info = manager.reverse_geocode(lat, lng)
if location_info:
print(f"πŸ“ Location found: {location_info['formatted_address']}")
# Create location
bounds = manager.get_bounds_from_center(lat, lng, 10) # 10km radius
location = manager.create_custom_location(name, lat, lng, bounds)
if location:
print(f"βœ… Custom location created: {name}")
print(f" Center: {lat:.4f}, {lng:.4f}")
print(f" Hotspots: {len(location.hotspots)}")
# Save to file
filename = f"custom_location_{name.lower().replace(' ', '_')}.json"
manager.save_custom_location(location, filename)
print(f"πŸ’Ύ Location saved to: {filename}")
# Test the location
test_location(manager, location)
else:
print("❌ Failed to create location")
except ValueError:
print("❌ Invalid number format")
except Exception as e:
print(f"❌ Error: {e}")
def setup_by_address(manager):
"""Setup location using address search"""
print("\nπŸ” Address Search Setup")
print("-" * 25)
address = input("Enter address or place name (e.g., 'Times Square, New York'): ").strip()
if not address:
print("❌ Address is required")
return
print(f"πŸ” Searching for: {address}")
# Geocode the address
coords = manager.geocode(address)
if not coords:
print("❌ Address not found. Please try a different address.")
return
lat, lng = coords
print(f"πŸ“ Found coordinates: {lat:.4f}, {lng:.4f}")
# Get location info
location_info = manager.reverse_geocode(lat, lng)
if location_info:
print(f"πŸ“ Location: {location_info['formatted_address']}")
# Create location
name = input("Enter a name for this location: ").strip() or address
bounds = manager.get_bounds_from_center(lat, lng, 10)
location = manager.create_custom_location(name, lat, lng, bounds)
if location:
print(f"βœ… Custom location created: {name}")
print(f" Center: {lat:.4f}, {lng:.4f}")
print(f" Hotspots: {len(location.hotspots)}")
# Save to file
filename = f"custom_location_{name.lower().replace(' ', '_')}.json"
manager.save_custom_location(location, filename)
print(f"πŸ’Ύ Location saved to: {filename}")
# Test the location
test_location(manager, location)
else:
print("❌ Failed to create location")
def setup_predefined(manager):
"""Setup using predefined location"""
print("\nπŸ“‹ Predefined Location Setup")
print("-" * 30)
locations = manager.get_available_locations()
print("Available predefined locations:")
for i, loc in enumerate(locations, 1):
print(f" {i}. {loc}")
try:
choice = int(input(f"\nSelect location (1-{len(locations)}): "))
if 1 <= choice <= len(locations):
location_id = locations[choice - 1]
manager.set_location(location_id)
location = manager.current_location
print(f"βœ… Location set to: {location.name}")
print(f" Center: {location.center_lat:.4f}, {location.center_lng:.4f}")
print(f" Hotspots: {len(location.hotspots)}")
print(f" Country: {location.country}")
# Test the location
test_location(manager, location)
else:
print("❌ Invalid choice")
except ValueError:
print("❌ Invalid number format")
except Exception as e:
print(f"❌ Error: {e}")
def test_location(manager, location):
"""Test the location setup"""
print(f"\nπŸ§ͺ Testing location: {location.name}")
print("-" * 40)
# Test geocoding
print("πŸ” Testing geocoding...")
coords = manager.geocode(f"{location.name}, {location.country}")
if coords:
print(f" βœ… Geocoding works: {coords[0]:.4f}, {coords[1]:.4f}")
else:
print(" ⚠️ Geocoding test failed")
# Test reverse geocoding
print("πŸ“ Testing reverse geocoding...")
location_info = manager.reverse_geocode(location.center_lat, location.center_lng)
if location_info:
print(f" βœ… Reverse geocoding works: {location_info['formatted_address']}")
else:
print(" ⚠️ Reverse geocoding test failed")
# Show hotspots
print(f"🏒 Hotspots ({len(location.hotspots)}):")
for i, hotspot in enumerate(location.hotspots[:3], 1): # Show first 3
print(f" {i}. {hotspot['name']} ({hotspot['lat']:.4f}, {hotspot['lng']:.4f})")
if len(location.hotspots) > 3:
print(f" ... and {len(location.hotspots) - 3} more")
print(f"\nβœ… Location setup complete! You can now use '{location.name}' in the simulator.")
def show_usage_examples():
"""Show usage examples"""
print("\nπŸ“– Usage Examples")
print("-" * 20)
print("1. In the simulator interface:")
print(" - Select from dropdown: new_york, london, tokyo, singapore")
print(" - Or create custom location with coordinates")
print()
print("2. Programmatically:")
print(" from realtime_fleet_optimizer import RealTimeFleetOptimizer")
print(" optimizer = RealTimeFleetOptimizer('london')")
print(" # or")
print(" optimizer.set_location('tokyo')")
print()
print("3. Custom location:")
print(" optimizer.create_custom_location('Paris', 48.8566, 2.3522, bounds)")
def main():
"""Main function"""
if len(sys.argv) > 1 and sys.argv[1] == '--help':
show_usage_examples()
return
try:
setup_custom_location()
except KeyboardInterrupt:
print("\nπŸ‘‹ Setup cancelled by user")
except Exception as e:
print(f"❌ Unexpected error: {e}")
if __name__ == "__main__":
main()