Views
No views yet
.wav audio files, converted to 224x224x3 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/vgg16-sda_gunshot-detection", filename="vgg16_model.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=224, fmax=4000
16 )
17 mel_spectrogram = librosa.power_to_db(mel_spectrogram, ref=np.max)
18 # Normalize
19 spec_min = np.min(mel_spectrogram)
20 spec_max = np.max(mel_spectrogram)
21 if spec_max > spec_min:
22 mel_spectrogram = 255 * (mel_spectrogram - spec_min) / (spec_max - spec_min)
23 else:
24 mel_spectrogram = np.zeros_like(mel_spectrogram)
25 mel_spectrogram = mel_spectrogram.astype(np.float32)
26 # Resize to 224x224
27 mel = tf.image.resize(mel_spectrogram[..., np.newaxis], (224, 224))
28 # Repeat to create 3 channels
29 mel = tf.repeat(mel, 3, axis=-1)
30 # Apply VGG-16 preprocessing
31 mel = tf.keras.applications.vgg16.preprocess_input(mel)
32 return mel
33
34# Example usage
35wav_path = "path/to/your/audio.wav"
36input_data = load_and_preprocess_wav(wav_path)
37input_data = tf.expand_dims(input_data, axis=0) # Add batch dimension
38predictions = model.predict(input_data)
39class_names = ['gunshot', 'background']
40predicted_class = class_names[np.argmax(predictions[0])]
41print(f"Predicted class: {predicted_class}, Probabilities: {predictions[0]}")