Metadata-Version: 2.4
Name: spatialbound
Version: 0.0.8
Summary: Spatialbound API client library
Home-page: https://github.com/spatialbound/spatialbound_api
Author: Mohamed R. Ibrahim
Author-email: contact@spatialbound.com
Project-URL: Bug Tracker, https://github.com/spatialbound/spatialbound_api/issues
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: License :: Other/Proprietary License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.6
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: requests>=2.25.0
Requires-Dist: python-dotenv>=0.15.0
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license-file
Dynamic: project-url
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary


# SpatialBound Python SDK

A comprehensive Python SDK for accessing SpatialBound's spatial AI and analytics platform. This SDK provides easy access to geospatial data, routing, location analysis, weather information, and more.

## Installation

```bash
pip install spatialbound
```

## Quick Start

### Clean Import (Recommended)
```python
import spatialbound

# Initialize with your API key
api_key = "your-api-key-here"
spatialbound = spatialbound(api_key)

# Check login status
print("Login successful:", bool(spatialbound.login_response))
```

### Alternative Import Method
```python
# Direct import (original way)
from spatialbound import Spatialbound
spatialbound = Spatialbound("your-api-key")
```

## Features

- **Route Calculation** - Multi-modal routing with optimization options
- **Location Analysis** - Residential and commercial location suitability analysis
- **Geocoding** - Address and coordinate conversion
- **Weather & Air Quality** - Real-time environmental data
- **Points of Interest** - POI search and filtering
- **Map Generation** - Dynamic map creation and visualization
- **Video Analysis** - Upload and analyze video content
- **Chat AI** - Conversational AI for location-based queries
- **Live Events** - Real-time disaster and critical event monitoring

## Authentication

The SDK uses API key authentication. Get your API key from the SpatialBound platform.

```python
# Initialize the SDK (clean import)
import spatialbound
spatialbound = spatialbound("your-api-key-here")

# View login response
print("Login Response:", spatialbound.login_response)
```

## Route Calculation

Calculate routes between locations with various optimization options.

### Route using addresses:
```python
origin = "London Eye, London, UK"
destinations = [
    "British Museum, London, UK",
    "Tower of London, London, UK"
]

address_route = spatialbound.navigate(
    route_type="address",
    origin=origin,
    destinations=destinations,
    optimisation_type="shortest_path",
    mode_of_travel="walk"
)
print("Address route result:", address_route)
```

### Route using coordinates:
```python
origin_coords = [51.5007, -0.1246]  # London Eye coordinates
destination_coords = [
    [51.5194, -0.1269],  # British Museum coordinates
    [51.5081, -0.0759]   # Tower of London coordinates
]

coords_route = spatialbound.navigate(
    route_type="points",
    origin=origin_coords,
    destinations=destination_coords,
    optimisation_type="shortest_path",
    mode_of_travel="drive"
)
print("Coordinates route result:", coords_route)
```

### Get Available Route Options

```python
# Get available optimization types from server
optimization_types = spatialbound.get_optimization_types()
print("Available optimization types:", optimization_types)

# Get available modes of travel from server
modes_of_travel = spatialbound.get_modes_of_travel()
print("Available modes of travel:", modes_of_travel)
```

## Location Analysis

Analyze residential and commercial locations for suitability.

### Residential location analysis:
```python
residential_analysis = spatialbound.analyse_location(
    location_type="home",  
    address="221B Baker Street, London",
    transaction_type="rent",
    radius=400
)
print("Residential analysis:", residential_analysis)
```

### Commercial location analysis:
```python
commercial_analysis = spatialbound.analyse_location(
    location_type="business",
    postcode="EC2A 4BX",  # Shoreditch, London
    business_type="restaurant",
    transaction_type="rent",
    radius=500
)
print("Commercial analysis:", commercial_analysis)
```

### Location analysis using coordinates:
```python
coordinate_analysis = spatialbound.analyse_location(
    location_type="home",
    location={"lat": 51.5074, "lng": -0.1278},  # Central London coordinates
    transaction_type="buy"
)
print("Coordinate analysis:", coordinate_analysis)
```

## Geocoding

Convert between addresses and coordinates.

```python
# Convert address or postcode to coordinates
geocode_result = spatialbound.address_to_latlon("221B Baker Street, London")
print("Geocoding result:", geocode_result)

# Convert postcode to coordinates
postcode_result = spatialbound.address_to_latlon("SW1A 0AA")
print("Postcode result:", postcode_result)

# Convert coordinates to address
reverse_result = spatialbound.latlon_to_address(51.5074, -0.1278)
print("Reverse geocoding:", reverse_result)
```

## Points of Interest (POI)

Search for points of interest around specific locations.

```python
poi_result = spatialbound.fetch_pois_from_buffer(
    center_point=(-0.1278, 51.5074),  # (lon, lat) for London
    radius_meters=1000,
    poi_types=["restaurant", "cafe", "park"]
)
print("POI search result:", poi_result)
```

## Weather Data

Get current weather information for any location.

```python
# Get weather data for London
london_coords = (51.5074, -0.1278)
weather_data = spatialbound.get_weather(london_coords[0], london_coords[1])
print("Weather data:", weather_data)
```

## Air Quality Data

Retrieve air quality metrics for specific locations.

```python
# Get air quality data for New York
ny_coords = (40.7128, -74.0060)
air_quality = spatialbound.get_air_quality(ny_coords[0], ny_coords[1])
print("Air quality:", air_quality)
```

## Map Generation

Create dynamic maps with custom data layers.

```python
# Generate a map ID
map_id_response = spatialbound.generate_map_id()
map_id = map_id_response.get('map_id')
print(f"Generated map ID: {map_id}")

# Create a grid map for Central London
grid_map = spatialbound.create_map(
    map_id=f"{map_id}_grid",
    layers=["green_spaces", "water", "residential"],
    grid_or_vector="grid",
    grid_type="square",
    resolution=100,
    boundary_type="bbox",
    boundary_details="51.505,-0.155,51.520,-0.130",  # Central London bounding box
    operation="visualisation"
)
print("Grid map created:", grid_map.get('message'))
print("Number of features:", len(grid_map.get('data', {}).get('features', [])))
```

### Get available map layers:
```python
# Get available vector layer names
vector_layers = spatialbound.get_vector_layer_names()
print("Available vector layers:", vector_layers)

# Get available grid layer names
grid_layers = spatialbound.get_grid_layer_names()
print("Available grid layers:", grid_layers)
```

## Video Analysis

Upload and analyze video content for spatial insights.

```python
# Upload a video file
upload_response = spatialbound.upload_video("brixton.mp4")
video_url = upload_response.get("video_url")
print("Uploaded video URL:", video_url)

# Analyze the uploaded video
analysis = spatialbound.analyse_video(
    video_url=video_url,
    user_prompt="Count vehicles, identify weather conditions, detect road signs",
    fps=1  # Process 1 frame per second
)
print("Video analysis:", analysis)

# Search for specific content in a video
search_results = spatialbound.search_video(
    query="red cars at intersection",
    video_url=video_url,
    limit=5,
    search_mode="semantic"
)
print("Search results:", search_results)

# Find similarities to a specific timestamp
similar_moments = spatialbound.find_similarities(
    video_url=video_url,
    timestamp=45.2,  # 45.2 seconds into the video
    limit=3,
    threshold=0.8
)
print("Similar moments:", similar_moments)

# Find an image in a video
image_occurrences = spatialbound.find_image_in_video(
    image_path="image.png",
    video_url=video_url,
    threshold=0.75
)
print("Image occurrences:", image_occurrences)
```

## Chat AI

Ask questions about locations and get AI-powered responses.

```python
# Ask a question about routing
chat_response = spatialbound.chat("What's the best route from Kings Cross, London, UK to Buckingham Palace, London driving?")
print("Chat response:", chat_response)

# Ask about location information
location_question = spatialbound.chat("How to go to London Heathrow airport from Notting Hill, London, UK, driving?")
print("Location question:", location_question)
```

## Live Events

Monitor real-time disaster and critical events from around the world with account-based quota limits.

### Get Live Events

```python
# Get all events from the last hour
all_events = spatialbound.live_events(category="all", timeframe="1h")
print("All events (1h):", all_events)

# Get natural disasters from the last 2 hours
natural_disasters = spatialbound.live_events(category="natural_disaster", timeframe="2h")
print("Natural disasters (2h):", natural_disasters)

# Get human conflicts from the last 6 hours
human_conflicts = spatialbound.live_events(category="human_conflict", timeframe="6h")
print("Human conflicts (6h):", human_conflicts)

# Get health emergencies from the last 12 hours
health_emergencies = spatialbound.live_events(category="health_emergency", timeframe="12h")
print("Health emergencies (12h):", health_emergencies)

# Get infrastructure failures from the last 24 hours
infrastructure_failures = spatialbound.live_events(category="infrastructure_failure", timeframe="24h")
print("Infrastructure failures (24h):", infrastructure_failures)

# Get environmental crises from the last 48 hours (Pro/Ultra accounts only)
environmental_crises = spatialbound.live_events(category="environmental_crisis", timeframe="48h")
print("Environmental crises (48h):", environmental_crises)

# Get security threats from the last 72 hours (Ultra/Enterprise accounts only)
security_threats = spatialbound.live_events(category="security_threat", timeframe="72h")
print("Security threats (72h):", security_threats)
```

### Available Categories

```python
# Get available categories from the server
categories = spatialbound.get_live_events_categories()
print("Available categories:", categories)

# Get local category codes
available_categories = spatialbound.live_events_handler.get_available_categories()
print("Category codes:", available_categories)
```

### Available Timeframes

```python
# Get available timeframe options
available_timeframes = spatialbound.live_events_handler.get_available_timeframes()
print("Available timeframes:", available_timeframes)
```

### Account Limits

```python
# Check your account limits for live events
account_limits = spatialbound.live_events_handler.get_account_limits()
print("Account limits:", account_limits)
```

### Event Categories

- **all** - All event types
- **natural_disaster** - Earthquakes, floods, wildfires, etc.
- **human_conflict** - Wars, terrorism, civil unrest
- **health_emergency** - Disease outbreaks, epidemics
- **infrastructure_failure** - Power outages, transport disruptions
- **environmental_crisis** - Oil spills, chemical leaks
- **security_threat** - Cyber attacks, security incidents
- **other_critical** - Other critical incidents

### Timeframe Options

- **1h** - Last 1 hour (all accounts)
- **2h** - Last 2 hours (all accounts)
- **6h** - Last 6 hours (all accounts)
- **12h** - Last 12 hours (all accounts)
- **24h** - Last 24 hours (all accounts)
- **48h** - Last 48 hours (Pro/Ultra accounts)
- **72h** - Last 72 hours (Ultra/Enterprise accounts)

### Account-Based Limits

- **Free/Basic**: Up to 1 hour of data, 50-100 events
- **Pro**: Up to 24 hours of data, 500 events
- **Ultra/Enterprise**: Up to 168 hours (7 days) of data, 1000+ events

## Error Handling

The SDK provides comprehensive error handling:

```python
try:
    result = spatialbound.get_weather(51.5074, -0.1278)
    print("Success:", result)
except Exception as e:
    print("Error occurred:", str(e))
```

## Configuration

The SDK automatically handles configuration, but you can check the current settings:

```python
# Get version information
version_info = spatialbound.get_version()
print("SDK Version:", version_info)

# Get user location information (if available)
location_info = spatialbound.get_user_location_info()
print("Location info:", location_info)
```

## Best Practices

1. **API Key Security**: Never hardcode your API key. Use environment variables:
   ```python
   import os
   api_key = os.getenv("SPATIALBOUND_API_KEY")
   spatialbound = Spatialbound(api_key)
   ```

2. **Error Handling**: Always wrap API calls in try-catch blocks for production use.

3. **Rate Limiting**: The SDK handles rate limiting automatically, but be mindful of your usage.

4. **Data Validation**: Validate input data before making API calls.

## Support

For support and questions:
- Email: contact@spatialbound.com
- Documentation: https://wwww.spatialbound.com/doc

## License

SpatialBound License

This proprietary software is the sole property of the copyright holder. You are granted permission to use this software solely in accordance to the terms and conditions of SpatialBound.
Under no circumstances may this software be copied, distributed, modified, or reused for any commercial purposes without explicit prior written consent from the copyright holder.
All rights reserved, including but not limited to distribution, modification, and use for commercial benefit outside the terms and conditions of SpatialBound.
