diff --git a/Birders_Guide_Installer.sh b/Birders_Guide_Installer.sh index 81b4f7a..5c06af3 100755 --- a/Birders_Guide_Installer.sh +++ b/Birders_Guide_Installer.sh @@ -141,6 +141,12 @@ DB_PWD=changeme ICE_PWD=changeme +#--------------------- BirdWeather Station Information -----------------------# +#_____________The variable below can be set to have your BirdNET-Pi____________# +#__________________also act as a BirdWeather listening station_________________# + +BIRDWEATHER_ID=${BIRDWEATHER_ID} + #----------------------- Web-hosting/Caddy File-server -----------------------# #________The four variables below can be set to enable internet access_________# #____________to your data,(e.g., extractions, raw data, live___________________# diff --git a/Birders_Guide_Installer_Configuration.txt b/Birders_Guide_Installer_Configuration.txt index b4aa1cd..1bbf484 100644 --- a/Birders_Guide_Installer_Configuration.txt +++ b/Birders_Guide_Installer_Configuration.txt @@ -1,18 +1,19 @@ # Birders Guide Installer Configuration File -########################################################################### +################################################################################ # Fill this out in order to install BirdNET-Lite # Follow the instructions for each section. -########################################################################### +################################################################################ # 1. To find your latitude and longitude, you can go to https://maps.google.com # 1a. Find the location on the map where you will be putting the BirdNET-Lite -# 1b. Right-click the location to view the latitude and longitude and click them to -# copy them to your clip-board. -# 2. Enter the latitude and longitude here. Be certain not to mix them up and -# only go to the thousandth's decimal place. The first number is the latitude, -# and the second is longitude. See the example below. +# 1b. Right-click the location to view the latitude and longitude and click +# them to copy them to your clip-board. +# 2. Enter the latitude and longitude here. Be certain not to mix them up. +# The first number is the latitude, and the second is longitude. See the +# example below. +# # Example: these coordinates would indicate the Eiffel Tower in Paris, France. # LATITUDE=48.858 # LONGITUDE=2.294 @@ -22,17 +23,17 @@ LONGITUDE= # 1. CADDY_PWD is the password you will use to access your live audio stream and # maintenance tools. You can set this to anything, but keep it alpha-numeric. -# You will probably also want to write this one down if you ever plan to listen -# to the live stream. -# 2. ICE_PWD is the password that IceCast2 will use to authenticate the stream source. -# You can set this to anything also, but keep it alpha-numeric. You will never use -# this again, so just set it to your favorite word. +# You will probably also want to write this one down if you ever plan to +# listen to the live stream. +# 2. ICE_PWD is the password that IceCast2 will use to authenticate the stream +# source.You can set this to anything also, but keep it alpha-numeric. You +# will never use this again, so just set it to your favorite word. CADDY_PWD= ICE_PWD= -# DB_PWD is the password that the system will use to access the database. Set this to -# anything you want. +# DB_PWD is the password that the system will use to access the database. Set +# this to anything you want. DB_PWD= @@ -49,3 +50,10 @@ PUSHED_APP_KEY= BIRDNETPI_URL= BIRDNETLOG_URL= EXTRACTIONLOG_URL= + +# If you would like to POST your BirdNET-Pi detections to +# https://app.birdweather.com, reach out to github:@timsterc for a unique and +# confidential BirdWeather ID. Place that here if you have one already. +# You can always add this later and the system will immediately start POSTing. + +BIRDWEATHER_ID= diff --git a/LICENSE b/LICENSE index 2820ecf..01cecb6 100644 --- a/LICENSE +++ b/LICENSE @@ -570,11 +570,11 @@ Caddy, and Adminer use the Apache License Version 2.0 limitations under the License. ============================================================================= -GoTTY use the MIT License +GoTTY and autoAP scripts use the MIT License ============================================================================= MIT License -BirdNET - Copyright (c) 2019 Stefan Kahl +autoAP - Copywrite (c) 2021 Benn GoTTY - Copyright (c) 2015-2017 Iwasaki Yudai Permission is hereby granted, free of charge, to any person obtaining a copy diff --git a/README.md b/README.md index 6420714..547a171 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ Check out birds from around the world * Web interface access to all data and logs * Automatic extraction of detected data (creating audio clips of detected bird sounds) * Spectrograms available for all extractions +* [BirdWeather](https://app.birdweather.com) integration (you will need to be issued a BirdWeather ID -- for now, request that from [@timsterc here](https://github.com/mcguirepr89/BirdNET-Pi/discussions/82)) * MariaDB integration * NoMachine remote desktop (for personal use only) * Live audio stream diff --git a/analyze.py b/analyze.py index 4177070..b90038f 100644 --- a/analyze.py +++ b/analyze.py @@ -1,3 +1,5 @@ +# BirdWeather edits by @timsterc +# Other edits by @CaiusX and @mcguirepr89 import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ['CUDA_VISIBLE_DEVICES'] = '' @@ -13,10 +15,17 @@ import librosa import numpy as np import math import time +from decimal import Decimal +import json ############################################################################### +import requests import mysql.connector -############################################################################### -from datetime import date, datetime +############################################################################### +import datetime +import pytz +from tzlocal import get_localzone +from pathlib import Path + def loadModel(): global INPUT_LAYER_INDEX @@ -196,6 +205,7 @@ def main(): parser.add_argument('--sensitivity', type=float, default=1.0, help='Detection sensitivity; Higher values result in higher sensitivity. Values in [0.5, 1.5]. Defaults to 1.0.') parser.add_argument('--min_conf', type=float, default=0.1, help='Minimum confidence threshold. Values in [0.01, 0.99]. Defaults to 0.1.') parser.add_argument('--custom_list', default='', help='Path to text file containing a list of species. Not used if not provided.') + parser.add_argument('--birdweather_id', default='99999', help='Private Station ID for BirdWeather.') args = parser.parse_args() @@ -208,75 +218,128 @@ def main(): else: WHITE_LIST = [] + birdweather_id = args.birdweather_id # Read audio data audioData = readAudioData(args.i, args.overlap) - # Process audio data and get detections - week = max(1, min(args.week, 48)) + # Get Date/Time from filename in case Pi gets behind + #now = datetime.now() + full_file_name = args.i + file_name = Path(full_file_name).stem + file_date = file_name.split('-birdnet-')[0] + file_time = file_name.split('-birdnet-')[1] + date_time_str = file_date + ' ' + file_time + date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S') + #print('Date:', date_time_obj.date()) + #print('Time:', date_time_obj.time()) + print('Date-time:', date_time_obj) + now = date_time_obj + current_date = now.strftime("%Y/%m/%d") + current_time = now.strftime("%H:%M:%S") + current_iso8601 = now.astimezone(get_localzone()).isoformat() + + week_number = int(now.strftime("%V")) + week = max(1, min(week_number, 48)) + sensitivity = max(0.5, min(1.0 - (args.sensitivity - 1.0), 1.5)) + + # Process audio data and get detections detections = analyzeAudioData(audioData, args.lat, args.lon, week, sensitivity, args.overlap, interpreter) # Write detections to output file min_conf = max(0.01, min(args.min_conf, 0.99)) writeResultsToFile(detections, min_conf, args.o) - now = datetime.now() ############################################################################### ############################################################################### - - + + soundscape_uploaded = False # Write detections to Database for i in detections: - print("\n", detections[i][0],"\n") + print("\n", detections[i][0],"\n") with open('BirdDB.txt', 'a') as rfile: - for d in detections: - print("\n", "Database Entry", "\n") - for entry in detections[d]: - if entry[1] >= min_conf and (entry[0] in WHITE_LIST or len(WHITE_LIST) == 0): - current_date = now.strftime("%Y/%m/%d") - current_time = now.strftime("%H:%M:%S") - rfile.write(str(current_date) + ';' + str(current_time) + ';' + entry[0].replace('_', ';') + ';' \ - + str(entry[1]) +";" + str(args.lat) + ';' + str(args.lon) + ';' + str(min_conf) + ';' + str(week) + ';' \ - + str(sensitivity) +';' + str(args.overlap) + '\n') + for d in detections: + print("\n", "Database Entry", "\n") + for entry in detections[d]: + if entry[1] >= min_conf and (entry[0] in WHITE_LIST or len(WHITE_LIST) == 0): + rfile.write(str(current_date) + ';' + str(current_time) + ';' + entry[0].replace('_', ';') + ';' \ + + str(entry[1]) +";" + str(args.lat) + ';' + str(args.lon) + ';' + str(min_conf) + ';' + str(week) + ';' \ + + str(sensitivity) +';' + str(args.overlap) + '\n') - def insert_variables_into_table(Date, Time, Sci_Name, Com_Name, Confidence, Lat, Lon, Cutoff, Week, Sens, Overlap): - try: - connection = mysql.connector.connect(host='localhost', - database='birds', - user='birder', - password='databasepassword') - cursor = connection.cursor() - mySql_insert_query = """INSERT INTO detections (Date, Time, Sci_Name, Com_Name, Confidence, Lat, Lon, Cutoff, Week, Sens, Overlap) - VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """ + def insert_variables_into_table(Date, Time, Sci_Name, Com_Name, Confidence, Lat, Lon, Cutoff, Week, Sens, Overlap): + try: + connection = mysql.connector.connect(host='localhost', + database='birds', + user='birder', + password='databasepassword') + cursor = connection.cursor() + mySql_insert_query = """INSERT INTO detections (Date, Time, Sci_Name, Com_Name, Confidence, Lat, Lon, Cutoff, Week, Sens, Overlap) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """ + + record = (Date, Time, Sci_Name, Com_Name, Confidence, Lat, Lon, Cutoff, Week, Sens, Overlap) + + cursor.execute(mySql_insert_query, record) + connection.commit() + print("Record inserted successfully into detections table") + + + except mysql.connector.Error as error: + print("Failed to insert record into detections table {}".format(error)) - record = (Date, Time, Sci_Name, Com_Name, Confidence, Lat, Lon, Cutoff, Week, Sens, Overlap) + finally: + if connection.is_connected(): + connection.close() + print("MySQL connection is closed") - cursor.execute(mySql_insert_query, record) - connection.commit() - print("Record inserted successfully into detections table") + species = entry[0] + sci_name,com_name = species.split('_') + insert_variables_into_table(str(current_date), str(current_time), sci_name, com_name, \ + str(entry[1]), str(args.lat), str(args.lon), str(min_conf), str(week), \ + str(args.sensitivity), str(args.overlap)) - - except mysql.connector.Error as error: - print("Failed to insert record into detections table {}".format(error)) - - finally: - if connection.is_connected(): - connection.close() - print("MySQL connection is closed") + print(str(current_date) + ';' + str(current_time) + ';' + entry[0].replace('_', ';') + ';' + str(entry[1]) +";" + str(args.lat) + ';' + str(args.lon) + ';' + str(min_conf) + ';' + str(week) + ';' + str(args.sensitivity) +';' + str(args.overlap) + '\n') - species = entry[0] - sci_name,com_name = species.split('_') - insert_variables_into_table(str(current_date), str(current_time), sci_name, com_name, \ - str(entry[1]), str(args.lat), str(args.lon), str(min_conf), str(week), \ - str(args.sensitivity), str(args.overlap)) + if birdweather_id != "99999": - print(str(current_date) + ';' + str(current_time) + ';' + entry[0].replace('_', ';') + ';' + str(entry[1]) +";" + str(args.lat) + ';' + str(args.lon) + ';' + str(min_conf) + ';' + str(week) + ';' + str(args.sensitivity) +';' + str(args.overlap) + '\n') + if soundscape_uploaded is False: + # POST soundscape to server + soundscape_url = "https://app.birdweather.com/api/v1/stations/" + birdweather_id + "/soundscapes" + "?timestamp=" + current_iso8601 - time.sleep(3) + with open(args.i, 'rb') as f: + wav_data = f.read() + response = requests.post(url=soundscape_url, data=wav_data, headers={'Content-Type': 'application/octet-stream'}) + print("Soundscape POST Response Status - ", response.status_code) + sdata = response.json() + soundscape_id = sdata['soundscape']['id'] + soundscape_uploaded = True - now = datetime.now() + # POST detection to server + detection_url = "https://app.birdweather.com/api/v1/stations/" + birdweather_id + "/detections" + start_time = d.split(';')[0] + end_time = d.split(';')[1] + post_begin = "{ " + now_p_start = now + datetime.timedelta(seconds=float(start_time)) + current_iso8601 = now_p_start.astimezone(get_localzone()).isoformat() + post_timestamp = "\"timestamp\": \"" + current_iso8601 + "\"," + post_lat = "\"lat\": " + str(args.lat) + "," + post_lon = "\"lon\": " + str(args.lon) + "," + post_soundscape_id = "\"soundscapeId\": " + str(soundscape_id) + "," + post_soundscape_start_time = "\"soundscapeStartTime\": " + start_time + "," + post_soundscape_end_time = "\"soundscapeEndTime\": " + end_time + "," + post_commonName = "\"commonName\": \"" + entry[0].split('_')[1] + "\"," + post_scientificName = "\"scientificName\": \"" + entry[0].split('_')[0] + "\"," + post_algorithm = "\"algorithm\": " + "\"alpha\"" + "," + post_confidence = "\"confidence\": " + str(entry[1]) + post_end = " }" + + post_json = post_begin + post_timestamp + post_lat + post_lon + post_soundscape_id + post_soundscape_start_time + post_soundscape_end_time + post_commonName + post_scientificName + post_algorithm + post_confidence + post_end + print(post_json) + response = requests.post(detection_url, json=json.loads(post_json)) + print("Detection POST Response Status - ", response.status_code) + + #time.sleep(3) ############################################################################### ############################################################################### diff --git a/birdnet.conf-defaults b/birdnet.conf-defaults index a20c045..751ff8b 100644 --- a/birdnet.conf-defaults +++ b/birdnet.conf-defaults @@ -53,6 +53,12 @@ DB_PWD=changeme ICE_PWD=changeme +#--------------------- BirdWeather Station Information -----------------------# +#_____________The variable below can be set to have your BirdNET-Pi____________# +#__________________also act as a BirdWeather listening station_________________# + +BIRDWEATHER_ID= + #----------------------- Web-hosting/Caddy File-server -----------------------# #________The four variables below can be set to enable internet access_________# #____________to your data,(e.g., extractions, raw data, live___________________# diff --git a/homepage/index.html b/homepage/index.html index 9d2922c..a1294b0 100644 --- a/homepage/index.html +++ b/homepage/index.html @@ -1,45 +1,42 @@ -
- -