Spaces:
Sleeping
Sleeping
Download src/streamlit_app.py from EnYa32/BeatsPerMinutePrediction: direct link, hf CLI and curl.
- Browser
- Download file 4.98 kB
-
https://huggingface.co/spaces/EnYa32/BeatsPerMinutePrediction/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/EnYa32/BeatsPerMinutePrediction/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/EnYa32/BeatsPerMinutePrediction/resolve/main/src/streamlit_app.py
4.98 kB
| 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 | |
| # -------------------------------------------------- | |
| 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`.') |