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
+
import librosa
|
5 |
+
import numpy as np
|
6 |
+
import io
|
7 |
+
import os
|
8 |
+
import gc
|
9 |
+
import matplotlib.pyplot as plt
|
10 |
+
import librosa.display
|
11 |
+
from datetime import datetime
|
12 |
+
import random
|
13 |
+
from tensorflow.keras.preprocessing import image
|
14 |
+
import matplotlib
|
15 |
+
|
16 |
+
|
17 |
+
# load assets
|
18 |
+
|
19 |
+
ppt = Image.open(r"poster\Avifauna Acoustics Detection.png")
|
20 |
+
dataset_img = Image.open("poster/dataset.png")
|
21 |
+
# about_img = Image.open("poster/about.png")
|
22 |
+
|
23 |
+
|
24 |
+
# Set Matplotlib backend
|
25 |
+
matplotlib.use("Agg")
|
26 |
+
|
27 |
+
# Define the classes/species mapping
|
28 |
+
class_labels = {
|
29 |
+
0: 'affinis',
|
30 |
+
1: 'asiaticus',
|
31 |
+
2: 'indicus',
|
32 |
+
3: 'mystery',
|
33 |
+
4: 'smyrnensis',
|
34 |
+
5: 'sonneratii',
|
35 |
+
6: 'striata',
|
36 |
+
7: 'sutorius',
|
37 |
+
8: 'xanthornus'
|
38 |
+
}
|
39 |
+
|
40 |
+
# Function to preprocess audio for CNN models
|
41 |
+
N_FFT = 1024
|
42 |
+
HOP_SIZE = 1024
|
43 |
+
N_MELS = 128
|
44 |
+
WIN_SIZE = 1024
|
45 |
+
WINDOW_TYPE = "hann"
|
46 |
+
FEATURE = "mel"
|
47 |
+
FMIN = 0
|
48 |
+
|
49 |
+
|
50 |
+
def preprocess_and_save_spectrogram_from_signal(signal, image_path):
|
51 |
+
# Plot the spectrogram and save it
|
52 |
+
plt.figure(figsize=(10, 4))
|
53 |
+
D = librosa.amplitude_to_db(np.abs(librosa.stft(signal)), ref=np.max)
|
54 |
+
librosa.display.specshow(D, y_axis="linear")
|
55 |
+
plt.colorbar(format="%+2.0f dB")
|
56 |
+
plt.title("Linear-frequency power spectrogram")
|
57 |
+
|
58 |
+
# Save the spectrogram image to the species folder
|
59 |
+
plt.savefig(image_path, format="png", bbox_inches="tight")
|
60 |
+
plt.close()
|
61 |
+
|
62 |
+
|
63 |
+
def preprocess_and_save_spectrogram_from_signal_v2(signal, image_path):
|
64 |
+
fig, ax = plt.subplots(figsize=(10, 4))
|
65 |
+
D = librosa.amplitude_to_db(np.abs(librosa.stft(signal)), ref=np.max)
|
66 |
+
librosa.display.specshow(D, y_axis="linear")
|
67 |
+
|
68 |
+
try:
|
69 |
+
plt.savefig(image_path, format="png", bbox_inches="tight")
|
70 |
+
|
71 |
+
except Exception as e:
|
72 |
+
print(f"Error processing {image_path}: {e}")
|
73 |
+
|
74 |
+
plt.close(fig)
|
75 |
+
|
76 |
+
|
77 |
+
# Streamlit app with two columns
|
78 |
+
st.set_page_config(layout="wide", page_title="Avifauna Acoustics Detection", page_icon=":bird:")
|
79 |
+
|
80 |
+
st.title('Avifauna Acoustics Detection')
|
81 |
+
|
82 |
+
def home_page():
|
83 |
+
st.title("Avifauna Acoustics Detection")
|
84 |
+
with st.container():
|
85 |
+
st.subheader("Introduction")
|
86 |
+
st.write(
|
87 |
+
"Avifauna Acoustics Detection is a field in ornithology and machine learning that involves identifying different bird species based on their vocalizations and physical characteristics. It plays a crucial role in bird conservation, ecology, and birdwatching. Bird vocalizations, such as songs and calls, are unique to each species and serve as an essential way to distinguish them. Additionally, machine learning and computer vision techniques are used to identify birds based on their physical attributes, including plumage, beak shape, and size. Avifauna Acoustics Detection can be valuable for tracking migration patterns, studying bird behavior, and monitoring populations.")
|
88 |
+
|
89 |
+
st.write("---")
|
90 |
+
st.subheader("Key Features")
|
91 |
+
st.write(
|
92 |
+
"""
|
93 |
+
- Our Avifauna Acoustics Detection application is designed to identify various bird species from audio recordings and images.
|
94 |
+
- The application utilizes machine learning models trained on extensive datasets of bird songs, calls, and images.
|
95 |
+
- We have employed deep learning models, including Convolutional Neural Networks (CNNs) for image recognition and recurrent neural networks (RNNs) for audio analysis.
|
96 |
+
- Users can either upload bird audio recordings or bird images to get predictions about the species.
|
97 |
+
- The application can provide information about the bird's common habitats, migration patterns, and conservation status, enhancing the user's birdwatching experience.""")
|
98 |
+
st.write("---")
|
99 |
+
st.subheader("Problem Statement")
|
100 |
+
st.write(
|
101 |
+
"Our goal is to develop a reliable tool for bird enthusiasts, ornithologists, and conservationists to "
|
102 |
+
"easily identify bird species from their vocalizations and visual characteristics. We aim to address the "
|
103 |
+
"challenge of accurate Avifauna Acoustics Detection by leveraging advanced machine learning techniques. "
|
104 |
+
"This can aid in monitoring bird populations, understanding their behavior, and contributing to "
|
105 |
+
"conservation efforts.")
|
106 |
+
|
107 |
+
st.write("---")
|
108 |
+
st.subheader("Future Scope")
|
109 |
+
st.write(
|
110 |
+
"Avifauna Acoustics Detection can have a profound impact on bird conservation and environmental research. "
|
111 |
+
"In the future, we envision expanding the application's capabilities by incorporating real-time "
|
112 |
+
"recognition using smartphones. This can assist in on-the-fly bird identification during birdwatching "
|
113 |
+
"excursions. Additionally, we can collaborate with researchers to collect more extensive datasets and "
|
114 |
+
"improve the accuracy of our models. Such advancements can play a vital role in preserving bird "
|
115 |
+
"biodiversity and understanding their role in ecosystems.")
|
116 |
+
|
117 |
+
with st.container():
|
118 |
+
st.write("---")
|
119 |
+
st.write("##")
|
120 |
+
with st.container():
|
121 |
+
st.write("---")
|
122 |
+
st.write("##")
|
123 |
+
image_column, text_column = st.columns((1, 2))
|
124 |
+
with image_column:
|
125 |
+
st.image(ppt, use_column_width=True)
|
126 |
+
with text_column:
|
127 |
+
st.subheader("Avifauna Acoustics Detection - PPT")
|
128 |
+
st.write(
|
129 |
+
"""
|
130 |
+
This PPT explains the overall project in brief.
|
131 |
+
"""
|
132 |
+
)
|
133 |
+
link_str = "https://www.canva.com/design/DAFqmtxqCeU/D_a9yxpRnjr41IRaqGCVFA/edit?utm_content=DAFqmtxqCeU&utm_campaign=designshare&utm_medium=link2&utm_source=sharebutton"
|
134 |
+
# link_str2 = "https://drive.google.com/drive/folders/1cFb_WIXBSvzkGFMEtjxAtnz502aEXSM4?usp=sharing"
|
135 |
+
st.markdown(f"[View]({link_str})")
|
136 |
+
|
137 |
+
with st.container():
|
138 |
+
st.write("---")
|
139 |
+
st.write("##")
|
140 |
+
image_column, text_column = st.columns((1, 2))
|
141 |
+
with image_column:
|
142 |
+
st.image(dataset_img, use_column_width=True)
|
143 |
+
with text_column:
|
144 |
+
st.subheader("Dataset - Xeno-canto")
|
145 |
+
st.write(
|
146 |
+
"""
|
147 |
+
"""
|
148 |
+
)
|
149 |
+
link_str = "https://xeno-canto.org/"
|
150 |
+
st.markdown(f"[View]({link_str})")
|
151 |
+
|
152 |
+
def model():
|
153 |
+
# Create a sidebar for model selection
|
154 |
+
with st.sidebar:
|
155 |
+
st.write('Model Selection')
|
156 |
+
model_files = [f for f in os.listdir('model') if f.endswith('.h5')]
|
157 |
+
selected_model = st.selectbox('Select a model', model_files)
|
158 |
+
|
159 |
+
# Create two columns
|
160 |
+
col1, col2 = st.columns(2)
|
161 |
+
|
162 |
+
# Upload an MP3 audio file
|
163 |
+
with col1:
|
164 |
+
audio_file = st.file_uploader('Upload an MP3 audio file', type=['mp3'])
|
165 |
+
|
166 |
+
if audio_file is not None:
|
167 |
+
st.write('Processing...')
|
168 |
+
|
169 |
+
# Load the audio for playback
|
170 |
+
y, sr = librosa.load(audio_file)
|
171 |
+
|
172 |
+
# Play the uploaded audio using st.audio()
|
173 |
+
st.audio(audio_file, format="audio/mp3", start_time=0)
|
174 |
+
|
175 |
+
# Predict button
|
176 |
+
if st.button('Predict'):
|
177 |
+
st.write('Predicting using', selected_model)
|
178 |
+
|
179 |
+
# get current time
|
180 |
+
now = datetime.now()
|
181 |
+
|
182 |
+
# Generate a random number (e.g., a 6-digit number)
|
183 |
+
random_number = random.randint(100000, 999999)
|
184 |
+
|
185 |
+
# Create a new file name with the random number
|
186 |
+
file_name = f'input_{random_number}.png'
|
187 |
+
|
188 |
+
# Define the full path to the image
|
189 |
+
image_path = fr'C:\Users\jaini\PycharmProjects\nlp\DL\temp_images\{file_name}'
|
190 |
+
|
191 |
+
# Call the `saveMel` function with the updated image_path
|
192 |
+
# plot_spectrogram_and_save(y, image_path)
|
193 |
+
|
194 |
+
preprocess_and_save_spectrogram_from_signal(y, image_path)
|
195 |
+
# preprocess_and_save_spectrogram_from_signal_v2(y, image_path)
|
196 |
+
image_ = Image.open(image_path)
|
197 |
+
st.image(image_, caption='Specrogram', use_column_width=True)
|
198 |
+
|
199 |
+
# Load the selected model
|
200 |
+
|
201 |
+
model_path = os.path.join('model', selected_model)
|
202 |
+
model = tf.keras.models.load_model(model_path)
|
203 |
+
|
204 |
+
# Load and preprocess the image
|
205 |
+
img = image.load_img(image_path, target_size=(224, 224))
|
206 |
+
img = image.img_to_array(img)
|
207 |
+
img = np.expand_dims(img, axis=0)
|
208 |
+
|
209 |
+
# Make a prediction
|
210 |
+
predicted_class_index = model.predict(img, verbose=1)
|
211 |
+
print(predicted_class_index)
|
212 |
+
predicted_class = class_labels[predicted_class_index.argmax()]
|
213 |
+
|
214 |
+
# Display the predicted bird species
|
215 |
+
st.write('Predicted Bird Species:', predicted_class)
|
216 |
+
|
217 |
+
# create a Streamlit app
|
218 |
+
# def about_us():
|
219 |
+
# # st.image(about_img)
|
220 |
+
|
221 |
+
|
222 |
+
def app():
|
223 |
+
tab1, tab2 = st.tabs(["Our Project", "Model"])
|
224 |
+
with tab1:
|
225 |
+
home_page()
|
226 |
+
with tab2:
|
227 |
+
model()
|
228 |
+
# with tab3:
|
229 |
+
# # about_us()
|
230 |
+
|
231 |
+
|
232 |
+
app()
|