-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
187 lines (157 loc) · 7.68 KB
/
app.py
File metadata and controls
187 lines (157 loc) · 7.68 KB
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
"""
Spotify Global Trends Analysis Dashboard.
This module provides a comprehensive Streamlit interface to analyze,
clean, and visualize Spotify track data from 1952 to 2025.
"""
import streamlit as st
import pandas as pd
import os
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
from src.cleaner import SpotifyCleaner
from src.analyzer import SpotifyAnalyzer
from src.visualizer import SpotifyVisualizer
class SpotifyAdvancedDashboard:
"""
Main application class for Spotify data analysis.
This class handles data ingestion, applies custom Spotify-themed CSS,
manages sidebar filters, and renders the multi-tab analysis interface.
"""
def __init__(self):
"""
Initializes the dashboard and sets up the initial page configuration.
"""
st.set_page_config(
page_title="Spotify Global Analysis",
page_icon="🎵",
layout="wide"
)
self.data_path = "data/track_data_final.csv"
self.apply_spotify_theme()
def apply_spotify_theme(_self):
"""
Injects custom CSS into the Streamlit app to apply Spotify's
corporate identity, including dark mode and green highlights.
"""
st.markdown("""
<style>
.main { background-color: #121212; color: #FFFFFF; }
.stMetric {
background-color: #181818;
padding: 15px;
border-radius: 10px;
border-left: 5px solid #1DB954;
}
h1, h2, h3, .stTabs [data-baseweb="tab"] {
color: #1DB954 !important;
}
.stTabs [data-baseweb="tab-list"] { gap: 10px; }
</style>
""", unsafe_allow_html=True)
@st.cache_data
def load_data(_self):
"""
Loads the dataset from a CSV file and performs initial preprocessing.
Returns:
pd.DataFrame: The processed Spotify dataset. Returns None if the file is missing.
"""
# '_self' is used to bypass Streamlit's cache hashing for the class instance.
try:
if not os.path.exists(_self.data_path):
st.error("Data file not found!")
return None
df = pd.read_csv(_self.data_path)
df.columns = df.columns.str.strip()
cleaner = SpotifyCleaner(_self.data_path)
cleaner.df = df
cleaner.clean()
df = cleaner.df
# Selecting year information
if 'album_release_date' in df.columns:
df['release_year'] = pd.to_datetime(df['album_release_date'], errors='coerce').dt.year
df['release_year'] = df['release_year'].fillna(0).astype(int)
if 'explicit' in df.columns:
df['explicit'] = df['explicit'].astype(str)
return df
except Exception as e:
st.error(f"Data loading error: {e}")
return None
def render_sidebar(self, df):
"""
Renders the filtering panel and module status indicators on the sidebar.
Args:
df (pd.DataFrame): The main dataframe used to determine filter ranges.
Returns:
tuple: A tuple containing the selected (year_range, min_popularity).
"""
st.sidebar.image("https://storage.googleapis.com/pr-newsroom-wp/1/2018/11/Spotify_Logo_RGB_Green.png", width=180)
st.sidebar.title("Analysis Filters")
valid_df = df[df['release_year'] > 1950] #Select 1950 and later(Cleans erroneous 0000 data)
min_y = int(valid_df['release_year'].min())
max_y = int(valid_df['release_year'].max())
selected_years = st.sidebar.slider("Year Range", min_y, max_y, (min_y, max_y))
min_pop = st.sidebar.number_input("Popularity Threshold", 50, 100, 50)
return selected_years, min_pop
def run(self):
"""
Executes the main dashboard workflow.
Loads data, applies sidebar filters, and organizes the UI into tabs:
Summary: High-level metrics and data preview.
Trends: Interactive Plotly visualizations.
Statistical Profile: Distribution and outlier plots.
Anomaly: Z-score based track analysis.
"""
st.title("🎵Spotify Global Trends Analysis (1952-2025)")
df = self.load_data()
if df is not None:
years, min_pop = self.render_sidebar(df)
mask = (df['release_year'] >= years[0]) & (df['release_year'] <= years[1]) & (df['track_popularity'] >= min_pop)
filtered_df = df[mask].copy()
tab_main, tab_modern, tab_statistics, tab_anomaly = st.tabs([ "Summary Table", "Interactive Trends", "Statistical Profile", "Anomaly Detection"])
with tab_main:
if not filtered_df.empty:
c1, c2, c3, c4 = st.columns(4)
c1.metric("Number of Songs", len(filtered_df))
c2.metric("Average Popularity", f"{filtered_df['track_popularity'].mean():.1f}")
c3.metric("Popularity Std Dev", f"{filtered_df['track_popularity'].std():.2f}")
explicit_count = (filtered_df['explicit'] == "True").sum()
explicit_ratio = (explicit_count / len(filtered_df)) * 100 if len(filtered_df) > 0 else 0
c4.metric("Explicit Rate", f"%{explicit_ratio:.1f}")
st.subheader("Filtered Data Summary")
st.dataframe(filtered_df.sort_values("release_year").head(100), use_container_width=True)
else:
st.warning("No data was found matching the selected filters.")
with tab_modern:
st.header("Trend Discovery")
try:
viz = SpotifyVisualizer(filtered_df)
st.plotly_chart(viz.plot_modern(), use_container_width=True)
except Exception as e:
st.error(f"Error occurred while loading modern graphics: {e}")
with tab_statistics:
st.header("Data Distribution")
try:
viz = SpotifyVisualizer(filtered_df)
st.pyplot(viz.plot_popularity_distribution())
st.pyplot(viz.plot_popularity_boxplot())
except Exception as e:
st.error(f"Error occurred while loading the graphic:{e}")
with tab_anomaly:
st.header("Anomaly Detection (Z-Score Analysis)")
try:
analyzer = SpotifyAnalyzer(filtered_df)
anomalies = analyzer.detect_anomalies()
if not anomalies.empty:
st.success(f"Analysis Completed: {len(anomalies)} anomalies detected.")
display_cols = ['track_name', 'artist_name', 'track_popularity', 'z_score']
available_cols = [c for c in display_cols if c in anomalies.columns]
st.dataframe(anomalies[available_cols].sort_values(by='z_score', ascending=False), use_container_width=True)
st.caption("Note: Anomalies are tracks with a popularity Z-Score > 3 (statistically significant outliers).")
else:
st.info("No anomalies detected with the current filters and threshold.")
except Exception as e:
st.error(f"Error occurred during anomaly detection: {e}")
if __name__ == "__main__":
app = SpotifyAdvancedDashboard()
app.run()