Spaces:
Sleeping
Sleeping
File size: 4,979 Bytes
4804242 60029ba 4804242 60029ba | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | import numpy as np
import pandas as pd
import streamlit as st
import joblib
from pathlib import Path
# --------------------------------------------------
# Page config
# --------------------------------------------------
st.set_page_config(
page_title='BPM Predictor (LightGBM)',
page_icon='🎵',
layout='centered'
)
st.title('🎵 BPM Predictor')
st.write('Predict **Beats Per Minute (BPM)** from audio features using a trained **LightGBM** regression model.')
BASE_DIR = Path(__file__).resolve().parent
MODEL_PATH = BASE_DIR / 'lgbm_model.pkl'
FEATURES_PATH = BASE_DIR / 'feature_names.pkl'
# --------------------------------------------------
# Load artifacts
# --------------------------------------------------
@st.cache_resource
def load_artifacts():
if not MODEL_PATH.exists():
raise FileNotFoundError(
f'Model not found: {MODEL_PATH.name}. Put it in the repo root (same folder as app.py).'
)
if not FEATURES_PATH.exists():
raise FileNotFoundError(
f'Feature list not found: {FEATURES_PATH.name}. Put it in the repo root (same folder as app.py).'
)
model = joblib.load(MODEL_PATH)
feature_names = joblib.load(FEATURES_PATH)
if not isinstance(feature_names, list) or len(feature_names) == 0:
raise ValueError('feature_names.pkl must contain a non-empty list of feature names.')
return model, feature_names
model, feature_names = load_artifacts()
# --------------------------------------------------
# Feature engineering (MUST match training)
# --------------------------------------------------
def add_features(df: pd.DataFrame) -> pd.DataFrame:
df = df.copy()
# required base columns
required = [
'RhythmScore', 'AudioLoudness', 'VocalContent', 'AcousticQuality',
'InstrumentalScore', 'LivePerformanceLikelihood', 'MoodScore',
'TrackDurationMs', 'Energy'
]
missing = [c for c in required if c not in df.columns]
if missing:
raise ValueError(f'Missing required base columns: {missing}')
# engineered columns (same as training)
df['Rhythm_Energy'] = df['RhythmScore'] * df['Energy']
df['Mood_Energy'] = df['MoodScore'] * df['Energy']
df['Loudness_Energy'] = df['AudioLoudness'] * df['Energy']
return df
def make_single_row_input(values: dict) -> pd.DataFrame:
df = pd.DataFrame([values])
df = add_features(df)
# align to training columns exactly
missing = [c for c in feature_names if c not in df.columns]
if missing:
raise ValueError(f'Missing engineered columns after feature engineering: {missing}')
extra = [c for c in df.columns if c not in feature_names]
if extra:
df = df.drop(columns=extra)
df = df[feature_names]
return df
# --------------------------------------------------
# UI
# --------------------------------------------------
with st.expander('ℹ️ Model info', expanded=False):
st.write('**Model:** LightGBM Regressor')
st.write('**Target:** BeatsPerMinute')
st.write('**Features:** numeric audio descriptors + interaction features')
st.caption('Note: In this dataset, features show limited predictive signal, so predictions may be close to the mean BPM.')
st.subheader('Enter audio feature values')
col1, col2 = st.columns(2)
with col1:
rhythm = st.slider('RhythmScore', min_value=0.0, max_value=1.0, value=0.6, step=0.001)
energy = st.slider('Energy', min_value=0.0, max_value=1.0, value=0.6, step=0.001)
mood = st.slider('MoodScore', min_value=0.0, max_value=1.0, value=0.6, step=0.001)
live = st.slider('LivePerformanceLikelihood', min_value=0.0, max_value=1.0, value=0.2, step=0.001)
with col2:
loudness = st.number_input('AudioLoudness (dB)', value=-10.0, step=0.1)
vocal = st.slider('VocalContent', min_value=0.0, max_value=1.0, value=0.08, step=0.001)
acoustic = st.slider('AcousticQuality', min_value=0.0, max_value=1.0, value=0.25, step=0.001)
instrumental = st.slider('InstrumentalScore', min_value=0.0, max_value=1.0, value=0.10, step=0.001)
track_ms = st.number_input('TrackDurationMs', value=240000, step=1000, min_value=10000)
input_values = {
'RhythmScore': float(rhythm),
'AudioLoudness': float(loudness),
'VocalContent': float(vocal),
'AcousticQuality': float(acoustic),
'InstrumentalScore': float(instrumental),
'LivePerformanceLikelihood': float(live),
'MoodScore': float(mood),
'TrackDurationMs': float(track_ms),
'Energy': float(energy)
}
st.divider()
if st.button('Predict BPM'):
try:
X = make_single_row_input(input_values)
pred = float(model.predict(X)[0])
st.success(f'Predicted BPM: **{pred:.2f}**')
with st.expander('See model input (after feature engineering)'):
st.dataframe(X)
except Exception as e:
st.error(str(e))
st.caption('Tip: Keep `lgbm_model.pkl` and `feature_names.pkl` in the repo root next to `app.py`.') |