# House Damage Assessment

### The Scenario

We are insurance agents at **Hometown Insurance Company**. We have received a claim from a business owner whose business was damaged in a recent severe storm.

**The Claim:**

* **Address**: 1337 Bayard Ave, St Louis, MO
* **Claim**: Exterior damage from tornado - need immediate assessment

### The Problem

We need to know:

* How bad is the damage?

Normally, this would require sending an adjuster to visit the property. But with aerial imagery, we can assess the damage remotely before scheduling an on-site visit.

### The Solution

Instead, we'll use **aerial imagery** to assess the damage remotely:

1. **Get "before" images** - how the building looked before the storm
2. **Get "after" images** - recent imagery showing current conditions
3. **Compare the images** - identify what's damaged
4. **Make an informed assessment** - determine if immediate action is needed

### The Process

Using aerial imagery, we can objectively determine:

* **Is the damage real?** (verify the claim)
* **How severe is it?** (cosmetic vs. major structural)
* **Is immediate action needed?** (emergency repairs, safety concerns)
* **Next steps?** (prioritize adjuster visit, approve emergency funds)

This remote assessment helps us make informed decisions about claim handling and resource allocation.

## Code Walkthrough

Let's begin setting up the code by importing key libraries and configuring our environment variables. This code imports the necessary Python libraries for API requests, geocoding, and image display, then establishes our connection to the Spexi Image API using authentication headers. We're targeting a single address for our damage assessment analysis.

```python
import requests
import json
from geopy.geocoders import Nominatim
import os
from IPython.display import display, Image

# Configuration
API_KEY = "your-api-key"
BASE_URL = "https://api-world.spexi.com/api/ogc/v1"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

# Target addresses
addresses = [
    "1337 Bayard Ave, St Louis, MO"
]
```

### Retrieve collection ID

Now let's retrieve the collection ID of the imagery collection we have access to. This code queries the Spexi API to retrieve all accessible collections, displays the results so we can see what's available, then automatically selects the first collection for our analysis.

```python
print("🔍 Discovering available collections...")
collections_response = requests.get(f"{BASE_URL}/collections", headers=HEADERS)
collections = collections_response.json()
collection_id = collections['collections'][0]['id']  # Use first available collection
```

### Geocode address

Next, we'll convert our street address into the geographic coordinates needed for the API query. This code uses OpenStreetMap's free geocoding service to transform "4769 Dr Martin Luther King Dr, St. Louis, MO" into precise latitude and longitude coordinates, then stores those coordinates for use in our imagery requests.

```python
print("\n📍 Geocoding addresses...")
geolocator = Nominatim(user_agent="spexi_demo")
locations = []

for address in addresses:
    location = geolocator.geocode(address)
    if location:
        locations.append({
            'address': address,
            'lat': location.latitude,
            'lon': location.longitude
        })
        print(f"✓ {address} → {location.latitude:.6f}, {location.longitude:.6f}")
```

### Query before and after images

Next, we'll retrieve the before and after aerial imagery for our damage assessment. This code queries the same location twice - once for images captured before May 16th (pre-storm condition) and once for images captured after May 16th (post-storm damage), allowing us to compare the property's condition and identify any visible damage from the severe weather event.

```python
print(f"\n🖼️ Querying images from collection: {collection_id}")

for location in locations:
    # Get BEFORE images (before May 16th)
    print(f"\n📅 Getting BEFORE images for {location['address']}...")
    before_params = {
        'p': f"{location['lon']},{location['lat']}",
        'focused': 'focused',
        'captured_at': '2025-01-01,2025-05-16',
    }
    
    before_response = requests.get(
        f"{BASE_URL}/collections/{collection_id}/items",
        headers=HEADERS,
        params=before_params
    )
    
    before_images = before_response.json().get('features', [])
    print(f"Found {len(before_images)} images before the storm")
    
    # Get AFTER images (after May 16th) 
    print(f"\n📅 Getting AFTER images for {location['address']}...")
    after_params = {
        'p': f"{location['lon']},{location['lat']}",
        'focused': 'focused', 
        'captured_at': '2025-05-16,2025-12-31',
    }
    
    after_response = requests.get(
        f"{BASE_URL}/collections/{collection_id}/items",
        headers=HEADERS,
        params=after_params
    )
    
    after_images = after_response.json().get('features', [])
    print(f"Found {len(after_images)} images after the storm")
```

### Display images

Lastly, let's inspect the before and after images side-by-side for easy visual comparison. The aerial imagery clearly shows the extent of roof damage and validates the homeowner's claim, allowing the insurance agent to quickly determine next steps without requiring an immediate site visit.

```python
# Display before and after images for comparison
print(f"\n🏠 DAMAGE ASSESSMENT: {location['address']}")
print("\n📅 BEFORE STORM (Pre-May 16th):")
for i, image_data in enumerate(before_images[:1]):
    for link in image_data.get('links', []):
        if link.get('title') == 'Raw Image':
            print(f"Before Image #{i+1}:")
            display(Image(url=link['href']))
            break

print("\n📅 AFTER STORM (Post-May 16th):")
for i, image_data in enumerate(after_images[:1/]):
    for link in image_data.get('links', []):
        if link.get('title') == 'Raw Image':
            print(f"After Image #{i+1}:")
            display(Image(url=link['href']))
            break
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://learn.spexi.com/api-reference/code-examples/house-damage-assessment.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
