Priyanka-Kumavat's picture
Update app.py
51d8727 verified
import streamlit as st
import os
import numpy as np
import librosa
import joblib
from pydub import AudioSegment
# Define a function to load the saved model and make predictions
def predict_anomalies(sample_audio_file, model_filename='isolation_forest_model_advanced.pkl'):
# Load the saved Isolation Forest model using joblib
clf = joblib.load(model_filename)
# Load and extract advanced features from the sample audio file
audio, sample_rate = librosa.load(sample_audio_file, sr=None)
mfccs = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=13)
spectral_contrast = librosa.feature.spectral_contrast(y=audio, sr=sample_rate)
feature = np.hstack((mfccs.mean(axis=1), spectral_contrast.mean(axis=1)))
# Reshape the feature for prediction
feature = feature.reshape(1, -1)
# Predict anomalies using the loaded model
prediction = clf.predict(feature)
# Return the predicted label (0 for normal, 1 for anomaly)
return prediction[0]
# List of sample .wav files
sample_files = {
"Sample 1": "good28.wav",
"Sample 2": "fault35.wav",
"Sample 3": "fault31.wav",
"Sample 4": "good30.wav",
"Sample 5": "fault30.wav",
"Sample 6": "fault32.wav",
"Sample 7": "good29.wav",
}
# Streamlit UI
st.title("Anomaly Detection on Sound Data")
# Description of the model and algorithm
st.write("This app uses an Isolation Forest Model to Detect Anomalies in .wav audio files. Isolation Forest is an unsupervised machine learning algorithm that is particularly effective for anomaly detection in high-dimensional data. It works by isolating anomalies from the majority of normal data points.")
# Sidebar for selecting a sample .wav file
selected_sample = st.sidebar.selectbox("Select a Sample .wav File from the dropdown", list(sample_files.keys()))
# Get the selected sample file path
sample_audio_file = sample_files[selected_sample]
# Button for prediction
predict_button = st.button("Click to Predict Anomalies ")
if predict_button:
# Perform prediction based on the selected sample
result = predict_anomalies(sample_audio_file)
if result == 1:
st.error("Anomaly Detected in Audio file")
else:
st.success("Normal Audio file")
# Play the selected .wav file using pydub
audio = AudioSegment.from_wav(sample_audio_file)
audio.export("temp.wav", format="wav") # Export to a temporary file
st.audio("temp.wav", format="audio/wav")
# Update the sidebar content
st.sidebar.markdown(
"""
**How to Use:** Select a sample .wav file, click the "Predict" button to check for anomalies, and then you can listen to the audio by clicking the play Button.
"""
)