import streamlit as st import joblib import pandas as pd import os # Operating system module for path manipulation # Define the directory where the models are stored # File Names MODEL_FILENAME = 'src/music_model.joblib' SCALER_FILENAME = 'src/music_scaler.joblib' # --- Load Saved Models --- try: # Use os.path.join to create the correct file paths loaded_model = joblib.load(MODEL_FILENAME) loaded_scaler = joblib.load(SCALER_FILENAME) except FileNotFoundError: st.error(f"Model or Scaler files not found! Please ensure 'music_model.joblib' and 'music_scaler.joblib' are located in the '{MODEL_DIR}' directory.") st.stop() except Exception as e: st.error(f"An error occurred while loading the models: {e}") st.stop() # --- Streamlit Interface --- st.title("🎧 Music Clustering Prediction App") st.markdown("Enter the song's audio features to see which music segment it belongs to!") # Get User Input (Ensure the feature names match the training data order) st.subheader("Enter Song Audio Features:") bpm = st.slider("Beats Per Minute (BPM)", min_value=50, max_value=200, value=120) loudness = st.slider("Loudness (dB)", min_value=-20.0, max_value=0.0, value=-5.0, format="%.2f") liveness = st.slider("Liveness", min_value=0.0, max_value=1.0, value=0.5, format="%.2f") valence = st.slider("Valence (Positivity/Cheerfulness)", min_value=0.0, max_value=1.0, value=0.6, format="%.2f") acousticness = st.slider("Acousticness", min_value=0.0, max_value=1.0, value=0.2, format="%.2f") speechiness = st.slider("Speechiness", min_value=0.0, max_value=1.0, value=0.1, format="%.2f") # Define feature names in the exact order used during training/scaling FEATURE_NAMES = ['Beats Per Minute (BPM)', 'Loudness (dB)', 'Liveness', 'Valence', 'Acousticness', 'Speechiness'] if st.button('Perform Cluster Prediction'): # 1. Convert inputs into a DataFrame new_data = pd.DataFrame([[bpm, loudness, liveness, valence, acousticness, speechiness]], columns=FEATURE_NAMES) # 2. Transform the new data using the loaded scaler scaled_new_data = loaded_scaler.transform(new_data) # 3. Make the prediction using the model prediction = loaded_model.predict(scaled_new_data) # 4. Display the result st.success(f"Based on its audio characteristics, this song belongs to **Cluster {prediction[0]}**!")