import os

import requests

import pandas as pd

import time


# Google Maps API Key

GOOGLE_MAPS_API_KEY = “AIzaSyCard2PScx5ziEsMJ8MwysTeEUHh8f19iY”


# Create a directory to store images

IMAGE_DIR = “roof_images”

os.makedirs(IMAGE_DIR, exist_ok=True)


print(“The script is starting…”)  # Debugging print


# Function to format the address using Google Maps API

def format_address(address):

    print(f”Formatting address: {address}”)  # Debugging print

    time.sleep(1)  # Add a delay to avoid blocking

    url = f”https://maps.googleapis.com/maps/api/geocode/json?address={address}&key={GOOGLE_MAPS_API_KEY}”

    response = requests.get(url)

    if response.status_code == 200:

        data = response.json()

        if data[“status”] == “OK”:

            formatted = data[“results”][0][“formatted_address”]

            print(f”Formatted address: {formatted}”)  # Debugging print

            return formatted

    print(f”Could not format address: {address}”)  # Debugging print

    return address  # Return original if formatting fails


# Function to get latitude and longitude using Google Maps API

def get_lat_lon(address):

    print(f”Getting coordinates for: {address}”)  # Debugging print

    time.sleep(1)  # Add a delay to avoid blocking

    url = f”https://maps.googleapis.com/maps/api/geocode/json?address={address}&key={GOOGLE_MAPS_API_KEY}”

    response = requests.get(url)

    if response.status_code == 200:

        data = response.json()

        if data[“status”] == “OK”:

            location = data[“results”][0][“geometry”][“location”]

            print(f”Coordinates for {address}: {location[‘lat’]}, {location[‘lng’]}”)  # Debugging print

            return location[“lat”], location[“lng”]

    print(f”Could not get coordinates for: {address}”)  # Debugging print

    return None, None


# Function to fetch satellite image

def fetch_satellite_image(lat, lon, address):

    url = f”https://maps.googleapis.com/maps/api/staticmap?center={lat},{lon}&zoom=20&size=600×600&maptype=satellite&key={GOOGLE_MAPS_API_KEY}”

    print(f”Fetching image for {address} at {url}”)

    response = requests.get(url)

    if response.status_code == 200:

        image_path = os.path.join(IMAGE_DIR, f”{address.replace(‘ ‘, ‘_’)}.png”)

        with open(image_path, “wb”) as file:

            file.write(response.content)

        print(f”Saved image to {image_path}”)

        return image_path

    else:

        print(f”Failed to fetch image for {address} with status code {response.status_code}”)

    return None


# Load CSV with separate address columns and process it

def process_csv(csv_file):

    print(f”Reading CSV file: {csv_file}”)  # Debugging print

    df = pd.read_csv(csv_file)

    print(“CSV read successfully!”)  # Debugging print

    df[“Full Address”] = df[“Street Address”] + “, ” + df[“City”] + “, ” + df[“State”] + ” ” + df[“Zip Code”].astype(str)

    

    print(“Formatting addresses…”)  # Debugging print

    df[“Formatted Address”] = df[“Full Address”].apply(format_address)

    

    print(“Processing addresses for images…”)  # Debugging print

    for index, row in df.iterrows():

        address = row[“Formatted Address”]

        print(f”Processing: {address}”)  # Debugging print

        lat, lon = get_lat_lon(address)

        if lat and lon:

            print(f”Fetching image for {address}”)  # Debugging print

            image_path = fetch_satellite_image(lat, lon, address)

            df.at[index, “Image Path”] = image_path

        else:

            print(f”Skipping {address}, no coordinates found.”)  # Debugging print

    

    output_csv = “output_with_images.csv”

    df.to_csv(output_csv, index=False)

    print(f”Processing complete. Output saved to {output_csv}”)  # Debugging print


print(“Starting CSV processing…”)

process_csv(“kansas.csv”)


cd ~/Desktop/RoofDetection

python3 main.py

Add Your Heading Text Here

run the program

~/Desktop/RoofDetection/tf-env/bin/python3 label_images.py

Here’s a step-by-step prompt with everything that worked so far. You can follow this tomorrow to make sure you’re set up properly and ready to continue.

Project Setup & Running the Model (Roof Type Detection)


Follow these steps to ensure everything is working before you continue.


1. Open Terminal and Navigate to Your Project

cd ~/Desktop/RoofDetection

2. Activate the Virtual Environment

source tf-env/bin/activate

If this command fails with no such file or directory, ensure you’re in the correct directory before running it.


3. Check if TensorFlow is Installed and Recognized

python -c "import tensorflow as tf; print(tf.__version__)"

If it prints 2.16.2, TensorFlow is correctly installed. If you get an error, you might need to reinstall TensorFlow.


4. Check Installed Packages

pip list | grep tensorflow

This should return:

tensorflow                   2.16.2
tensorflow-io-gcs-filesystem 0.37.1
tensorflow-macos             2.16.2
tensorflow-metal             1.2.0

If any of these are missing, install them again using:

pip install --upgrade --force-reinstall tensorflow-macos tensorflow-metal

5. Ensure the Right Python Version is Used

which python3

It should return:

/Users/victorsantos/Desktop/RoofDetection/tf-env/bin/python3

If it returns something like /opt/homebrew/bin/python3.10, explicitly call Python from the virtual environment when running scripts:

~/Desktop/RoofDetection/tf-env/bin/python3 train_model.py

6. Run the Training Script

python3 train_model.py

If everything is working, the model should begin training. If you see an error related to shape mismatch like:

ValueError: Exception encountered when calling Sequential.call().
Input 0 of layer "dense" is incompatible...

This means there’s a mismatch between the expected and actual input shape, and we may need to update the model architecture.


7. If Python Script Doesn’t Recognize a Module


If you ever get an error like ModuleNotFoundError: No module named ‘some_package’, install it using:

pip install some_package

For example:

pip install pandas opencv-python pillow

Then, retry running the script.

If You Need to Restart Everything Tomorrow

1. Open Terminal

2. Run:

cd ~/Desktop/RoofDetection
source tf-env/bin/activate
python -c "import tensorflow as tf; print(tf.__version__)"


3. If TensorFlow is recognized, proceed with:

python3 train_model.py


4. If there’s an issue, check for missing dependencies:

pip list | grep tensorflow


5. If needed, reinstall dependencies:

pip install --upgrade --force-reinstall tensorflow-macos tensorflow-metal

This guide should get you back exactly where we left off. When you get back tomorrow, follow it step by step and let me know if you hit any issues! 🚀

Sign In

Register

Reset Password

Please enter your username or email address, you will receive a link to create a new password via email.