Bird Detection Data Retrieval ScripT

Bird Detection Data Retrieval ScripT

This script is designed to fetch bird detection data from the specified API and save it in a structured CSV format. You can run this script by ensuring you have the required libraries (requests, csv) installed and providing the #correct API URL, initial cursor value, and CSV filename. Make sure to handle any authentication or API key requirements if necessary, and adjust the sleep duration between requests as needed to comply with the API's rate limits and #guidelines.

Bird Detection Data Retrieval ScripT CODE

import requestsimport csvimport time
# Print program explanation and instructions to the screenprint("\n")print("\n-------------------------------------------------------------------------------------------------------------------\n")print("Bird Detection Data Retrieval Script\n")print("This script is designed to retrieve bird detection data from the Bird Weather API and save it into a CSV file.")print("\nCreated by Douglas Fessler on 10/06/2023")print("- Fessler IT Consulting - ")print("Last modified: 10/06/2023     VERSION 1.2")print("\nNote: Please be patient while the script pulls data. It may take a while depending on the amount of data.")print("Ensure you have the necessary libraries (requests, csv) installed before running the script.")print("Make sure to customize the API URL, initial cursor value, and CSV filename as needed.")print("Handle any authentication or API key requirements if necessary.")print("Adjust the sleep duration between requests to comply with the API's rate limits and guidelines.")print("\n-------------------------------------------------------------------------------------------------------------------\n")
# ASCII art representation of a bird, aligned to the rightprint("          | o     |")print("          |       |")print("       _  | |  () |")print("      ( '=| |     |")print("     /  ( |     | |")print("    / / |/|   |   |")print("    |/\ |/|       |")print("       \\  | ()    |")print("        \\ |    |  |")print("          |    |  |")print("          |       |")print("          |  |    |")print("          |       |")print("For more documentation you can visit https://app.birdweather.com/api/v1#detections-detections-get")print("https://www.birdweather.com/")print("https://www.birdweather.com/birdnetpi")print("\n")print("MAKE SURE TO UPDATE CODE BELOW BY REPLACING **YOUR BIRDWEATHER ID GOES HERE** with your BirdWeather ID ")print("                This can be found on your BirdNETPi under Tools then Settings")print("\n-------------------------------------------------------------------------------------------------------------------\n")
# Define the API URL with the time period, limit, and initial cursor valueapi_url = 'https://app.birdweather.com/api/v1/stations/YOUR BIRDWEATHER ID GOES HERE/detections?period=all&limit=100'cursor = None  # Initial cursor value
# Specify the CSV file namecsv_filename = 'bird_detections.csv'
# Define the CSV headercsv_header = ['id', 'stationId', 'timestamp', 'lat', 'lon', 'confidence', 'probability', 'score', 'certainty', 'algorithm', 'species_id', 'species_commonName', 'species_scientificName', 'species_color', 'species_imageUrl', 'species_thumbnailUrl', 'soundscape_url', 'soundscape_startTime', 'soundscape_endTime']
# Open the CSV file for writingwith open(csv_filename, mode='w', newline='') as csv_file:    writer = csv.writer(csv_file)
    # Write the header row    writer.writerow(csv_header)
    while True:        # Make a GET request to the API with the current cursor        if cursor is not None:            api_url_with_cursor = f'{api_url}&cursor={cursor}'            response = requests.get(api_url_with_cursor)        else:            response = requests.get(api_url)
        # Check if the request was successful (status code 200)        if response.status_code == 200:            # Parse the response data            data = response.json()
            # Check if 'detections' key exists in the response data            if 'detections' in data:                detections = data['detections']
                # If there are no more detections, break out of the loop                if not detections:                    break
                # Iterate through the detections and write each detection as a row in the CSV file                for detection in detections:                    species = detection['species']                    soundscape = detection['soundscape']
                    row = [                        detection['id'],                        detection['stationId'],                        detection['timestamp'],                        detection['lat'],                        detection['lon'],                        detection['confidence'],                        detection['probability'],                        detection['score'],                        detection['certainty'],                        detection['algorithm'],                        species['id'],                        species['commonName'],                        species['scientificName'],                        species['color'],                        species['imageUrl'],                        species['thumbnailUrl'],                        soundscape['url'],                        soundscape['startTime'],                        soundscape['endTime']                    ]
                    writer.writerow(row)
                # Update the cursor for the next request                cursor = data.get('nextCursor')
                # Sleep for a few seconds to avoid overloading the server                time.sleep(2)            else:                print('No detections found in the response.')                break        else:            # Handle errors            print(f"Request failed with status code {response.status_code}")            print(response.text)
print(f'All data has been written to {csv_filename}')

Description OF

Bird Detection Data Retrieval ScripT


1. It starts by printing an explanation and instructions for using the script, providing information about the script's purpose, author, version, and usage guidelines.

2. It displays an ASCII art representation of a bird for visual appeal.

3. It provides links for more documentation and resources related to Bird Weather and BirdNETPi.

4. It instructs the user to replace the placeholder 'YOUR BIRDWEATHER ID GOES HERE' with their actual BirdWeather ID.

5. It defines the API URL with parameters like the time period, limit, and initial cursor value.

6. It specifies the CSV file name and header, which includes the column names for the data to be retrieved.

7. It opens the CSV file for writing and writes the header row.

8. It enters a loop that makes GET requests to the Bird Weather API to retrieve bird detection data.

9. It checks if the request was successful (status code 200), parses the response data, and extracts information about detected bird species and soundscapes.

10. It iterates through the detections and writes each detection as a row in the CSV file.

11. It updates the cursor for the next request, sleeps for 2 seconds to avoid overloading the server, and continues the loop until all data is retrieved.

12. If there are no more detections in the response, the script breaks out of the loop.

13. If there is an error in the request, it handles the error and prints the status code and response text.

14. Finally, the script prints a message indicating that all data has been written to the CSV file.

Overall, this script is designed for retrieving bird detection data from the Bird Weather API in a structured manner and saving it to a CSV file. Users need to provide their BirdWeather ID and may need to customize the script further to match their specific requirements, such as adjusting the sleep duration, handling authentication, or modifying the API URL for different queries.

I would like to kindly request that if you find my code useful and decide to use it, I would greatly appreciate it if you could do so under an open and free license. Additionally, I kindly ask that proper attribution be provided to acknowledge the original authorship. 

Donate

If you've enjoyed exploring my projects and want to see more amazing creations, your support can make a big difference! By contributing, you're helping me continue to innovate and bring even more exciting projects to life.  Don't forget to like, subscribe, and follow for updates on the latest developments. Thank you for being a part of this journey! 

Click here to make a difference with your donation today!