wooalex commited on
Commit
dbe12a5
·
verified ·
1 Parent(s): 260df56

Upload folder using huggingface_hub

Browse files
iti110_birds_classifier_model_builder.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """ITI110-Birds-CNN-ResNet-GPT-4o.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/16uUvA-YukBceEUQd8qBCISg9K3raRmAh
8
+
9
+ Based on the above pipeline, write a python code to create a Gradio UI which performs the following: 1. An input text box for user to input the path to the dataset 2. An output text bx to display the distribution of samples across species 3. Automatically perform 1.2 Audio Processing 4. Put 3 checkboxes for enabling or disabling Pitch Shifting, Time Stretching, and Background Noise 5. Use bullet buttons to allow user to select using MFCC, Spectrograms or Chroma for Feature Extraction 6. Use bullet buttons to allow user to select building either RestNet50 or CNN model 7. Let the user press a button to train and save the model 8. Let the user press a button to evaluate the model, output the results 9. Let the user press a button to perform hyperparameter tuning and save the model file 10. Let the user press a button to perform Learning Rate Reduction Callback and save the model file 11. Let the user press a button to evaluate the two fine-tuned models, output the results
10
+
11
+ Below is the Python code to create a Gradio UI that performs the tasks as specified. This code assumes you have already installed Gradio (pip install gradio) and other necessary libraries.
12
+ """
13
+
14
+
15
+ import os
16
+ import numpy as np
17
+ import pandas as pd
18
+ import librosa
19
+ import soundfile as sf
20
+ from pydub import AudioSegment
21
+ import gradio as gr
22
+ from sklearn.model_selection import train_test_split
23
+ from sklearn.preprocessing import LabelEncoder
24
+ from tensorflow.keras.utils import to_categorical
25
+ from tensorflow.keras.models import Sequential, load_model, Model
26
+ from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, Input
27
+ from tensorflow.keras.applications import ResNet50
28
+ from tensorflow.keras.callbacks import ReduceLROnPlateau
29
+ import matplotlib.pyplot as plt
30
+ import seaborn as sns
31
+ from sklearn.metrics import classification_report, confusion_matrix
32
+
33
+ # Global variables
34
+ dataset_path = ''
35
+ species_folders = []
36
+ label_encoder = LabelEncoder()
37
+ X_train, X_test, y_train, y_test = None, None, None, None
38
+ history = None
39
+ model = None
40
+
41
+ def data_exploration(path):
42
+ global dataset_path, species_folders
43
+ dataset_path = path
44
+ species_folders = [f for f in os.listdir(dataset_path) if os.path.isdir(os.path.join(dataset_path, f))]
45
+ species_count = Counter()
46
+ for species in species_folders:
47
+ species_files = os.listdir(os.path.join(dataset_path, species))
48
+ species_count[species] = len(species_files)
49
+ species_df = pd.DataFrame(list(species_count.items()), columns=['Species', 'Count'])
50
+ species_df.to_csv('species_distribution.csv', index=False)
51
+ return species_df.to_string(index=False)
52
+
53
+ def audio_processing():
54
+ for species in species_folders:
55
+ species_folder = os.path.join(dataset_path, species)
56
+ for file_name in os.listdir(species_folder):
57
+ if file_name.endswith('.mp3'):
58
+ mp3_path = os.path.join(species_folder, file_name)
59
+ wav_path = os.path.join(species_folder, file_name.replace('.mp3', '.wav'))
60
+ convert_mp3_to_wav(mp3_path, wav_path)
61
+ os.remove(mp3_path)
62
+ for species in species_folders:
63
+ species_folder = os.path.join(dataset_path, species)
64
+ for file_name in os.listdir(species_folder):
65
+ if file_name.endswith('.wav'):
66
+ wav_path = os.path.join(species_folder, file_name)
67
+ preprocess_audio(wav_path, wav_path)
68
+ return "Audio processing completed."
69
+
70
+ def convert_mp3_to_wav(input_path, output_path):
71
+ audio = AudioSegment.from_mp3(input_path)
72
+ audio.export(output_path, format="wav")
73
+
74
+ def preprocess_audio(input_path, output_path, sample_rate=22050):
75
+ y, sr = librosa.load(input_path, sr=sample_rate)
76
+ y_trimmed, _ = librosa.effects.trim(y)
77
+ y_normalized = librosa.util.normalize(y_trimmed)
78
+ sf.write(output_path, y_normalized, sample_rate)
79
+
80
+ def data_augmentation(pitch_shifting, time_stretching, background_noise):
81
+ for species in species_folders:
82
+ species_folder = os.path.join(dataset_path, species)
83
+ if pitch_shifting:
84
+ apply_pitch_shift(species_folder)
85
+ if time_stretching:
86
+ apply_time_stretch(species_folder)
87
+ if background_noise:
88
+ apply_background_noise(species_folder)
89
+ return "Data augmentation completed."
90
+
91
+ def apply_pitch_shift(species_folder):
92
+ for file_name in os.listdir(species_folder):
93
+ if file_name.endswith('.wav'):
94
+ wav_path = os.path.join(species_folder, file_name)
95
+ y, sr = librosa.load(wav_path, sr=None)
96
+ y_shifted = librosa.effects.pitch_shift(y, sr, n_steps=2)
97
+ shifted_path = wav_path.replace('.wav', '_pitch_shifted.wav')
98
+ sf.write(shifted_path, y_shifted, sr)
99
+
100
+ def apply_time_stretch(species_folder):
101
+ for file_name in os.listdir(species_folder):
102
+ if file_name.endswith('.wav'):
103
+ wav_path = os.path.join(species_folder, file_name)
104
+ y, sr = librosa.load(wav_path, sr=None)
105
+ y_stretched = librosa.effects.time_stretch(y, rate=1.2)
106
+ stretched_path = wav_path.replace('.wav', '_time_stretched.wav')
107
+ sf.write(stretched_path, y_stretched, sr)
108
+
109
+ def apply_background_noise(species_folder):
110
+ for file_name in os.listdir(species_folder):
111
+ if file_name.endswith('.wav'):
112
+ wav_path = os.path.join(species_folder, file_name)
113
+ y, sr = librosa.load(wav_path, sr=None)
114
+ noise = np.random.randn(len(y))
115
+ y_noisy = y + 0.005 * noise
116
+ noisy_path = wav_path.replace('.wav', '_noisy.wav')
117
+ sf.write(noisy_path, y_noisy, sr)
118
+
119
+ def feature_extraction(feature_type):
120
+ output_folder = f'path_to_output_{feature_type.lower()}'
121
+ if feature_type == 'MFCC':
122
+ extract_features = extract_mfcc
123
+ elif feature_type == 'Spectrogram':
124
+ extract_features = extract_spectrogram
125
+ elif feature_type == 'Chroma':
126
+ extract_features = extract_chroma_features
127
+
128
+ for species in species_folders:
129
+ species_folder = os.path.join(dataset_path, species)
130
+ species_output_folder = os.path.join(output_folder, species)
131
+ extract_features(species_folder, species_output_folder)
132
+
133
+ return f"{feature_type} features extracted and saved."
134
+
135
+ def extract_mfcc(species_folder, output_folder):
136
+ if not os.path.exists(output_folder):
137
+ os.makedirs(output_folder)
138
+ for file_name in os.listdir(species_folder):
139
+ if file_name.endswith('.wav'):
140
+ wav_path = os.path.join(species_folder, file_name)
141
+ y, sr = librosa.load(wav_path, sr=None)
142
+ mfccs = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13)
143
+ feature_path = os.path.join(output_folder, file_name.replace('.wav', '.npy'))
144
+ np.save(feature_path, mfccs)
145
+
146
+ def extract_spectrogram(species_folder, output_folder):
147
+ if not os.path.exists(output_folder):
148
+ os.makedirs(output_folder)
149
+ for file_name in os.listdir(species_folder):
150
+ if file_name.endswith('.wav'):
151
+ wav_path = os.path.join(species_folder, file_name)
152
+ y, sr = librosa.load(wav_path, sr=None)
153
+ S = librosa.feature.melspectrogram(y=y, sr=sr)
154
+ S_DB = librosa.power_to_db(S, ref=np.max)
155
+ feature_path = os.path.join(output_folder, file_name.replace('.wav', '.npy'))
156
+ np.save(feature_path, S_DB)
157
+
158
+ def extract_chroma_features(species_folder, output_folder):
159
+ if not os.path.exists(output_folder):
160
+ os.makedirs(output_folder)
161
+ for file_name in os.listdir(species_folder):
162
+ if file_name.endswith('.wav'):
163
+ wav_path = os.path.join(species_folder, file_name)
164
+ y, sr = librosa.load(wav_path, sr=None)
165
+ chroma = librosa.feature.chroma_stft(y=y, sr=sr)
166
+ feature_path = os.path.join(output_folder, file_name.replace('.wav', '_chroma.npy'))
167
+ np.save(feature_path, chroma)
168
+
169
+ def load_features_and_labels(feature_folder):
170
+ X = []
171
+ y = []
172
+ species_list = os.listdir(feature_folder)
173
+ for species in species_list:
174
+ species_folder = os.path.join(feature_folder, species)
175
+ for file_name in os.listdir(species_folder):
176
+ if file_name.endswith('.npy'):
177
+ feature_path = os.path.join(species_folder, file_name)
178
+ features = np.load(feature_path)
179
+ X.append(features)
180
+ y.append(species)
181
+ return np.array(X), np.array(y)
182
+
183
+ def build_model(model_type, feature_type):
184
+ global X_train, X_test, y_train, y_test, label_encoder, model
185
+ feature_folder = f'path_to_output_{feature_type.lower()}'
186
+ X, y = load_features_and_labels(feature_folder)
187
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
188
+ label_encoder = LabelEncoder()
189
+ y_train_encoded = label_encoder.fit_transform(y_train)
190
+ y_test_encoded = label_encoder.transform(y_test)
191
+ y_train_categorical = to_categorical(y_train_encoded)
192
+ y_test_categorical = to_categorical(y_test_encoded)
193
+ np.save('classes.npy', label_encoder.classes_)
194
+ X_train_reshaped = np.stack([np.repeat(x[..., np.newaxis], 3, axis=-1) for x in X_train])
195
+ X_test_reshaped = np.stack([np.repeat(x[..., np.newaxis], 3, axis=-1) for x in X_test])
196
+
197
+ if model_type == 'ResNet50':
198
+ input_tensor = Input(shape=(X_train.shape[1], X_train.shape[2], 3))
199
+ base_model = ResNet50(include_top=False, weights='imagenet', input_tensor=input_tensor)
200
+ x = Flatten()(base_model.output)
201
+ x = Dense(128, activation='relu')(x)
202
+ x = Dropout(0.3)(x)
203
+ output_tensor = Dense(len(label_encoder.classes_), activation='softmax')(x)
204
+ model = Model(inputs=input_tensor, outputs=output_tensor)
205
+ else:
206
+ model = Sequential([
207
+ Conv2D(32, (3, 3), activation='relu', input_shape=(X_train.shape[1], X_train.shape[2], 3)),
208
+ MaxPooling2D((2, 2)),
209
+ Dropout(0.3),
210
+ Conv2D(64, (3, 3), activation='relu'),
211
+ MaxPooling2D((2, 2)),
212
+ Dropout(0.3),
213
+ Flatten(),
214
+ Dense(128, activation='relu'),
215
+ Dropout(0.3),
216
+ Dense(len(label_encoder.classes_), activation='softmax')
217
+ ])
218
+
219
+ model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
220
+ model.summary()
221
+ return "Model built."
222
+
223
+ def train_model():
224
+ global history
225
+ history = model.fit(X_train_reshaped, y_train_categorical, epochs=30, batch_size=32, validation_data=(X_test_reshaped, y_test_categorical))
226
+ model.save('bird_species_model.h5')
227
+ return "Model training completed and saved as 'bird_species_model.h5'."
228
+
229
+ def evaluate_model():
230
+ test_loss, test_accuracy = model.evaluate(X_test_reshaped, y_test_categorical)
231
+ y_pred = model.predict(X_test_reshaped)
232
+ y_pred_classes = np.argmax(y_pred, axis=1)
233
+ y_true_classes = np.argmax(y_test_categorical, axis=1)
234
+ report = classification_report(y_true_classes, y_pred_classes, target_names=label_encoder.classes_)
235
+ conf_matrix = confusion_matrix(y_true_classes, y_pred_classes)
236
+ plt.figure(figsize=(12, 8))
237
+ sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues', xticklabels=label_encoder.classes_, yticklabels=label_encoder.classes_)
238
+ plt.xlabel('Predicted Label')
239
+ plt.ylabel('True Label')
240
+ plt.title('Confusion Matrix')
241
+ plt.show()
242
+ return f"Test Loss: {test_loss}\nTest Accuracy: {test_accuracy}\n\nClassification Report:\n{report}"
243
+
244
+ def hyperparameter_tuning():
245
+ global history
246
+ reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5, min_lr=0.001)
247
+ history = model.fit(X_train_reshaped, y_train_categorical, epochs=50, batch_size=32, validation_data=(X_test_reshaped, y_test_categorical), callbacks=[reduce_lr])
248
+ model.save('bird_species_model_fine_tuned_v1.h5')
249
+ return "Model hyperparameter tuning completed and saved as 'bird_species_model_fine_tuned_v1.h5'."
250
+
251
+ def learning_rate_reduction():
252
+ global history
253
+ reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5, min_lr=0.001)
254
+ history = model.fit(X_train_reshaped, y_train_categorical, epochs=50, batch_size=32, validation_data=(X_test_reshaped, y_test_categorical), callbacks=[reduce_lr])
255
+ model.save('bird_species_model_fine_tuned_v2.h5')
256
+ return "Model learning rate reduction completed and saved as 'bird_species_model_fine_tuned_v2.h5'."
257
+
258
+ def evaluate_fine_tuned_models():
259
+ model_v1 = load_model('bird_species_model_fine_tuned_v1.h5')
260
+ model_v2 = load_model('bird_species_model_fine_tuned_v2.h5')
261
+
262
+ test_loss_v1, test_accuracy_v1 = model_v1.evaluate(X_test_reshaped, y_test_categorical)
263
+ y_pred_v1 = model_v1.predict(X_test_reshaped)
264
+ y_pred_classes_v1 = np.argmax(y_pred_v1, axis=1)
265
+ y_true_classes_v1 = np.argmax(y_test_categorical, axis=1)
266
+ report_v1 = classification_report(y_true_classes_v1, y_pred_classes_v1, target_names=label_encoder.classes_)
267
+
268
+ test_loss_v2, test_accuracy_v2 = model_v2.evaluate(X_test_reshaped, y_test_categorical)
269
+ y_pred_v2 = model_v2.predict(X_test_reshaped)
270
+ y_pred_classes_v2 = np.argmax(y_pred_v2, axis=1)
271
+ y_true_classes_v2 = np.argmax(y_test_categorical, axis=1)
272
+ report_v2 = classification_report(y_true_classes_v2, y_pred_classes_v2, target_names=label_encoder.classes_)
273
+
274
+ return f"Fine-Tuned Model V1:\nTest Loss: {test_loss_v1}\nTest Accuracy: {test_accuracy_v1}\n\nClassification Report:\n{report_v1}\n\n" \
275
+ f"Fine-Tuned Model V2:\nTest Loss: {test_loss_v2}\nTest Accuracy: {test_accuracy_v2}\n\nClassification Report:\n{report_v2}"
276
+
277
+ # Gradio UI
278
+ with gr.Blocks() as demo:
279
+ with gr.Row():
280
+ dataset_path_input = gr.Textbox(label="Dataset Path")
281
+ data_exploration_output = gr.Textbox(label="Data Exploration Output")
282
+ with gr.Row():
283
+ audio_processing_button = gr.Button("Perform Audio Processing")
284
+ with gr.Row():
285
+ pitch_shifting_checkbox = gr.Checkbox(label="Enable Pitch Shifting")
286
+ time_stretching_checkbox = gr.Checkbox(label="Enable Time Stretching")
287
+ background_noise_checkbox = gr.Checkbox(label="Enable Background Noise")
288
+ data_augmentation_button = gr.Button("Perform Data Augmentation")
289
+ with gr.Row():
290
+ feature_extraction_radio = gr.Radio(["MFCC", "Spectrogram", "Chroma"], label="Feature Extraction")
291
+ feature_extraction_button = gr.Button("Perform Feature Extraction")
292
+ with gr.Row():
293
+ model_type_radio = gr.Radio(["ResNet50", "CNN"], label="Model Type")
294
+ build_model_button = gr.Button("Build Model")
295
+ with gr.Row():
296
+ train_model_button = gr.Button("Train and Save Model")
297
+ evaluate_model_button = gr.Button("Evaluate Model")
298
+ with gr.Row():
299
+ hyperparameter_tuning_button = gr.Button("Hyperparameter Tuning")
300
+ learning_rate_reduction_button = gr.Button("Learning Rate Reduction")
301
+ with gr.Row():
302
+ evaluate_fine_tuned_models_button = gr.Button("Evaluate Fine-Tuned Models")
303
+
304
+ dataset_path_input.change(data_exploration, inputs=dataset_path_input, outputs=data_exploration_output)
305
+ audio_processing_button.click(audio_processing, outputs=None)
306
+ data_augmentation_button.click(data_augmentation, inputs=[pitch_shifting_checkbox, time_stretching_checkbox, background_noise_checkbox], outputs=None)
307
+ feature_extraction_button.click(feature_extraction, inputs=feature_extraction_radio, outputs=None)
308
+ build_model_button.click(build_model, inputs=[model_type_radio, feature_extraction_radio], outputs=None)
309
+ train_model_button.click(train_model, outputs=None)
310
+ evaluate_model_button.click(evaluate_model, outputs=None)
311
+ hyperparameter_tuning_button.click(hyperparameter_tuning, outputs=None)
312
+ learning_rate_reduction_button.click(learning_rate_reduction, outputs=None)
313
+ evaluate_fine_tuned_models_button.click(evaluate_fine_tuned_models, outputs=None)
314
+
315
+ demo.launch()