Spaces:
Runtime error
Runtime error
File size: 5,721 Bytes
081461b 6e1ba52 081461b 6e1ba52 | 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 | import streamlit as st
import pandas as pd
import numpy as np
"""
# Welcome to Streamlit!
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
forums](https://discuss.streamlit.io).
"""
# --- Helper Functions ---
def mock_predict(lyrics):
"""
Mock prediction function for demo purposes.
In a production environment, this would load a trained .pkl model
(e.g., Logistic Regression or XGBoost) and apply TF-IDF vectorization.
"""
lyrics_lower = lyrics.lower()
if any(word in lyrics_lower for word in ["love", "baby", "heart", "dance"]):
return "Pop"
elif any(word in lyrics_lower for word in ["blood", "death", "kill", "dark"]):
return "Metal"
elif any(word in lyrics_lower for word in ["truck", "beer", "dirt", "whiskey"]):
return "Country"
elif any(word in lyrics_lower for word in ["rhyme", "beat", "flow", "street"]):
return "Hip Hop"
else:
return np.random.choice(["Rock", "Pop", "Indie", "Jazz"])
# --- Main App Configuration ---
st.set_page_config(page_title="Lyric Genre Classifier", page_icon="π΅")
# --- Sidebar Navigation ---
st.sidebar.title("Navigation")
st.sidebar.write("Explore the project:")
page = st.sidebar.radio("Go to", ["Project Overview", "Data Exploration", "Model Results", "Interactive Demo"])
st.sidebar.markdown("---")
st.sidebar.write("**Author:** Data Science Portfolio")
st.sidebar.write("**Tech Stack:** Python, Pandas, Scikit-Learn, XGBoost, Streamlit")
# --- Page 1: Project Overview ---
if page == "Project Overview":
st.title("π΅ Lyric Frequency Genre Classifier")
st.write("""
### Welcome to my project!
This application attempts to classify the musical genre of a song based purely on the text of its lyrics.
By treating lyrics as unstructured text data, we can apply Natural Language Processing (NLP) techniques
like Bag-of-Words and TF-IDF to find patterns in how different genres use vocabulary.
""")
st.markdown("""
**Project Goals:**
* Clean and preprocess thousands of song lyrics.
* Perform Exploratory Data Analysis (EDA) to find distinctive words per genre.
* Train machine learning classification models (Logistic Regression, XGBoost, HistGradientBoosting).
* Evaluate model accuracy and build a simple interface.
""")
st.info("π Use the sidebar to navigate through the data, model results, and try the demo!")
# --- Page 2: Data Exploration ---
elif page == "Data Exploration":
st.title("π Exploratory Data Analysis")
st.write("Before modeling, I explored the dataset to understand the class balance and vocabulary distribution.")
st.subheader("Genre Distribution")
st.write("This chart shows the balance of our target classes across the dataset.")
# Mock data for demonstration purposes
genre_counts = pd.DataFrame({
"Genre": ["Rock", "Pop", "Hip Hop", "Metal", "Country"],
"Song Count": [1250, 1100, 950, 800, 750]
}).set_index("Genre")
st.bar_chart(genre_counts)
st.markdown("---")
st.subheader("Distinctive Words by Genre")
st.write("Using frequency counts and TF-IDF, I identified words that heavily index toward specific genres.")
# Mock top words dataframe
top_words = pd.DataFrame({
"Genre": ["Rock", "Pop", "Hip Hop", "Metal", "Country"],
"Top Distinctive Words": ["guitar, band, night, roll", "love, baby, dance, tonight", "beat, flow, street, money", "death, blood, dark, soul", "truck, whiskey, dirt, road"]
})
st.table(top_words)
# --- Page 3: Model Results ---
elif page == "Model Results":
st.title("π Model Performance")
st.write("""
I experimented with several models to classify the text data.
The primary metrics used for evaluation were Accuracy and F1-Score (due to slight class imbalances).
""")
st.subheader("Classification Metrics")
# Mock metrics dataframe
metrics = pd.DataFrame({
"Model": ["Logistic Regression", "HistGradientBoosting", "XGBoost"],
"Accuracy": [0.72, 0.78, 0.81],
"Weighted F1-Score": [0.71, 0.76, 0.80]
})
st.dataframe(metrics, use_container_width=True, hide_index=True)
st.subheader("Key Takeaways")
st.markdown("""
* **XGBoost** handled the sparse text matrices well but required careful hyperparameter tuning.
* **Logistic Regression** served as a surprisingly strong and interpretable baseline.
* Genres with highly specific jargon (like Metal or Country) were easier to classify than broad categories (like Pop/Rock) which often shared overlapping vocabulary.
""")
# --- Page 4: Interactive Demo ---
elif page == "Interactive Demo":
st.title("π€ Live Genre Predictor")
st.write("Paste some lyrics below to see what genre the model predicts!")
# Input text area
user_lyrics = st.text_area("Enter lyrics here:", height=200, placeholder="e.g., I'm driving my truck down the dirt road...")
if st.button("Predict Genre"):
if user_lyrics.strip() == "":
st.error("Please enter some lyrics first.")
else:
with st.spinner("Analyzing lyric frequencies..."):
# Call mock prediction
prediction = mock_predict(user_lyrics)
st.success(f"**Predicted Genre:** {prediction}")
st.write("*Note: This is a lightweight demo version utilizing a mock predictor. Full model inferences and vectorizers are available in the repository notebooks.*") |