Certainly! This is an elaborate task that involves multiple steps, from data preprocessing to model training and finally evaluation. Below is a step-by-step guide to achieve the desired goal focusing on Python and using tools like TensorFlow and Keras for the model and libraries like Matplotlib and Tkinter for GUI.
Step 1: Convert Audio Files to Spectrograms
import os
import librosa
import numpy as np
import matplotlib.pyplot as plt
def audio_to_spectrogram(audio_path, output_path):
y, sr = librosa.load(audio_path, sr=None)
# Convert audio signal to Mel-Spectrogram
spect = librosa.feature.melspectrogram(y=y, sr=sr)
# Convert to log scale (dB)
spect_db = librosa.power_to_db(spect, ref=np.max)
plt.figure(figsize=(10, 4))
librosa.display.specshow(spect_db, sr=sr, x_axis='time', y_axis='mel')
plt.colorbar(format='%+2.0f dB')
plt.tight_layout()
plt.savefig(output_path)
plt.close()
input_folder = "path_to_your_audio_classes"
output_folder = "path_to_your_spectrogram_classes"
for speaker_class in os.listdir(input_folder):
class_folder = os.path.join(input_folder, speaker_class)
output_class_folder = os.path.join(output_folder, speaker_class)
os.makedirs(output_class_folder, exist_ok=True)
for audio_file in os.listdir(class_folder):
audio_path = os.path.join(class_folder, audio_file)
spect_output_path = os.path.join(output_class_folder, audio_file.replace('.wav', '.png'))
audio_to_spectrogram(audio_path, spect_output_path)
Step 2: Split Dataset into Train/Validation/Test Folders
from sklearn.model_selection import train_test_split
import shutil
def split_data(input_folder, output_folder, train_ratio=0.7, val_ratio=0.2, test_ratio=0.1):
assert train_ratio + val_ratio + test_ratio == 1.0, "Ratios must sum to 1"
def move_files(files, src_folder, dst_folder):
for f in files:
os.makedirs(dst_folder, exist_ok=True)
shutil.copy(os.path.join(src_folder, f), dst_folder)
for speaker_class in os.listdir(input_folder):
class_folder = os.path.join(input_folder, speaker_class)
files = os.listdir(class_folder)
train_files, test_files = train_test_split(files, test_size=(1-train_ratio))
val_files, test_files = train_test_split(test_files, test_size=(test_ratio / (val_ratio + test_ratio)))
move_files(train_files, class_folder, os.path.join(output_folder, 'train', speaker_class))
move_files(val_files, class_folder, os.path.join(output_folder, 'val', speaker_class))
move_files(test_files, class_folder, os.path.join(output_folder, 'test', speaker_class))
input_folder = "path_to_your_spectrogram_classes"
output_folder = "path_to_your_split_data"
split_data(input_folder, output_folder)
Step 3: Data Augmentation and Normalization
from tensorflow.keras.preprocessing.image import ImageDataGenerator
datagen = ImageDataGenerator(
rescale=1./255, # Normalize pixel values
zoom_range=0.2, # Randomly zoom into images
width_shift_range=0.2, # Randomly shift images horizontally (fraction of total width)
height_shift_range=0.2, # Randomly shift images vertically (fraction of total height)
horizontal_flip=True, # Randomly flip images
validation_split=0.2 # Reserve some images for validation
)
train_generator = datagen.flow_from_directory(
'path_to_your_split_data/train',
target_size=(224, 224),
batch_size=32,
class_mode='categorical',
subset='training'
)
validation_generator = datagen.flow_from_directory(
'path_to_your_split_data/val',
target_size=(224, 224),
batch_size=32,
class_mode='categorical',
subset='validation'
)
Step 4: Fine-Tune Pretrained Model
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.optimizers import Adam
base_model = tf.keras.applications.ResNet50(weights='imagenet', include_top=False)
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
predictions = Dense(len(train_generator.class_indices), activation='softmax')(x)
model = Model(inputs=base_model.input, outputs=predictions)
for layer in base_model.layers:
layer.trainable = False
model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(
train_generator,
steps_per_epoch=train_generator.samples // train_generator.batch_size,
validation_data=validation_generator,
validation_steps=validation_generator.samples // validation_generator.batch_size,
epochs=10
)
# Unfreeze and fine-tune
for layer in model.layers[:143]:
layer.trainable = False
for layer in model.layers[143:]:
layer.trainable = True
model.compile(optimizer=Adam(lr=1e-4), loss='categorical_crossentropy', metrics=['accuracy'])
history_finetuned = model.fit(
train_generator,
steps_per_epoch=train_generator.samples // train_generator.batch_size,
validation_data=validation_generator,
validation_steps=validation_generator.samples // validation_generator.batch_size,
epochs=10
)
Step 5: Evaluate Model
test_generator = ImageDataGenerator(rescale=1./255).flow_from_directory(
'path_to_your_split_data/test',
target_size=(224, 224),
batch_size=32,
class_mode='categorical'
)
score = model.evaluate(test_generator, steps=test_generator.samples // test_generator.batch_size)
print(f"Test accuracy: {score[1]*100:.2f}%")
Step 6: Predict and GUI Implementation
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
def predict_speaker(image_path, model, class_indices, threshold=0.5):
img = tf.keras.preprocessing.image.load_img(image_path, target_size=(224, 224))
x = tf.keras.preprocessing.image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = x / 255.0
preds = model.predict(x)
confidence = np.max(preds)
predicted_class = list(class_indices.keys())[np.argmax(preds)]
found = "Found in dataset" if confidence >= threshold else "Not found in dataset"
return predicted_class, confidence, found
def open_file():
file_path = filedialog.askopenfilename()
predicted_class, confidence, found = predict_speaker(file_path, model, test_generator.class_indices)
result.set(f"Class: {predicted_class}\nConfidence: {confidence:.2f}\n{found}")
app = tk.Tk()
app.title("Speaker Recognition")
frame = tk.Frame(app)
frame.pack(pady=20, padx=20)
button = tk.Button(frame, text="Open Image", command=open_file)
button.pack()
result = tk.StringVar()
label = tk.Label(frame, textvariable=result, width=50, height=10)
label.pack()
app.mainloop()
This step-by-step guide includes data preprocessing, augmentation, normalization, model training, fine-tuning, evaluation, and predicting with a GUI to display the results. Adjust paths and parameters as per your specific requirements.