# utils/feature_extractor.py
import librosa
import numpy as np
def extract_features(file_path):
y, sr = librosa.load(file_path, duration=30)
mfccs = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40)
mfccs_mean = np.mean(mfccs.T, axis=0)
return mfccs_mean
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
import pandas as pd
import joblib
# Load features (extracted previously)
df = pd.read_csv("features_dataset.csv") # Your dataset with MFCC + genre
X = df.drop('genre', axis=1)
y = df['genre']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
clf = RandomForestClassifier()
clf.fit(X_train, y_train)
# Save model
joblib.dump(clf, "model/genre_model.pkl")
# app.py
import streamlit as st
import joblib
import numpy as np
from utils.feature_extractor import extract_features
import tempfile
# Load model
model = joblib.load("model/genre_model.pkl")
st.title("🎵 Music Genre Classifier")
st.write("Upload a music file to predict its genre")
uploaded_file = st.file_uploader("Choose a file", type=["mp3", "wav"])
if uploaded_file:
# Save temporarily
with tempfile.NamedTemporaryFile(delete=False) as tmp:
tmp.write(uploaded_file.read())
tmp_path = tmp.name
# Extract features and predict
features = extract_features(tmp_path)
prediction = model.predict([features])[0]
proba = model.predict_proba([features])
st.success(f"Predicted Genre: **{prediction}**")
st.bar_chart(proba[0])
No comments:
Post a Comment