Spaces:
Sleeping
Sleeping
File size: 14,831 Bytes
cb07dba 926e88f cb07dba a5476de 4e2bf25 cb07dba 4e2bf25 cb07dba 4e2bf25 cb07dba 4e2bf25 cb07dba eb8dd18 4e2bf25 cb07dba 4e2bf25 cb07dba 4e2bf25 cb07dba 4e2bf25 cb07dba 4e2bf25 cb07dba 4e2bf25 cb07dba 4e2bf25 cb07dba 4e2bf25 cb07dba 4e2bf25 cb07dba 4e2bf25 cb07dba 4e2bf25 cb07dba 4e2bf25 cb07dba |
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 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 |
import numpy as np
import pickle
import pandas as pd
import streamlit as st
st.set_page_config(layout="centered", page_title="Predict Music Genre")
# DATA
data = [
{"key": "popularity", "label": "Popularity", "min": 1,
"max": 100, "default": 44, "type": "number", "format": "%1f"},
{"key": "danceability", "label": "Danceability", "min": 0.00,
"max": 1.00, "default": 0.66, "type": "number"},
{"key": "mode", "label": "Mode", "default": 0, "type": "bool"},
{"key": "valence", "label": "Valence", "min": 0.00,
"max": 1.00, "default": 0.48, "type": "number"},
{"key": "speechiness_log", "label": "Speechiness", "min": 0.00,
"max": 1.00, "default": 0.79, "type": "number"},
{"key": "acousticness_log", "label": "Acousticness",
"min": 0.00, "max": 1.00, "default": 0.24, "type": "number"},
{"key": "liveness_log", "label": "Liveness", "min": 0.00,
"max": 1.00, "default": 0.19, "type": "number"},
{"key": "instrumentalness_log", "label": "Instrumentalness",
"min": 0.00, "max": 1.00, "default": 0.17, "type": "number"},
{"key": "duration_in_min_sg_log", "label": "Duration in seg",
"min": 0, "max": 1000000, "default": 317, "type": "number"},
]
response = [
{"label": "Acoustic/Folk", "descripcion": "Acoustic/Folk music emphasizes unplugged instruments like guitars and violins. It often features narrative storytelling and heartfelt lyrics, drawing on traditional sounds and cultural roots. This genre evokes a sense of intimacy and authenticity, focusing on raw musical expression.",
"image": "https://i.pinimg.com/736x/03/80/eb/0380eb05f1ce83ea0f429413f8daebef.jpg"},
{"label": "Alternative Music", "descripcion": "Alternative music emerged from the indie underground, rejecting mainstream rock and pop conventions. It encompasses diverse styles, often characterized by unconventional song structures, experimental sounds, and emotionally charged lyrics. Alt_Music prioritizes artistic expression over commercial appeal.",
"image": "https://i.pinimg.com/736x/87/68/3c/87683cd8c9dafe80b6bd927167efcbaa.jpg"},
{"label": "Blues", "descripcion": "Blues is a foundational genre born from African-American spirituals, work songs, and chants. It's known for its melancholic themes, expressive vocal delivery, and distinctive 12-bar chord progressions. Blues music powerfully conveys feelings of hardship, resilience, and hope.",
"image": "https://i.pinimg.com/736x/69/89/03/6989032f191d50fe98f76a3e7503e79a.jpg"},
{"label": "Bollywood", "descripcion": "Bollywood music is the vibrant soundtrack of Indian cinema, a fusion of traditional Indian melodies with Western pop, folk, and classical influences. It's highly energetic, often featuring elaborate orchestral arrangements, rich vocals, and rhythmic dance numbers. Bollywood music is integral to the storytelling and emotional core of the films.",
"image": "https://i.pinimg.com/736x/6d/d2/f1/6dd2f14df0e77a432df1cd9703a7d3f7.jpg"},
{"label": "Country", "descripcion": "Country music originates from the American South and Southwest, blending folk, blues, and gospel traditions. It typically features themes of rural life, love, loss, and patriotism, often driven by instruments like guitars, banjos, and fiddles. Country music tells relatable stories with a down-to-earth sensibility.",
"image": "https://i.pinimg.com/736x/58/a3/ad/58a3ad5a34925b1735d29c617e4e55d6.jpg"},
{"label": "HipHop",
"descripcion": "HipHop is a cultural movement originating in the Bronx, New York, known for its rhythmic spoken word (rapping) over sampled beats. It incorporates elements of DJing, breakdancing, and graffiti art, serving as a powerful medium for social commentary and storytelling. HipHop is diverse, influential, and constantly evolving.", "image": "https://i.pinimg.com/736x/0f/5e/6d/0f5e6d5466ac7e0b7a99a9aa4df88d89.jpg"},
{"label": "Indie Alternative", "descripcion": "Indie Alternative music emphasizes independent production and distribution, fostering a unique sound distinct from major labels. It often combines raw, DIY aesthetics with experimental sounds and introspective lyrics. This genre celebrates artistic freedom and a non-conformist approach to music creation.",
"image": "https://i.pinimg.com/736x/8c/10/6d/8c106dfea2b51acfad3eaa6d12b886d0.jpg"},
{"label": "Instrumental", "descripcion": "Instrumental music focuses solely on musical instruments without the presence of vocals. It can span any genre, allowing for pure melodic and harmonic exploration. This genre allows listeners to interpret the music based on its sonic qualities and emotional resonance, often used for background or cinematic purposes.",
"image": "https://i.pinimg.com/736x/ce/36/d7/ce36d70c2b71b931bceb7b744f871944.jpg"},
{"label": "Metal", "descripcion": "Metal music is characterized by its aggressive, powerful sound, typically featuring distorted guitars, heavy drumming, and often intense vocals. Subgenres vary widely, but common themes include fantasy, mythology, and social issues. Metal is known for its strong subculture and energetic live performances.",
"image": "https://i.pinimg.com/736x/bd/0c/dc/bd0cdc59569c0bd45876f80ad673ad70.jpg"},
{"label": "Pop", "descripcion": "Pop music is a broad genre characterized by catchy melodies, simple song structures, and widespread appeal. It's designed for mass consumption, often incorporating elements from various genres and focusing on relatable themes like love and everyday life. Pop music is highly commercial and constantly evolving with trends.",
"image": "https://i.pinimg.com/736x/f1/63/5e/f1635e44415b7eb86876ab0d181049b8.jpg"},
{"label": "Rock", "descripcion": "Rock music emerged from blues and country, known for its prominent electric guitar, bass, drums, and often strong vocals. It's a diverse genre encompassing many subgenres, often exploring themes of rebellion, love, and social change. Rock music is celebrated for its energy and cultural impact.",
"image": "https://i.pinimg.com/736x/37/e4/e1/37e4e1add7dbe95fb90b962d015edd26.jpg"},
]
# LOGIC
@st.cache_resource
def load_model(path="./src/xgb_model.pkl"):
try:
with open(path, "rb") as f:
model = pickle.load(f)
return model
except FileNotFoundError:
st.error(
f"Error: Model file not found at {path}. Please ensure the model file is in the directory.")
return None
except Exception as e:
st.error(f"An error occurred while loading the model: {e}")
return None
@st.cache_resource
def load_model_scaler(path="./src/scaler.pkl"):
try:
with open(path, "rb") as f:
return pickle.load(f)
except FileNotFoundError:
st.error(
f"Error: Model file not found at {path}. Please ensure the model file is in the directory.")
return None
except Exception as e:
st.error(f"An error occurred while loading the model: {e}")
return None
model = load_model()
scaler = load_model_scaler()
input_data_original = {}
prediction = -1
datos_bool = []
# VIEW
# Custom CSS for styling
st.markdown("""<style>
.main {
background-color: #1a1a1a;
color: #f0f0f0;
font-family: Arial, sans-serif;
}
.stApp {
background-color: #2a2a2a;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
display: flex;
flex-direction: row;
gap: 30px;
}
.right-panel {
flex: 1.5;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
text-align: center;
}
h1 {
color: #f0f000;
margin-bottom: 25px;
font-size: 2rem !important;
text-align: left;
width: 100%;
}
h2 {
color: #f0f000;
font-size: 1.8em;
margin-bottom: 25px;
text-align: center;
width: 100%;
}
.stTextInput label, .stNumberInput label {
color: #b0b0b0;
font-size: 0.95em;
display: flex;
align-items: center;
}
.stTextInput div[data-baseweb="input"] input, .stNumberInput div[data-baseweb="input"] input {
background-color: #3b3b3b;
border: 1px solid #555;
border-radius: 5px;
color: #f0f0f0;
font-size: 1em;
outline: none;
}
.stButton button {
background-color: #ffd700;
color: #333;
padding: 15px 30px;
border: none;
border-radius: 25px;
font-size: 1.1em;
font-weight: bold;
transition: background-color 0.3s, transform 0.2s;
margin-top: 30px;
align-self: flex-start;
}
.stButton button:hover {
background-color: #e6c200;
transform: translateY(-2px);
}
.image-container {
width: 100%;
height: 250px;
background-color: #333;
border-radius: 8px;
margin-bottom: 30px;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
}
.genre-box {
background-color: #3b3b3b;
padding: 8px 25px;
border-radius: 8px;
width: 80%;
text-align: left;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
width: 100% !important;
}
.genre-box h3 {
color: #ffd700;
margin-top: 0;
margin-bottom: 10px;
font-size: 1.6em;
}
.genre-box p {
color: #c0c0c0;
line-height: 1.6;
font-size: 0.95em;
}
.predicted-genre-title {
color: #ddf4fb !important;
font-size: 1.8em;
margin-bottom: 25px;
}
.disclaimer {
font-size: 0.8em;
color: #888;
margin-top: 20px;
margin-bottom: 30px;
text-align: center;
width: 100%;
}
.stAppHeader {
display: none !important
}
.stMainBlockContainer {
padding: 2rem !important;
max-width: max-content !important;
}
.fixed-height-image-container {
height: 340px;
width: 100%;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
border-radius: 8px;
margin-bottom: 30px;
}
.fixed-height-image-container img {
height: 100%;
width: 100%;
object-fit: contain;
display: block;
}
.max-box {
width: 5000px !important;
}
#predict-music-genre{
color: #ddf4fb !important;
}
#predict-music-genre{
color: #ddf4fb !important;
}
</style>""", unsafe_allow_html=True)
col1, col2 = st.columns([1.5, 4], vertical_alignment="top", )
with col1:
st.markdown('<h1>Predict Music Genre</h1>', unsafe_allow_html=True)
for data_point in data:
if data_point["type"] == "number":
input_data_original[data_point["key"]] = st.number_input(
label=data_point["label"], min_value=data_point["min"], max_value=data_point["max"], value=data_point["default"])
elif data_point["type"] == "bool":
input_data_original[data_point["key"]] = st.checkbox(
label=data_point["label"], value=data_point["default"])
datos_bool.append(data_point["key"])
if st.button("Predict Genre"):
try:
for key in datos_bool:
input_data_original[key] = int(input_data_original[key])
for key in input_data_original:
if 'log' in key:
input_data_original[key] = np.log1p(
input_data_original[key])
input_df_model = pd.DataFrame([input_data_original])
input_df_scaled = scaler.transform(input_df_model)
input_df_model = pd.DataFrame(
input_df_scaled, columns=input_df_model.columns)
prediction = int(model.predict(input_df_model)[0])
except Exception as e:
st.error(f"An error occurred during prediction: {e}")
with col2:
st.markdown('<h2 class="predicted-genre-title">Predicted Genre</h2>',
unsafe_allow_html=True)
if prediction != -1:
st.markdown(f"""
<div class="fixed-height-image-container">
<img src="{response[prediction]["image"]}" alt="Imagen grande">
</div>
""", unsafe_allow_html=True)
st.markdown(f"""
<div class="genre-box">
<h3>{response[prediction]["label"]}</h3>
<p>{response[prediction]["descripcion"]}</p>
<h3>Ejemplos</h3>
<p>Indie Alternative: [Popularity: 50, Danceability: 0.5, Mode: False, Valance: 0.50, Speechines: 0.50, Acousticness: 0.50, Liveness: 0.50, Instrumentalness: 0.50, Duration in seg: 60]</p>
<p>Country: [Popularity: 50, Danceability: 0.5, Mode: True, Valance: 0.50, Speechines: 0.50, Acousticness: 0.50, Liveness: 0.50, Instrumentalness: 0.50, Duration in seg: 60]</p>
<p>Rock: [Popularity: 50, Danceability: 0.5, Mode: True, Valance: 0.50, Speechines: 0.50, Acousticness: 0.50, Liveness: 0.50, Instrumentalness: 0.50, Duration in seg: 1000]</p>
<p>Alternative: [Popularity: 44, Danceability: 0.66, Mode: False, Valance: 0.48, Speechines: 0.79, Acousticness: 0.34, Liveness: 0.19, Instrumentalness: 0.17, Duration in seg: 317]</p>
<p>Pop: [Popularity: 79, Danceability: 0.80, Mode: False, Valance: 0.05, Speechines: 0.79, Acousticness: 0.48, Liveness: 0.03, Instrumentalness: 0.61, Duration in seg: 352]</p>
</div>
""", unsafe_allow_html=True)
else:
st.markdown("""
<div class="genre-box max-box">
<h3>Select values and predict genre</h3>
<h3>Ejemplos</h3>
<p>Indie Alternative: [Popularity: 50, Danceability: 0.5, Mode: False, Valance: 0.50, Speechines: 0.50, Acousticness: 0.50, Liveness: 0.50, Instrumentalness: , Duration in seg: 60]</p>
<p>Country: [Popularity: 50, Danceability: 0.5, Mode: True, Valance: 0.50, Speechines: 0.50, Acousticness: 0.50, Liveness: 0.50, Instrumentalness: 0.50, Duration in seg: 60]</p>
<p>Rock: [Popularity: 50, Danceability: 0.5, Mode: True, Valance: 0.50, Speechines: 0.50, Acousticness: 0.50, Liveness: 0.50, Instrumentalness: 0.50, Duration in seg: 1000]</p>
<p>Alternative: [Popularity: 44, Danceability: 0.66, Mode: False, Valance: 0.48, Speechines: 0.79, Acousticness: 0.34, Liveness: 0.19, Instrumentalness: 0.17, Duration in seg: 317]</p>
<p>Pop: [Popularity: 79, Danceability: 0.80, Mode: False, Valance: 0.05, Speechines: 0.79, Acousticness: 0.48, Liveness: 0.03, Instrumentalness: 0.61, Duration in seg: 352]</p>
</div>
""", unsafe_allow_html=True)
|