ESMATUGBA commited on
Commit
c866602
·
verified ·
1 Parent(s): 32e9a46

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +38 -49
src/streamlit_app.py CHANGED
@@ -1,98 +1,90 @@
 
1
  import streamlit as st
2
  import pandas as pd
3
  import joblib
4
  import matplotlib.pyplot as plt
5
- import os
6
 
7
  # --------------------------------------
8
- # PAGE CONFIG
9
- # --------------------------------------
10
- st.set_page_config(page_title="Spotify Clustering", layout="wide")
11
- st.title("🎵 Spotify Music Clustering / Spotify Müzik Kümeleme")
12
- st.markdown("---")
13
-
14
- # --------------------------------------
15
- # FILE PATHS
16
- # Dosyalar streamlit_app.py ile aynı klasörde olmalı
17
  # --------------------------------------
18
  DATA_PATH = "spotify_clustered.csv"
19
  MODEL_PATH = "kmeans_music_model.pkl"
20
  SCALER_PATH = "scaler_music.pkl"
21
 
22
- # --------------------------------------
23
- # CHECK FILES EXIST
24
- # --------------------------------------
25
- for f in [DATA_PATH, MODEL_PATH, SCALER_PATH]:
26
- if not os.path.exists(f):
27
- st.error(f"{f} bulunamadı! Lütfen aynı klasöre yükleyin.")
28
- st.stop()
29
-
30
- # --------------------------------------
31
- # LOAD DATA & MODEL
32
- # --------------------------------------
33
  @st.cache_data
34
  def load_data():
35
- df = pd.read_csv(DATA_PATH)
 
 
 
 
 
 
36
  unnecessary_cols = ['Unnamed: 0', 'track_id', 'album_name', 'explicit']
37
  df_display = df.drop(columns=[c for c in unnecessary_cols if c in df.columns])
38
  return df, df_display
39
 
40
- @st.cache_resource
41
- def load_model():
42
- model = joblib.load(MODEL_PATH)
43
- scaler = joblib.load(SCALER_PATH)
44
- return model, scaler
45
-
46
  df, df_display = load_data()
47
- model, scaler = load_model()
 
 
 
 
 
48
 
49
  # --------------------------------------
50
- # SESSION STATE (NO FLICKER)
51
  # --------------------------------------
52
- if "prediction" not in st.session_state:
53
- st.session_state.prediction = None
54
- st.session_state.samples = None
55
 
56
  # --------------------------------------
57
- # DATA PREVIEW
58
  # --------------------------------------
59
  st.subheader("📄 Dataset Preview / Veri Önizleme")
 
60
  st.dataframe(df_display.head(10), use_container_width=True)
61
 
62
  # --------------------------------------
63
- # VISUALIZATIONS
64
  # --------------------------------------
65
  col1, col2 = st.columns(2)
66
 
67
  with col1:
68
  st.subheader("📊 Cluster Distribution / Küme Dağılımı")
69
- st.bar_chart(df['cluster'].value_counts(), use_container_width=True)
70
 
71
  with col2:
72
  st.subheader("🎯 Feature Analysis / Özellik Analizi")
73
- fig, ax = plt.subplots(figsize=(6,4))
74
  scatter = ax.scatter(df['danceability'], df['energy'], c=df['cluster'], cmap='viridis', alpha=0.6)
75
  ax.set_xlabel("Danceability / Dans Edilebilirlik")
76
  ax.set_ylabel("Energy / Enerji")
77
- plt.colorbar(scatter, ax=ax)
78
  st.pyplot(fig, clear_figure=True)
79
  plt.close(fig)
80
 
81
  # --------------------------------------
82
- # PREDICTION
83
  # --------------------------------------
84
  st.divider()
85
  st.subheader("🤖 Predict New Song Cluster / Yeni Şarkı Tahmini")
 
86
 
87
  c1, c2, c3 = st.columns(3)
 
88
  with c1:
89
  pop = st.slider("Popularity / Popülerlik", 0, 100, 50)
90
  dur = st.slider("Duration (ms) / Süre", 0, 600000, 200000)
91
  dance = st.slider("Danceability / Dans Edilebilirlik", 0.0, 1.0, 0.5)
 
92
  with c2:
93
  energy = st.slider("Energy / Enerji", 0.0, 1.0, 0.5)
94
  loud = st.slider("Loudness / Ses Yüksekliği", -60.0, 0.0, -10.0)
95
  tempo = st.slider("Tempo / Tempo", 0.0, 250.0, 120.0)
 
96
  with c3:
97
  speech = st.slider("Speechiness / Konuşma Oranı", 0.0, 1.0, 0.1)
98
 
@@ -101,22 +93,19 @@ if st.button("Predict Cluster / Kümeyi Tahmin Et ✨"):
101
  try:
102
  new_data_scaled = scaler.transform(new_data)
103
  res = model.predict(new_data_scaled)[0]
104
- st.session_state.prediction = res
105
- st.session_state.samples = df[df['cluster']==res][['track_name','artists']].head(5)
 
 
106
  except Exception as e:
107
  st.error(f"Prediction Error / Tahmin Hatası: {e}")
108
 
109
- if st.session_state.prediction is not None:
110
- st.success(f"### Predicted Cluster / Tahmin Edilen Küme: {st.session_state.prediction}")
111
- st.write("Similar Songs / Benzer Şarkılar:")
112
- st.table(st.session_state.samples)
113
-
114
  # --------------------------------------
115
- # CLUSTER CHARACTERISTICS
116
  # --------------------------------------
117
  st.divider()
118
- st.subheader("🔍 Cluster Characteristics / Küme Özellikleri")
119
- numeric_only = df.select_dtypes(include=['float64','int64'])
120
  if 'cluster' in df.columns:
121
  means = numeric_only.groupby(df['cluster']).mean()
122
  st.dataframe(means, use_container_width=True)
 
1
+ # src/streamlit_app.py
2
  import streamlit as st
3
  import pandas as pd
4
  import joblib
5
  import matplotlib.pyplot as plt
 
6
 
7
  # --------------------------------------
8
+ # 1️⃣ Load Files & Data Cleaning / Dosyaları Yükle ve Temizle
 
 
 
 
 
 
 
 
9
  # --------------------------------------
10
  DATA_PATH = "spotify_clustered.csv"
11
  MODEL_PATH = "kmeans_music_model.pkl"
12
  SCALER_PATH = "scaler_music.pkl"
13
 
 
 
 
 
 
 
 
 
 
 
 
14
  @st.cache_data
15
  def load_data():
16
+ try:
17
+ df = pd.read_csv(DATA_PATH)
18
+ except FileNotFoundError:
19
+ st.error(f"spotify_clustered.csv bulunamadı! Lütfen src/ klasörüne yükleyin.")
20
+ return None, None
21
+
22
+ # Gereksiz sütunları kaldır
23
  unnecessary_cols = ['Unnamed: 0', 'track_id', 'album_name', 'explicit']
24
  df_display = df.drop(columns=[c for c in unnecessary_cols if c in df.columns])
25
  return df, df_display
26
 
27
+ # Dosyaları yükle
 
 
 
 
 
28
  df, df_display = load_data()
29
+ if df is None:
30
+ st.stop()
31
+
32
+ # Model ve scaler yükle
33
+ model = joblib.load(MODEL_PATH)
34
+ scaler = joblib.load(SCALER_PATH)
35
 
36
  # --------------------------------------
37
+ # 2️⃣ Page Config / Sayfa Ayarları
38
  # --------------------------------------
39
+ st.set_page_config(page_title="Spotify Clusters", layout="wide")
40
+ st.title("🎵 Spotify Music Clustering / Spotify Müzik Kümeleme")
41
+ st.markdown("---")
42
 
43
  # --------------------------------------
44
+ # 3️⃣ Dataset Preview / Veri Önizleme
45
  # --------------------------------------
46
  st.subheader("📄 Dataset Preview / Veri Önizleme")
47
+ st.write("Cleaned data for analysis / Analiz için temizlenmiş veri:")
48
  st.dataframe(df_display.head(10), use_container_width=True)
49
 
50
  # --------------------------------------
51
+ # 4️⃣ Visualizations / Görselleştirmeler
52
  # --------------------------------------
53
  col1, col2 = st.columns(2)
54
 
55
  with col1:
56
  st.subheader("📊 Cluster Distribution / Küme Dağılımı")
57
+ st.bar_chart(df['cluster'].value_counts())
58
 
59
  with col2:
60
  st.subheader("🎯 Feature Analysis / Özellik Analizi")
61
+ fig, ax = plt.subplots(figsize=(8, 5))
62
  scatter = ax.scatter(df['danceability'], df['energy'], c=df['cluster'], cmap='viridis', alpha=0.6)
63
  ax.set_xlabel("Danceability / Dans Edilebilirlik")
64
  ax.set_ylabel("Energy / Enerji")
65
+ plt.colorbar(scatter, label="Cluster / Küme")
66
  st.pyplot(fig, clear_figure=True)
67
  plt.close(fig)
68
 
69
  # --------------------------------------
70
+ # 5️⃣ Prediction Section / Tahmin Bölümü
71
  # --------------------------------------
72
  st.divider()
73
  st.subheader("🤖 Predict New Song Cluster / Yeni Şarkı Tahmini")
74
+ st.info("Adjust the sliders to see which cluster a song belongs to / Şarkının hangi kümeye ait olduğunu görmek için sürgüleri ayarlayın.")
75
 
76
  c1, c2, c3 = st.columns(3)
77
+
78
  with c1:
79
  pop = st.slider("Popularity / Popülerlik", 0, 100, 50)
80
  dur = st.slider("Duration (ms) / Süre", 0, 600000, 200000)
81
  dance = st.slider("Danceability / Dans Edilebilirlik", 0.0, 1.0, 0.5)
82
+
83
  with c2:
84
  energy = st.slider("Energy / Enerji", 0.0, 1.0, 0.5)
85
  loud = st.slider("Loudness / Ses Yüksekliği", -60.0, 0.0, -10.0)
86
  tempo = st.slider("Tempo / Tempo", 0.0, 250.0, 120.0)
87
+
88
  with c3:
89
  speech = st.slider("Speechiness / Konuşma Oranı", 0.0, 1.0, 0.1)
90
 
 
93
  try:
94
  new_data_scaled = scaler.transform(new_data)
95
  res = model.predict(new_data_scaled)[0]
96
+ st.success(f"### Predicted Cluster / Tahmin Edilen Küme: {res}")
97
+ st.write(f"**Similar songs from this group / Bu gruptaki benzer şarkılar:**")
98
+ samples = df[df['cluster'] == res][['track_name', 'artists']].head(5)
99
+ st.table(samples)
100
  except Exception as e:
101
  st.error(f"Prediction Error / Tahmin Hatası: {e}")
102
 
 
 
 
 
 
103
  # --------------------------------------
104
+ # 6️⃣ Cluster Characteristics / Küme Karakteristikleri
105
  # --------------------------------------
106
  st.divider()
107
+ st.subheader("🔍 Cluster Characteristics / Küme Özellikleri (Ortalamalar)")
108
+ numeric_only = df.select_dtypes(include=['float64', 'int64'])
109
  if 'cluster' in df.columns:
110
  means = numeric_only.groupby(df['cluster']).mean()
111
  st.dataframe(means, use_container_width=True)