Views
No views yet
.wav audio files, converted to 128x128x3 mel-spectrograms during preprocessing.wav files as input.1import numpy as np
2import tensorflow as tf
3import librosa
4from huggingface_hub import hf_hub_download
5
6# Download the model
7model_path = hf_hub_download(repo_id="ranvir-not-found/resnet50-wda_gunshot-detection", filename="resnet50_wda.keras")
8model = tf.keras.models.load_model(model_path)
9
10# Function to load and preprocess .wav file
11def load_and_preprocess_wav(file_path):
12 # Load and process audio
13 audio_data, sr = librosa.load(file_path, sr=None)
14 mel_spectrogram = librosa.feature.melspectrogram(
15 y=audio_data, sr=sr, n_mels=128, fmax=4000
16 )
17 mel_spectrogram = librosa.power_to_db(mel_spectrogram, ref=np.max)
18 # Resize to 128x128 and add channel axis
19 mel_spectrogram = tf.image.resize(
20 np.expand_dims(mel_spectrogram, axis=-1), (128, 128)
21 )
22 # Convert to 3-channel (RGB)
23 mel_spectrogram = tf.repeat(mel_spectrogram, 3, axis=-1)
24 # Apply ResNet-50 preprocessing
25 mel_spectrogram = tf.keras.applications.resnet50.preprocess_input(mel_spectrogram)
26 return mel_spectrogram
27
28# Example usage
29wav_path = "path/to/your/audio.wav"
30input_data = load_and_preprocess_wav(wav_path)
31input_data = tf.expand_dims(input_data, axis=0) # Add batch dimension
32predictions = model.predict(input_data)
33class_names = ['gunshot', 'background']
34predicted_class = class_names[np.argmax(predictions[0])]
35print(f"Predicted class: {predicted_class}, Probabilities: {predictions[0]}")