diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..1fd4893 --- /dev/null +++ b/.flake8 @@ -0,0 +1,2 @@ +[flake8] +max-line-length = 160 diff --git a/.github/workflows/python-ci.yml b/.github/workflows/python-ci.yml index e918979..84c62cb 100644 --- a/.github/workflows/python-ci.yml +++ b/.github/workflows/python-ci.yml @@ -13,9 +13,6 @@ jobs: steps: - name: Checkout uses: actions/checkout@v3 - with: - # This is a bit heavy handed, but we need `origin/main` to get a ref to diff against - fetch-depth: 0 - name: Setup Python uses: actions/setup-python@v3 @@ -29,5 +26,4 @@ jobs: - name: Run Flake8 Lint run: | - DIFF="$(git --no-pager diff -u $(git merge-base HEAD origin/main) -- '**/*.py')" - echo "$DIFF" | flake8 --diff + flake8 diff --git a/README.md b/README.md index f23451c..10b6400 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ Currently listening in these countries . . . that I know of . . . * 24/7 recording and BirdNET-Lite analysis * Automatic extraction of detected data (creating audio clips of detected bird sounds) * Spectrograms available for all extractions -* Live audio stream +* Live audio stream & spectrogram * [BirdWeather](https://app.birdweather.com) integration -- you can request a BirdWeather ID from BirdNET-Pi's "Tools" > "Settings" page * Web interface access to all data and logs provided by [Caddy](https://caddyserver.com) * Web Terminal @@ -110,6 +110,7 @@ I hope that if you find BirdNET-Pi has been worth your time, you will share your - [Marie Lelouche's Out of Spaces](https://www.lestanneries.fr/exposition/marie-lelouche-out-of-spaces/) using BirdNET-Pi in post-sculpture VR! [Press Kit](https://github.com/mcguirepr89/BirdNET-Pi-assets/blob/main/dp_out_of_spaces_marie_lelouche_digital_05_01_22.pdf) - [Research on noded BirdNET-Pi networks for farming](https://github.com/mcguirepr89/BirdNET-Pi-assets/blob/main/G23_Report_ModelBasedSysEngineering_FarmMarkBirdDetector_V1__Copy_.pdf) +- [PixCams Build Guide](https://pixcams.com/building-a-birdnet-pi-real-time-acoustic-bird-id-station/) - [Core-Electronics](https://core-electronics.com.au/projects/bird-calls-raspberry-pi) Build Article diff --git a/homepage/style.css b/homepage/style.css index 3319185..4145aec 100644 --- a/homepage/style.css +++ b/homepage/style.css @@ -551,9 +551,11 @@ button:hover { width:25px !important; height:25px !important; } + .relative { position:relative; } + .sortbutton { margin-top:10px; font-size:x-large; @@ -561,6 +563,7 @@ button:hover { padding:5px; box-shadow: 0px 0px 5px 2px rgba(0, 0, 0, 0.10); } + button.legacyview { color:gray; margin:5px; @@ -573,6 +576,7 @@ button.legacyview { transition:box-shadow 280ms cubic-bezier(0.4, 0, 0.2, 1); box-shadow:0px 3px 1px -2px rgb(0 0 0 / 20%), 0px 2px 2px 0px rgb(0 0 0 / 14%), 0px 1px 5px 0px rgb(0 0 0 / 12%); } + button.legacyview:hover { box-shadow:0px 2px 4px -1px rgb(0 0 0 / 20%), 0px 4px 5px 0px rgb(0 0 0 / 14%), 0px 1px 10px 0px rgb(0 0 0 / 12%); } @@ -586,12 +590,15 @@ button.loadmore { box-shadow:0px 3px 1px -2px rgb(0 0 0 / 20%), 0px 2px 2px 0px rgb(0 0 0 / 14%), 0px 1px 5px 0px rgb(0 0 0 / 12%); } + button.loadmore:hover { box-shadow:0px 2px 4px -1px rgb(0 0 0 / 20%), 0px 4px 5px 0px rgb(0 0 0 / 14%), 0px 1px 10px 0px rgb(0 0 0 / 12%); } + #searchterm { transition:box-shadow 280ms cubic-bezier(0.4, 0, 0.2, 1); } + #searchterm:hover { box-shadow:0px 2px 4px -1px rgb(0 0 0 / 20%), 0px 4px 5px 0px rgb(0 0 0 / 14%), 0px 1px 10px 0px rgb(0 0 0 / 12%); } @@ -599,29 +606,36 @@ button.loadmore:hover { tr { background-color:#9fe29b; } + .history.centered form { display:flex; justify-content: center; } + .history.centered input { margin-right:5px; border:0px; } + .centered form#views button { box-shadow: 0px 0px 5px 2px rgba(0, 0, 0, 0.10); margin:2px; transition:box-shadow 280ms cubic-bezier(0.4, 0, 0.2, 1); box-shadow:0px 3px 1px -2px rgb(0 0 0 / 20%), 0px 2px 2px 0px rgb(0 0 0 / 14%), 0px 1px 5px 0px rgb(0 0 0 / 12%); } + .centered form#views button:hover { box-shadow:0px 2px 4px -1px rgb(0 0 0 / 20%), 0px 4px 5px 0px rgb(0 0 0 / 14%), 0px 1px 10px 0px rgb(0 0 0 / 12%); } + input { box-shadow: 0px 0px 17px 1px rgba(0, 0, 0, 0.10); } + dialog { border:none; } + dialog::backdrop { background: repeating-linear-gradient( 30deg, @@ -632,12 +646,14 @@ dialog::backdrop { ); backdrop-filter: blur(1px) } + .centered_image_container { font-size:19px !important; display:inline-block; position:relative; margin-bottom:3px; } + .centered_image_container img.img1 { transition:box-shadow 280ms cubic-bezier(0.4, 0, 0.2, 1); box-shadow:0px 3px 1px -2px rgb(0 0 0 / 20%), 0px 2px 2px 0px rgb(0 0 0 / 14%), 0px 1px 5px 0px rgb(0 0 0 / 12%); @@ -649,19 +665,27 @@ dialog::backdrop { border-radius: 5px; width:unset; } + .centered_image_container img.img1:hover{ opacity:0.8; box-shadow:0px 2px 4px -1px rgb(0 0 0 / 20%), 0px 4px 5px 0px rgb(0 0 0 / 14%), 0px 1px 10px 0px rgb(0 0 0 / 12%); } + .centered_image_container * { font-size:19px !important; } + .centered_image_container form { margin-bottom:0px; } + .brbanner { padding:15px; background-color:rgb(159, 226, 155); text-align:center; font-size:large; +} + +#gain.centered { + margin-bottom:10px; } \ No newline at end of file diff --git a/homepage/views.php b/homepage/views.php index 33f4621..49c0537 100644 --- a/homepage/views.php +++ b/homepage/views.php @@ -12,6 +12,9 @@ body::-webkit-scrollbar {
+ @@ -24,9 +27,6 @@ body::-webkit-scrollbar { - diff --git a/scripts/analyze.py b/scripts/analyze.py index 4f36e80..21fe905 100755 --- a/scripts/analyze.py +++ b/scripts/analyze.py @@ -11,6 +11,7 @@ ADDR = (SERVER, PORT) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDR) + def send(msg): message = msg.encode(FORMAT) msg_length = len(message) @@ -20,6 +21,7 @@ def send(msg): client.send(message) print(client.recv(2048).decode(FORMAT)) + def main(): global INCLUDE_LIST @@ -28,16 +30,52 @@ def main(): # Parse passed arguments parser = argparse.ArgumentParser() parser.add_argument('--i', help='Path to input file.') - parser.add_argument('--o', default='result.csv', help='Path to output file. Defaults to result.csv.') - parser.add_argument('--lat', type=float, default=-1, help='Recording location latitude. Set -1 to ignore.') - parser.add_argument('--lon', type=float, default=-1, help='Recording location longitude. Set -1 to ignore.') - parser.add_argument('--week', type=int, default=-1, help='Week of the year when the recording was made. Values in [1, 48] (4 weeks per month). Set -1 to ignore.') - parser.add_argument('--overlap', type=float, default=0.0, help='Overlap in seconds between extracted spectrograms. Values in [0.0, 2.9]. Defaults tp 0.0.') - 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('--include_list', default='null', help='Path to text file containing a list of included species. Not used if not provided.') - parser.add_argument('--exclude_list', default='null', help='Path to text file containing a list of excluded species. Not used if not provided.') - parser.add_argument('--birdweather_id', default='99999', help='Private Station ID for BirdWeather.') + parser.add_argument( + '--o', + default='result.csv', + help='Path to output file. Defaults to result.csv.') + parser.add_argument( + '--lat', + type=float, + default=-1, + help='Recording location latitude. Set -1 to ignore.') + parser.add_argument( + '--lon', + type=float, + default=-1, + help='Recording location longitude. Set -1 to ignore.') + parser.add_argument( + '--week', + type=int, + default=-1, + help='Week of the year when the recording was made. Values in [1, 48] (4 weeks per month). Set -1 to ignore.') + parser.add_argument( + '--overlap', + type=float, + default=0.0, + help='Overlap in seconds between extracted spectrograms. Values in [0.0, 2.9]. Defaults tp 0.0.') + 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( + '--include_list', + default='null', + help='Path to text file containing a list of included species. Not used if not provided.') + parser.add_argument( + '--exclude_list', + default='null', + help='Path to text file containing a list of excluded species. Not used if not provided.') + parser.add_argument( + '--birdweather_id', + default='99999', + help='Private Station ID for BirdWeather.') args = parser.parse_args() @@ -64,14 +102,15 @@ def main(): sockParams += 'lat=' + str(args.lat) + '||' if args.lon: sockParams += 'lon=' + str(args.lon) + '||' - + send(sockParams) send(DISCONNECT_MESSAGE) - #time.sleep(3) + # time.sleep(3) + +############################################################################### +############################################################################### -############################################################################### -############################################################################### if __name__ == '__main__': @@ -79,4 +118,6 @@ if __name__ == '__main__': # Example calls # python3 analyze.py --i 'example/XC558716 - Soundscape.mp3' --lat 35.4244 --lon -120.7463 --week 18 - # python3 analyze.py --i 'example/XC563936 - Soundscape.mp3' --lat 47.6766 --lon -122.294 --week 11 --overlap 1.5 --min_conf 0.25 --sensitivity 1.25 --custom_list 'example/custom_species_list.txt' + # python3 analyze.py --i 'example/XC563936 - Soundscape.mp3' --lat 47.6766 + # --lon -122.294 --week 11 --overlap 1.5 --min_conf 0.25 --sensitivity + # 1.25 --custom_list 'example/custom_species_list.txt' diff --git a/scripts/daily_plot.py b/scripts/daily_plot.py index a20e8d2..59747f9 100755 --- a/scripts/daily_plot.py +++ b/scripts/daily_plot.py @@ -1,6 +1,5 @@ import sqlite3 import os -import configparser import pandas as pd import seaborn as sns import matplotlib.pyplot as plt @@ -18,84 +17,95 @@ cursor.execute('SELECT * FROM detections WHERE Date = DATE(\'now\', \'localtime\ table_rows = cursor.fetchall() -#df=pd.DataFrame(table_rows) +# df=pd.DataFrame(table_rows) -#Convert Date and Time Fields to Panda's format -df['Date']=pd.to_datetime(df['Date']) -df['Time']=pd.to_datetime(df['Time'], unit='ns') +# Convert Date and Time Fields to Panda's format +df['Date'] = pd.to_datetime(df['Date']) +df['Time'] = pd.to_datetime(df['Time'], unit='ns') -#Add round hours to dataframe +# Add round hours to dataframe df['Hour of Day'] = [r.hour for r in df.Time] -#Create separate dataframes for separate locations -df_plt=df #Default to use the whole Dbase +# Create separate dataframes for separate locations +df_plt = df # Default to use the whole Dbase # Add every font at the specified location -font_dir = [userDir+'/BirdNET-Pi/homepage/static'] +font_dir = [userDir + '/BirdNET-Pi/homepage/static'] for font in font_manager.findSystemFonts(font_dir): font_manager.fontManager.addfont(font) # Set font family globally rcParams['font.family'] = 'Roboto Flex' -#Get todays readings +# Get todays readings now = datetime.now() -df_plt_today = df_plt[df_plt['Date']==now.strftime("%Y-%m-%d")] +df_plt_today = df_plt[df_plt['Date'] == now.strftime("%Y-%m-%d")] -#Set number of species to report -readings=10 +# Set number of species to report +readings = 10 plt_top10_today = (df_plt_today['Com_Name'].value_counts()[:readings]) df_plt_top10_today = df_plt_today[df_plt_today.Com_Name.isin(plt_top10_today.index)] -#Set Palette for graphics +# Set Palette for graphics pal = "Greens" -#Set up plot axes and titles -f, axs = plt.subplots(1, 2, figsize = (10, 4), gridspec_kw=dict(width_ratios=[3, 6]), facecolor='#77C487') +# Set up plot axes and titles +f, axs = plt.subplots(1, 2, figsize=(10, 4), gridspec_kw=dict(width_ratios=[3, 6]), facecolor='#77C487') plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0, hspace=0) -#generate y-axis order for all figures based on frequency +# generate y-axis order for all figures based on frequency freq_order = pd.value_counts(df_plt_top10_today['Com_Name']).iloc[:readings].index -#make color for max confidence --> this groups by name and calculates max conf +# make color for max confidence --> this groups by name and calculates max conf confmax = df_plt_top10_today.groupby('Com_Name')['Confidence'].max() -#reorder confmax to detection frequency order +# reorder confmax to detection frequency order confmax = confmax.reindex(freq_order) # norm values for color palette norm = plt.Normalize(confmax.values.min(), confmax.values.max()) colors = plt.cm.Greens(norm(confmax)) -#Generate frequency plot -plot=sns.countplot(y='Com_Name', data = df_plt_top10_today, palette = colors, order=freq_order, ax=axs[0]) +# Generate frequency plot +plot = sns.countplot(y='Com_Name', data=df_plt_top10_today, palette=colors, order=freq_order, ax=axs[0]) - - -#Try plot grid lines between bars - problem at the moment plots grid lines on bars - want between bars -z=plot.get_ymajorticklabels() -plot.set_yticklabels(['\n'.join(textwrap.wrap(ticklabel.get_text(),15)) for ticklabel in plot.get_yticklabels()], fontsize = 10) +# Try plot grid lines between bars - problem at the moment plots grid lines on bars - want between bars +z = plot.get_ymajorticklabels() +plot.set_yticklabels(['\n'.join(textwrap.wrap(ticklabel.get_text(), 15)) for ticklabel in plot.get_yticklabels()], fontsize=10) plot.set(ylabel=None) plot.set(xlabel="Detections") -#Generate crosstab matrix for heatmap plot +# Generate crosstab matrix for heatmap plot -heat = pd.crosstab(df_plt_top10_today['Com_Name'],df_plt_top10_today['Hour of Day']) -#Order heatmap Birds by frequency of occurrance -heat.index = pd.CategoricalIndex(heat.index, categories = freq_order) +heat = pd.crosstab(df_plt_top10_today['Com_Name'], df_plt_top10_today['Hour of Day']) +# Order heatmap Birds by frequency of occurrance +heat.index = pd.CategoricalIndex(heat.index, categories=freq_order) heat.sort_index(level=0, inplace=True) -hours_in_day = pd.Series(data = range(0,24)) -heat_frame = pd.DataFrame(data=0, index=heat.index, columns = hours_in_day) -heat=(heat+heat_frame).fillna(0) +hours_in_day = pd.Series(data=range(0, 24)) +heat_frame = pd.DataFrame(data=0, index=heat.index, columns=hours_in_day) +heat = (heat + heat_frame).fillna(0) -#Generatie heatmap plot -plot = sns.heatmap(heat, norm=LogNorm(), annot=True, annot_kws={"fontsize":7}, fmt="g", cmap = pal , square = False, cbar=False, linewidths = 0.5, linecolor = "Grey", ax=axs[1], yticklabels = False) -plot.set_xticklabels(plot.get_xticklabels(), rotation = 0, size = 7) +# Generatie heatmap plot +plot = sns.heatmap( + heat, + norm=LogNorm(), + annot=True, + annot_kws={ + "fontsize": 7}, + fmt="g", + cmap=pal, + square=False, + cbar=False, + linewidths=0.5, + linecolor="Grey", + ax=axs[1], + yticklabels=False) +plot.set_xticklabels(plot.get_xticklabels(), rotation=0, size=7) # Set heatmap border for _, spine in plot.spines.items(): @@ -103,13 +113,13 @@ for _, spine in plot.spines.items(): plot.set(ylabel=None) plot.set(xlabel="Hour of Day") -#Set combined plot layout and titles +# Set combined plot layout and titles f.subplots_adjust(top=0.9) -plt.suptitle("Top 10 Last Updated: "+ str(now.strftime("%Y-%m-%d %H:%M"))) +plt.suptitle("Top 10 Last Updated: " + str(now.strftime("%Y-%m-%d %H:%M"))) -#Save combined plot +# Save combined plot userDir = os.path.expanduser('~') -savename=userDir + '/BirdSongs/Extracted/Charts/Combo-'+str(now.strftime("%Y-%m-%d"))+'.png' +savename = userDir + '/BirdSongs/Extracted/Charts/Combo-' + str(now.strftime("%Y-%m-%d")) + '.png' plt.savefig(savename) plt.show() plt.close() @@ -119,18 +129,18 @@ plt.close() plt_Bot10_today = (df_plt_today['Com_Name'].value_counts()[-readings:]) df_plt_Bot10_today = df_plt_today[df_plt_today.Com_Name.isin(plt_Bot10_today.index)] -#Set Palette for graphics +# Set Palette for graphics pal = "Reds" -#Set up plot axes and titles +# Set up plot axes and titles -f, axs = plt.subplots(1, 2, figsize = (10, 4), gridspec_kw=dict(width_ratios=[3, 6]), facecolor='#77C487') +f, axs = plt.subplots(1, 2, figsize=(10, 4), gridspec_kw=dict(width_ratios=[3, 6]), facecolor='#77C487') plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0, hspace=0) -#generate y-axis order for all figures based on frequency +# generate y-axis order for all figures based on frequency freq_order = pd.value_counts(df_plt_Bot10_today['Com_Name']).iloc[-readings:].index -#make color for max confidence --> this groups by name and calculates max conf +# make color for max confidence --> this groups by name and calculates max conf confmax = df_plt_Bot10_today.groupby('Com_Name')['Confidence'].max() confmax = confmax.reindex(freq_order) # probably wrong order . . . how to sort by no. of detections ? @@ -138,33 +148,44 @@ confmax = confmax.reindex(freq_order) norm = plt.Normalize(confmax.values.min(), confmax.values.max()) colors = plt.cm.Reds(norm(confmax)) -#Generate frequency plot -plot=sns.countplot(y='Com_Name', data = df_plt_Bot10_today, palette = colors, order=freq_order, ax=axs[0]) +# Generate frequency plot +plot = sns.countplot(y='Com_Name', data=df_plt_Bot10_today, palette=colors, order=freq_order, ax=axs[0]) - - -#Try plot grid lines between bars - problem at the moment plots grid lines on bars - want between bars -z=plot.get_ymajorticklabels() -plot.set_yticklabels(['\n'.join(textwrap.wrap(ticklabel.get_text(),15)) for ticklabel in plot.get_yticklabels()], fontsize = 10) +# Try plot grid lines between bars - problem at the moment plots grid lines on bars - want between bars +z = plot.get_ymajorticklabels() +plot.set_yticklabels(['\n'.join(textwrap.wrap(ticklabel.get_text(), 15)) for ticklabel in plot.get_yticklabels()], fontsize=10) plot.set(ylabel=None) plot.set(xlabel="Detections") -#Generate crosstab matrix for heatmap plot +# Generate crosstab matrix for heatmap plot -heat = pd.crosstab(df_plt_Bot10_today['Com_Name'],df_plt_Bot10_today['Hour of Day']) -#Order heatmap Birds by frequency of occurrance -heat.index = pd.CategoricalIndex(heat.index, categories = freq_order) +heat = pd.crosstab(df_plt_Bot10_today['Com_Name'], df_plt_Bot10_today['Hour of Day']) +# Order heatmap Birds by frequency of occurrance +heat.index = pd.CategoricalIndex(heat.index, categories=freq_order) heat.sort_index(level=0, inplace=True) -hours_in_day = pd.Series(data = range(0,24)) -heat_frame = pd.DataFrame(data=0, index=heat.index, columns = hours_in_day) -heat=(heat+heat_frame).fillna(0) +hours_in_day = pd.Series(data=range(0, 24)) +heat_frame = pd.DataFrame(data=0, index=heat.index, columns=hours_in_day) +heat = (heat + heat_frame).fillna(0) -#Generatie heatmap plot -plot = sns.heatmap(heat, norm=LogNorm(), annot=True, fmt="g", annot_kws={"fontsize":7}, cmap = pal , square = False, cbar=False, linewidths = 0.5, linecolor = "Grey", ax=axs[1], yticklabels = False) -plot.set_xticklabels(plot.get_xticklabels(), rotation = 0, size = 7) +# Generatie heatmap plot +plot = sns.heatmap( + heat, + norm=LogNorm(), + annot=True, + fmt="g", + annot_kws={ + "fontsize": 7}, + cmap=pal, + square=False, + cbar=False, + linewidths=0.5, + linecolor="Grey", + ax=axs[1], + yticklabels=False) +plot.set_xticklabels(plot.get_xticklabels(), rotation=0, size=7) # Set heatmap border for _, spine in plot.spines.items(): @@ -172,12 +193,12 @@ for _, spine in plot.spines.items(): plot.set(ylabel=None) plot.set(xlabel="Hour of Day") -#Set combined plot layout and titles +# Set combined plot layout and titles f.subplots_adjust(top=0.9) -plt.suptitle("Bottom 10 Last Updated: "+ str(now.strftime("%Y-%m-%d %H:%M"))) +plt.suptitle("Bottom 10 Last Updated: " + str(now.strftime("%Y-%m-%d %H:%M"))) -#Save combined plot -savename=userDir + '/BirdSongs/Extracted/Charts/Combo2-'+str(now.strftime("%Y-%m-%d"))+'.png' +# Save combined plot +savename = userDir + '/BirdSongs/Extracted/Charts/Combo2-' + str(now.strftime("%Y-%m-%d")) + '.png' plt.savefig(savename) plt.show() plt.close() diff --git a/scripts/plotly_streamlit.py b/scripts/plotly_streamlit.py index 2d7eb6a..2df1550 100755 --- a/scripts/plotly_streamlit.py +++ b/scripts/plotly_streamlit.py @@ -4,8 +4,7 @@ import pandas as pd import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots -from datetime import timedelta, datetime -from pathlib import Path +from datetime import timedelta import sqlite3 from sqlite3 import Connection import plotly.express as px @@ -35,22 +34,22 @@ st.markdown(""" @st.cache(hash_funcs={Connection: id}) -def get_connection(path:str): - return sqlite3.connect(path,check_same_thread=False) +def get_connection(path: str): + return sqlite3.connect(path, check_same_thread=False) def get_data(conn: Connection): - df1=pd.read_sql("SELECT * FROM detections", con=conn) + df1 = pd.read_sql("SELECT * FROM detections", con=conn) return df1 + conn = get_connection(URI_SQLITE_DB) # Read in the cereal data # df = load_data() -df=get_data(conn) -df2=df.copy() -df2['DateTime']=pd.to_datetime(df2['Date'] + " " + df2['Time']) -df2=df2.set_index('DateTime') - +df = get_data(conn) +df2 = df.copy() +df2['DateTime'] = pd.to_datetime(df2['Date'] + " " + df2['Time']) +df2 = df2.set_index('DateTime') # Filter on date range @@ -60,174 +59,184 @@ df2=df2.set_index('DateTime') # Date as slider Start_Date = pd.to_datetime(df2.index.min()).date() -End_Date = pd.to_datetime(df2.index.max()).date() -cols1,cols2= st.columns((1,1)) +End_Date = pd.to_datetime(df2.index.max()).date() +cols1, cols2 = st.columns((1, 1)) Date_Slider = cols1.slider('Date Range', - min_value = Start_Date-timedelta(days=1), - max_value = End_Date, - value=(Start_Date, - End_Date) - ) + min_value=Start_Date - timedelta(days=1), + max_value=End_Date, + value=(Start_Date, + End_Date) + ) - -filt = (df2.index >= pd.Timestamp(Date_Slider[0])) & (df2.index <= pd.Timestamp(Date_Slider[1]+timedelta(days=1))) +filt = (df2.index >= pd.Timestamp(Date_Slider[0])) & (df2.index <= pd.Timestamp(Date_Slider[1] + timedelta(days=1))) df2 = df2[filt] st.write('', unsafe_allow_html=True) st.write('', unsafe_allow_html=True) -resample_sel=cols2.radio("Select Resample Resolution - To downsample and make run faster select longer period, Daily provides a view on detections at 15 min intervals through the day", ('1 minute', '5 minutes', '10 minutes', 'Hourly', 'Daily')) +resample_sel = cols2.radio( + ''' + Select Resample Resolution - To downsample and make run faster select longer period, + Daily provides a view on detections at 15 min intervals through the day + ''', + ('1 minute', + '5 minutes', + '10 minutes', + 'Hourly', + 'Daily')) -resample_times = {'1 minute':'1min', - '5 minutes':'5min', - '10 minutes':'10min', - 'Hourly':'1H', - 'Daily':'1D' +resample_times = {'1 minute': '1min', + '5 minutes': '5min', + '10 minutes': '10min', + 'Hourly': '1H', + 'Daily': '1D' } resample_time = resample_times[resample_sel] -df5=df2.resample(resample_time)['Com_Name'].aggregate('unique').explode() +df5 = df2.resample(resample_time)['Com_Name'].aggregate('unique').explode() -#Create species count for selected date range +# Create species count for selected date range -Specie_Count=df5.value_counts() +Specie_Count = df5.value_counts() -#Create species treemap +# Create species treemap # Create Hourly Crosstab -hourly=pd.crosstab(df5,df5.index.hour, dropna=False) +hourly = pd.crosstab(df5, df5.index.hour, dropna=False) # Filter on species species = list(hourly.index) -cols1,cols2= st.columns((1,1)) +cols1, cols2 = st.columns((1, 1)) top_N = cols1.slider( 'Select Number of Birds to Show', - min_value = 1, - value=min(10,len(Specie_Count)) - ) + min_value=1, + value=min(10, len(Specie_Count)) +) top_N_species = (df5.value_counts()[:top_N]) -specie = cols2.selectbox('Which bird would you like to explore for the dates '+str(Date_Slider[0])+' to '+str(Date_Slider[1])+'?', species, - index=species.index(list(top_N_species.index)[0])) +specie = cols2.selectbox('Which bird would you like to explore for the dates ' + str(Date_Slider[0]) + ' to ' + str(Date_Slider[1]) + '?', species, + index=species.index(list(top_N_species.index)[0])) -font_size=15 +font_size = 15 -#specie filter -filt=df2['Com_Name']==specie - -df_counts=sum(df5==specie) - +# specie filter +filt = df2['Com_Name'] == specie +df_counts = sum(df5 == specie) if resample_time != '1D': fig = make_subplots( - rows=3, cols =2, - specs= [[{"type":"xy","rowspan":3}, {"type":"polar","rowspan":2}], [{"rowspan":1}, {"rowspan":1} ], [None, {"type":"xy","rowspan":1}]], - subplot_titles=('Top '+ str(top_N) + ' Species in Date Range '+str(Date_Slider[0])+' to '+str(Date_Slider[1])+' for '+str(resample_sel)+' sampling interval.'+'', - 'Total Detect:'+str('{:,}'.format(df_counts))+ - ' Confidence Max:'+str('{:.2f}%'.format(max(df2[df2['Com_Name']==specie]['Confidence'])*100))+ - ' '+' Median:'+str('{:.2f}%'.format(np.median(df2[df2['Com_Name']==specie]['Confidence'])*100)) - ) + rows=3, cols=2, + specs=[[{"type": "xy", "rowspan": 3}, {"type": "polar", "rowspan": 2}], [{"rowspan": 1}, {"rowspan": 1}], [None, {"type": "xy", "rowspan": 1}]], + subplot_titles=('Top ' + + str(top_N) + + ' Species in Date Range ' + + str(Date_Slider[0]) + + ' to ' + + str(Date_Slider[1]) + + ' for ' + + str(resample_sel) + + ' sampling interval.' + + '', + 'Total Detect:' + str('{:,}'.format(df_counts)) + + ' Confidence Max:' + str('{:.2f}%'.format(max(df2[df2['Com_Name'] == specie]['Confidence']) * 100)) + + ' ' + ' Median:' + str('{:.2f}%'.format(np.median(df2[df2['Com_Name'] == specie]['Confidence']) * 100)) ) - fig.layout.annotations[1].update(x=0.7,y=0.25, font_size=15) + ) + fig.layout.annotations[1].update(x=0.7, y=0.25, font_size=15) - #Plot seen species for selected date range and number of species - fig.add_trace(go.Bar(y=top_N_species.index, x=top_N_species, orientation='h'), row=1,col=1) + # Plot seen species for selected date range and number of species + fig.add_trace(go.Bar(y=top_N_species.index, x=top_N_species, orientation='h'), row=1, col=1) fig.update_layout( margin=dict(l=0, r=0, t=50, b=0), - yaxis={'categoryorder':'total ascending'}) - + yaxis={'categoryorder': 'total ascending'}) # Set 360 degrees, 24 hours for polar plot theta = np.linspace(0.0, 360, 24, endpoint=False) - specie_filt= df5==specie - df3=df5[specie_filt] + specie_filt = df5 == specie + df3 = df5[specie_filt] - detections2= pd.crosstab(df3, df3.index.hour) + detections2 = pd.crosstab(df3, df3.index.hour) - - - - d=pd.DataFrame(np.zeros((23,1))).squeeze() + d = pd.DataFrame(np.zeros((23, 1))).squeeze() detections = hourly.loc[specie] - detections=(d+detections).fillna(0) - fig.add_trace(go.Barpolar(r = detections, theta=theta), row=1, col=2) + detections = (d + detections).fillna(0) + fig.add_trace(go.Barpolar(r=detections, theta=theta), row=1, col=2) fig.update_layout( autosize=False, - width = 1000, - height = 500, + width=1000, + height=500, showlegend=False, - polar = dict( - radialaxis = dict( - tickfont_size = font_size, - showticklabels = False, - hoverformat = "#%{theta}: