Spaces:
Build error
Build error
Add more examples & Fix height issue of Prediction
Browse files- .gitattributes +2 -0
- .gitignore +1 -0
- app.py +66 -19
- bat_detect/utils/audio_utils.py +8 -2
- bat_detect/utils/detector_utils.py +11 -9
- requirements.txt +11 -9
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 35 |
models/Net2DFast_UK_same.pth.tar filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 35 |
models/Net2DFast_UK_same.pth.tar filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.flac filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.pth.tar filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
__pycache__
|
app.py
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import os
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
import pandas as pd
|
| 5 |
import numpy as np
|
|
@@ -15,23 +31,48 @@ args = du.get_default_bd_args()
|
|
| 15 |
args['detection_threshold'] = 0.3
|
| 16 |
args['time_expansion_factor'] = 1
|
| 17 |
args['model_path'] = 'models/Net2DFast_UK_same.pth.tar'
|
| 18 |
-
max_duration =
|
| 19 |
|
| 20 |
# load the model
|
| 21 |
model, params = du.load_model(args['model_path'])
|
| 22 |
|
| 23 |
|
| 24 |
-
|
| 25 |
headers=["species", "time", "detection_prob", "species_prob"],
|
| 26 |
datatype=["str", "str", "str", "str"],
|
| 27 |
row_count=1,
|
| 28 |
col_count=(4, "fixed"),
|
|
|
|
|
|
|
| 29 |
label='Predictions'
|
| 30 |
)
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
examples = [['example_data/audio/20170701_213954-MYOMYS-LR_0_0.5.wav', 0.3],
|
| 33 |
['example_data/audio/20180530_213516-EPTSER-LR_0_0.5.wav', 0.3],
|
| 34 |
-
['example_data/audio/20180627_215323-RHIFER-LR_0_0.5.wav', 0.3]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
def make_prediction(file_name=None, detection_threshold=0.3):
|
|
@@ -46,6 +87,7 @@ def make_prediction(file_name=None, detection_threshold=0.3):
|
|
| 46 |
|
| 47 |
# process the file to generate predictions
|
| 48 |
results = du.process_file(audio_file, model, params, args, max_duration=max_duration)
|
|
|
|
| 49 |
|
| 50 |
anns = [ann for ann in results['pred_dict']['annotation']]
|
| 51 |
clss = [aa['class'] for aa in anns]
|
|
@@ -54,10 +96,10 @@ def make_prediction(file_name=None, detection_threshold=0.3):
|
|
| 54 |
det_prob = [aa['det_prob'] for aa in anns]
|
| 55 |
data = {'species': clss, 'time': st_time, 'detection_prob': det_prob, 'species_prob': cls_prob}
|
| 56 |
|
| 57 |
-
|
| 58 |
im = generate_results_image(audio_file, anns)
|
| 59 |
|
| 60 |
-
return [
|
| 61 |
|
| 62 |
|
| 63 |
def generate_results_image(audio_file, anns):
|
|
@@ -72,7 +114,11 @@ def generate_results_image(audio_file, anns):
|
|
| 72 |
|
| 73 |
# create fig
|
| 74 |
plt.close('all')
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
spec_duration = au.x_coords_to_time(spec.shape[1], sampling_rate, params['fft_win_length'], params['fft_overlap'])
|
| 77 |
viz.create_box_image(spec, fig, anns, 0, spec_duration, spec_duration, params, spec.max()*1.1, False, True)
|
| 78 |
plt.ylabel('Freq - kHz')
|
|
@@ -81,28 +127,29 @@ def generate_results_image(audio_file, anns):
|
|
| 81 |
|
| 82 |
# convert fig to image
|
| 83 |
fig.canvas.draw()
|
| 84 |
-
data = np.frombuffer(fig.canvas.
|
| 85 |
w, h = fig.canvas.get_width_height()
|
| 86 |
im = data.reshape((int(h), int(w), -1))
|
| 87 |
|
| 88 |
return im
|
| 89 |
|
| 90 |
|
| 91 |
-
descr_txt = "Demo of
|
| 92 |
-
"<br>
|
| 93 |
-
"file is longer than
|
| 94 |
-
|
| 95 |
|
| 96 |
-
gr.Interface(
|
| 97 |
fn = make_prediction,
|
| 98 |
inputs = [gr.Audio(sources=["upload"], type="filepath"),
|
| 99 |
gr.Dropdown([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])],
|
| 100 |
-
outputs = [
|
| 101 |
-
theme = "huggingface",
|
| 102 |
-
title = "
|
| 103 |
description = descr_txt,
|
| 104 |
examples = examples,
|
| 105 |
allow_flagging = 'never',
|
| 106 |
-
|
|
|
|
| 107 |
|
| 108 |
-
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
|
| 3 |
+
Step 1: Run Your Script
|
| 4 |
+
Save the above code in a file, for example, app.py. Then, run the script using Python:
|
| 5 |
+
|
| 6 |
+
python app.py
|
| 7 |
+
|
| 8 |
+
Step 2: Access the Gradio Interface
|
| 9 |
+
After running the script, you should see output in the terminal indicating that the Gradio interface is running. It will provide a local URL (usually http://localhost:7860) that you can open in your web browser to interact with your Gradio app.
|
| 10 |
+
|
| 11 |
+
Additional Features
|
| 12 |
+
Gradio supports various input and output types, including images, audio, and more. You can customize the interface further by adding more inputs and outputs, changing the layout, and adding examples.
|
| 13 |
+
|
| 14 |
+
For more advanced usage and features, you can refer to the Gradio documentation.
|
| 15 |
+
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
import gradio as gr
|
|
|
|
| 19 |
import matplotlib.pyplot as plt
|
| 20 |
import pandas as pd
|
| 21 |
import numpy as np
|
|
|
|
| 31 |
args['detection_threshold'] = 0.3
|
| 32 |
args['time_expansion_factor'] = 1
|
| 33 |
args['model_path'] = 'models/Net2DFast_UK_same.pth.tar'
|
| 34 |
+
max_duration = 10.0
|
| 35 |
|
| 36 |
# load the model
|
| 37 |
model, params = du.load_model(args['model_path'])
|
| 38 |
|
| 39 |
|
| 40 |
+
prediction_df = gr.Dataframe(
|
| 41 |
headers=["species", "time", "detection_prob", "species_prob"],
|
| 42 |
datatype=["str", "str", "str", "str"],
|
| 43 |
row_count=1,
|
| 44 |
col_count=(4, "fixed"),
|
| 45 |
+
# max_height=300,
|
| 46 |
+
elem_classes="qa-pairs",
|
| 47 |
label='Predictions'
|
| 48 |
)
|
| 49 |
+
|
| 50 |
+
prediction_css = """
|
| 51 |
+
.qa-pairs .table-wrap {
|
| 52 |
+
min-height: 300px;
|
| 53 |
+
max-height: 300px;
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
#visualisation-container {
|
| 57 |
+
overflow-x: auto;
|
| 58 |
+
width: 100%;
|
| 59 |
+
height: 200px; /* Fixed height */
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
#visualisation-container img {
|
| 63 |
+
height: 100%; /* fixed height */
|
| 64 |
+
width: auto; /* flexible width */
|
| 65 |
+
object-fit: contain;
|
| 66 |
+
}
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
examples = [['example_data/audio/20170701_213954-MYOMYS-LR_0_0.5.wav', 0.3],
|
| 70 |
['example_data/audio/20180530_213516-EPTSER-LR_0_0.5.wav', 0.3],
|
| 71 |
+
['example_data/audio/20180627_215323-RHIFER-LR_0_0.5.wav', 0.3],
|
| 72 |
+
['example_data/audio/Myotis daubentonii_A004034_PVTRQZEYAT.flac', 0.3],
|
| 73 |
+
# ['example_data/audio/Eptesicus serotinus_A003974_RLNMCAZDEJ.flac', 0.3],
|
| 74 |
+
# ['example_data/audio/Nyctalus noctula_A004093_DOEYCSPEZD.flac', 0.3],
|
| 75 |
+
]
|
| 76 |
|
| 77 |
|
| 78 |
def make_prediction(file_name=None, detection_threshold=0.3):
|
|
|
|
| 87 |
|
| 88 |
# process the file to generate predictions
|
| 89 |
results = du.process_file(audio_file, model, params, args, max_duration=max_duration)
|
| 90 |
+
# results = du.process_file(audio_file, model, params, args, max_duration=False)
|
| 91 |
|
| 92 |
anns = [ann for ann in results['pred_dict']['annotation']]
|
| 93 |
clss = [aa['class'] for aa in anns]
|
|
|
|
| 96 |
det_prob = [aa['det_prob'] for aa in anns]
|
| 97 |
data = {'species': clss, 'time': st_time, 'detection_prob': det_prob, 'species_prob': cls_prob}
|
| 98 |
|
| 99 |
+
prediction_df = pd.DataFrame(data=data)
|
| 100 |
im = generate_results_image(audio_file, anns)
|
| 101 |
|
| 102 |
+
return [prediction_df, im]
|
| 103 |
|
| 104 |
|
| 105 |
def generate_results_image(audio_file, anns):
|
|
|
|
| 114 |
|
| 115 |
# create fig
|
| 116 |
plt.close('all')
|
| 117 |
+
# Adjust figsize calculation to control the width of the spectrogram
|
| 118 |
+
fig_width = max(6, spec.shape[1] / 100) # Minimum width of 6 inches, scales with spectrogram width
|
| 119 |
+
fig_height = spec.shape[0] / 100 # Adjust the divisor for height scaling (higher = smaller)
|
| 120 |
+
fig = plt.figure(1, figsize=(fig_width, fig_height), dpi=100, frameon=False)
|
| 121 |
+
|
| 122 |
spec_duration = au.x_coords_to_time(spec.shape[1], sampling_rate, params['fft_win_length'], params['fft_overlap'])
|
| 123 |
viz.create_box_image(spec, fig, anns, 0, spec_duration, spec_duration, params, spec.max()*1.1, False, True)
|
| 124 |
plt.ylabel('Freq - kHz')
|
|
|
|
| 127 |
|
| 128 |
# convert fig to image
|
| 129 |
fig.canvas.draw()
|
| 130 |
+
data = np.frombuffer(fig.canvas.buffer_rgba(), dtype=np.uint8)
|
| 131 |
w, h = fig.canvas.get_width_height()
|
| 132 |
im = data.reshape((int(h), int(w), -1))
|
| 133 |
|
| 134 |
return im
|
| 135 |
|
| 136 |
|
| 137 |
+
descr_txt = "Demo of Bat identification tools. " \
|
| 138 |
+
"<br>It is based on two state-of-the-art models BatDetect2 and Bat-cli. " \
|
| 139 |
+
"For the demo purposes, the input file is longer than 10 seconds, only the first 10 seconds will be processed." \
|
| 140 |
+
# "<br>Check out the two papers for more details [here](https://www.biorxiv.org/content/10.1101/2022.12.14.520490v1) and [here](https://ar5iv.labs.arxiv.org/html/2309.11218)."
|
| 141 |
|
| 142 |
+
Gradio_interface = gr.Interface(
|
| 143 |
fn = make_prediction,
|
| 144 |
inputs = [gr.Audio(sources=["upload"], type="filepath"),
|
| 145 |
gr.Dropdown([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])],
|
| 146 |
+
outputs = [prediction_df, gr.Image(interactive=False, label="Visualisation", elem_id="visualisation-container")],
|
| 147 |
+
# theme = "huggingface",
|
| 148 |
+
title = "Bat Identification Demo",
|
| 149 |
description = descr_txt,
|
| 150 |
examples = examples,
|
| 151 |
allow_flagging = 'never',
|
| 152 |
+
css=prediction_css
|
| 153 |
+
)
|
| 154 |
|
| 155 |
+
Gradio_interface.launch()
|
bat_detect/utils/audio_utils.py
CHANGED
|
@@ -139,8 +139,14 @@ def gen_mag_spectrogram(x, fs, ms, overlap_perc):
|
|
| 139 |
# window data
|
| 140 |
step = nfft - noverlap
|
| 141 |
|
| 142 |
-
# compute spec
|
| 143 |
-
spec, _ = librosa.core.spectrum._spectrogram(y=x, power=1, n_fft=nfft, hop_length=step, center=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
# remove DC component and flip vertical orientation
|
| 146 |
spec = np.flipud(spec[1:, :])
|
|
|
|
| 139 |
# window data
|
| 140 |
step = nfft - noverlap
|
| 141 |
|
| 142 |
+
# # compute spec
|
| 143 |
+
# spec, _ = librosa.core.spectrum._spectrogram(y=x, power=1, n_fft=nfft, hop_length=step, center=False)
|
| 144 |
+
|
| 145 |
+
# Compute the Short-Time Fourier Transform (STFT)
|
| 146 |
+
stft = librosa.stft(x, n_fft=nfft, hop_length=step, center=False)
|
| 147 |
+
|
| 148 |
+
# Convert to magnitude spectrogram
|
| 149 |
+
spec = np.abs(stft)
|
| 150 |
|
| 151 |
# remove DC component and flip vertical orientation
|
| 152 |
spec = np.flipud(spec[1:, :])
|
bat_detect/utils/detector_utils.py
CHANGED
|
@@ -197,7 +197,8 @@ def compute_spectrogram(audio, sampling_rate, params, return_np=False):
|
|
| 197 |
return duration, spec, spec_np
|
| 198 |
|
| 199 |
|
| 200 |
-
def process_file(audio_file, model, params, args, time_exp=None, top_n=5,
|
|
|
|
| 201 |
|
| 202 |
# store temporary results here
|
| 203 |
predictions = []
|
|
@@ -224,17 +225,18 @@ def process_file(audio_file, model, params, args, time_exp=None, top_n=5, return
|
|
| 224 |
|
| 225 |
return_np_spec = args['spec_features'] or args['spec_slices']
|
| 226 |
|
| 227 |
-
# loop through larger file and split into chunks
|
| 228 |
-
|
| 229 |
-
|
|
|
|
|
|
|
| 230 |
for chunk_id in range(num_chunks):
|
| 231 |
|
| 232 |
-
# chunk
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
start_sample = chunk_id*chunk_length
|
| 236 |
-
end_sample = np.minimum((chunk_id+1)*chunk_length, audio_full.shape[0])
|
| 237 |
audio = audio_full[start_sample:end_sample]
|
|
|
|
| 238 |
|
| 239 |
# load audio file and compute spectrogram
|
| 240 |
duration, spec, spec_np = compute_spectrogram(audio, sampling_rate, params, return_np_spec)
|
|
|
|
| 197 |
return duration, spec, spec_np
|
| 198 |
|
| 199 |
|
| 200 |
+
def process_file(audio_file, model, params, args, time_exp=None, top_n=5,
|
| 201 |
+
return_raw_preds=False, max_duration=False, overlap_percentage = 0.5):
|
| 202 |
|
| 203 |
# store temporary results here
|
| 204 |
predictions = []
|
|
|
|
| 225 |
|
| 226 |
return_np_spec = args['spec_features'] or args['spec_slices']
|
| 227 |
|
| 228 |
+
# loop through larger file and split into chunks with overlap (50% overlap)
|
| 229 |
+
overlap_length = int(sampling_rate * args['chunk_size'] * overlap_percentage)
|
| 230 |
+
chunk_length = int(sampling_rate * args['chunk_size'])
|
| 231 |
+
|
| 232 |
+
num_chunks = int(np.ceil((duration_full * sampling_rate) / (chunk_length - overlap_length)))
|
| 233 |
for chunk_id in range(num_chunks):
|
| 234 |
|
| 235 |
+
# chunk with overlap
|
| 236 |
+
start_sample = chunk_id * (chunk_length - overlap_length)
|
| 237 |
+
end_sample = np.minimum(start_sample + chunk_length, audio_full.shape[0])
|
|
|
|
|
|
|
| 238 |
audio = audio_full[start_sample:end_sample]
|
| 239 |
+
chunk_time = start_sample/sampling_rate
|
| 240 |
|
| 241 |
# load audio file and compute spectrogram
|
| 242 |
duration, spec, spec_np = compute_spectrogram(audio, sampling_rate, params, return_np_spec)
|
requirements.txt
CHANGED
|
@@ -1,9 +1,11 @@
|
|
| 1 |
-
librosa==0.
|
| 2 |
-
matplotlib==3.
|
| 3 |
-
numpy==1.
|
| 4 |
-
pandas==
|
| 5 |
-
scikit_learn==1.
|
| 6 |
-
scipy==1.
|
| 7 |
-
torch==1.
|
| 8 |
-
torchaudio==
|
| 9 |
-
torchvision==0.
|
|
|
|
|
|
|
|
|
| 1 |
+
librosa==0.11.*
|
| 2 |
+
matplotlib==3.9.*
|
| 3 |
+
numpy==1.26.*
|
| 4 |
+
pandas==2.2.*
|
| 5 |
+
scikit_learn==1.5.*
|
| 6 |
+
scipy==1.14.*
|
| 7 |
+
torch==2.1.*
|
| 8 |
+
torchaudio==2.1.*
|
| 9 |
+
torchvision==0.16.*
|
| 10 |
+
gradio==5.0.*
|
| 11 |
+
pydantic==2.10.6
|