ESMATUGBA commited on
Commit
8b26a6e
·
verified ·
1 Parent(s): db712df

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -141
app.py CHANGED
@@ -1,141 +1,104 @@
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
-
12
- # --------------------------------------
13
- # AUTO PATH (LOCAL + HUGGING FACE)
14
- # --------------------------------------
15
- def get_path(filename):
16
- # Olası tüm konumları kontrol et
17
- base_dirs = [
18
- ".", # çalıştırıldığı klasör
19
- "..", # bir üst klasör
20
- os.path.dirname(os.path.abspath(__file__)), # script klasörü
21
- os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."),
22
- os.getcwd(), # working dir
23
- os.path.join(os.getcwd(), "..")
24
- ]
25
- for d in base_dirs:
26
- path = os.path.join(d, filename)
27
- if os.path.exists(path):
28
- return path
29
- # Eğer bulunamazsa
30
- st.error(f"{filename} bulunamadı! Mevcut dosyalar: {os.listdir()}")
31
- st.stop()
32
-
33
- DATA_PATH = get_path("spotify_clustered.csv")
34
- MODEL_PATH = get_path("kmeans_music_model.pkl")
35
- SCALER_PATH = get_path("scaler_music.pkl")
36
-
37
- # --------------------------------------
38
- # LOAD DATA (CACHE)
39
- # --------------------------------------
40
- @st.cache_data
41
- def load_data():
42
- df = pd.read_csv(DATA_PATH)
43
- unnecessary_cols = ['Unnamed: 0', 'track_id', 'album_name', 'explicit']
44
- df_display = df.drop(columns=[c for c in unnecessary_cols if c in df.columns])
45
- return df, df_display
46
-
47
- @st.cache_resource
48
- def load_model():
49
- model = joblib.load(MODEL_PATH)
50
- scaler = joblib.load(SCALER_PATH)
51
- return model, scaler
52
-
53
- df, df_display = load_data()
54
- model, scaler = load_model()
55
-
56
- # --------------------------------------
57
- # SESSION STATE (NO FLICKER)
58
- # --------------------------------------
59
- if "prediction" not in st.session_state:
60
- st.session_state.prediction = None
61
- st.session_state.samples = None
62
-
63
- # --------------------------------------
64
- # TITLE
65
- # --------------------------------------
66
- st.title("🎵 Spotify Music Clustering / Spotify Müzik Kümeleme")
67
- st.markdown("---")
68
-
69
- # --------------------------------------
70
- # DATA PREVIEW
71
- # --------------------------------------
72
- st.subheader("📄 Dataset Preview / Veri Önizleme")
73
- st.dataframe(df_display.head(10), use_container_width=True)
74
-
75
- # --------------------------------------
76
- # VISUALS
77
- # --------------------------------------
78
- col1, col2 = st.columns(2)
79
-
80
- with col1:
81
- st.subheader("📊 Cluster Distribution / Küme Dağılımı")
82
- st.bar_chart(df['cluster'].value_counts(), use_container_width=True)
83
-
84
- with col2:
85
- st.subheader("🎯 Feature Analysis / Özellik Analizi")
86
- fig, ax = plt.subplots(figsize=(6, 4))
87
- scatter = ax.scatter(df['danceability'], df['energy'], c=df['cluster'], cmap='viridis', alpha=0.6)
88
- ax.set_xlabel("Danceability / Dans Edilebilirlik")
89
- ax.set_ylabel("Energy / Enerji")
90
- plt.colorbar(scatter, ax=ax)
91
- st.pyplot(fig, clear_figure=True)
92
- plt.close(fig)
93
-
94
- # --------------------------------------
95
- # PREDICTION
96
- # --------------------------------------
97
- st.divider()
98
- st.subheader("🤖 Predict New Song Cluster / Yeni Şarkı Tahmini")
99
-
100
- c1, c2, c3 = st.columns(3)
101
- with c1:
102
- pop = st.slider("Popularity / Popülerlik", 0, 100, 50)
103
- dur = st.slider("Duration (ms) / Süre", 0, 600000, 200000)
104
- dance = st.slider("Danceability / Dans Edilebilirlik", 0.0, 1.0, 0.5)
105
- with c2:
106
- energy = st.slider("Energy / Enerji", 0.0, 1.0, 0.5)
107
- loud = st.slider("Loudness / Ses Yüksekliği", -60.0, 0.0, -10.0)
108
- tempo = st.slider("Tempo / Tempo", 0.0, 250.0, 120.0)
109
- with c3:
110
- speech = st.slider("Speechiness / Konuşma Oranı", 0.0, 1.0, 0.1)
111
-
112
- if st.button("Predict Cluster / Kümeyi Tahmin Et ✨"):
113
- new_data = [[pop, dur, dance, energy, loud, tempo, speech]]
114
- try:
115
- new_data_scaled = scaler.transform(new_data)
116
- res = model.predict(new_data_scaled)[0]
117
- st.session_state.prediction = res
118
- st.session_state.samples = df[df['cluster'] == res][['track_name', 'artists']].head(5)
119
- except Exception as e:
120
- st.error(f"Error / Hata: {e}")
121
-
122
- if st.session_state.prediction is not None:
123
- st.success(f"### Predicted Cluster / Tahmin Edilen Küme: {st.session_state.prediction}")
124
- st.write("Similar Songs / Benzer Şarkılar:")
125
- st.table(st.session_state.samples)
126
-
127
- # --------------------------------------
128
- # CLUSTER ANALYSIS
129
- # --------------------------------------
130
- st.divider()
131
- st.subheader("🔍 Cluster Characteristics / Küme Özellikleri")
132
- numeric_only = df.select_dtypes(include=['float64', 'int64'])
133
- if 'cluster' in df.columns:
134
- means = numeric_only.groupby(df['cluster']).mean()
135
- st.dataframe(means, use_container_width=True)
136
-
137
- # --------------------------------------
138
- # DEBUG (Opsiyonel)
139
- # --------------------------------------
140
- # st.write("Current working dir:", os.getcwd())
141
- # st.write("Files here:", os.listdir())
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import joblib
4
+ import matplotlib.pyplot as plt
5
+
6
+ # --------------------------------------
7
+ # 1️⃣ Dosya Yolları
8
+ # --------------------------------------
9
+ DATA_PATH = "spotify_clustered.csv"
10
+ MODEL_PATH = "kmeans_music_model.pkl"
11
+ SCALER_PATH = "scaler_music.pkl"
12
+
13
+ @st.cache_data
14
+ def load_data():
15
+ try:
16
+ df = pd.read_csv(DATA_PATH)
17
+ except FileNotFoundError:
18
+ st.error("spotify_clustered.csv bulunamadı! Lütfen root klasöre yükleyin.")
19
+ st.stop()
20
+ # Gereksiz sütunları kaldır
21
+ unnecessary_cols = ['Unnamed: 0', 'track_id', 'album_name', 'explicit']
22
+ df_display = df.drop(columns=[c for c in unnecessary_cols if c in df.columns])
23
+ return df, df_display
24
+
25
+ # Veri ve model yükle
26
+ df, df_display = load_data()
27
+ model = joblib.load(MODEL_PATH)
28
+ scaler = joblib.load(SCALER_PATH)
29
+
30
+ # --------------------------------------
31
+ # 2️⃣ Sayfa Ayarları
32
+ # --------------------------------------
33
+ st.set_page_config(page_title="Spotify Clusters", layout="wide")
34
+ st.title("🎵 Spotify Music Clustering / Spotify Müzik Kümeleme")
35
+ st.markdown("---")
36
+
37
+ # --------------------------------------
38
+ # 3️⃣ Veri Önizleme
39
+ # --------------------------------------
40
+ st.subheader("📄 Dataset Preview / Veri Önizleme")
41
+ st.dataframe(df_display.head(10), use_container_width=True)
42
+
43
+ # --------------------------------------
44
+ # 4️⃣ Görselleştirme
45
+ # --------------------------------------
46
+ col1, col2 = st.columns(2)
47
+
48
+ with col1:
49
+ st.subheader("📊 Cluster Distribution / Küme Dağılımı")
50
+ st.bar_chart(df['cluster'].value_counts())
51
+
52
+ with col2:
53
+ st.subheader("🎯 Feature Analysis / Özellik Analizi")
54
+ fig, ax = plt.subplots(figsize=(8, 5))
55
+ scatter = ax.scatter(df['danceability'], df['energy'], c=df['cluster'], cmap='viridis', alpha=0.6)
56
+ ax.set_xlabel("Danceability / Dans Edilebilirlik")
57
+ ax.set_ylabel("Energy / Enerji")
58
+ plt.colorbar(scatter, label="Cluster / Küme")
59
+ st.pyplot(fig, clear_figure=True)
60
+ plt.close(fig)
61
+
62
+ # --------------------------------------
63
+ # 5️⃣ Tahmin Bölümü
64
+ # --------------------------------------
65
+ st.divider()
66
+ st.subheader("🤖 Predict New Song Cluster / Yeni Şarkı Tahmini")
67
+ st.info("Adjust sliders to see which cluster a song belongs to / Sürgüleri ayarlayın.")
68
+
69
+ c1, c2, c3 = st.columns(3)
70
+
71
+ with c1:
72
+ pop = st.slider("Popularity / Popülerlik", 0, 100, 50)
73
+ dur = st.slider("Duration (ms) / Süre", 0, 600000, 200000)
74
+ dance = st.slider("Danceability / Dans Edilebilirlik", 0.0, 1.0, 0.5)
75
+
76
+ with c2:
77
+ energy = st.slider("Energy / Enerji", 0.0, 1.0, 0.5)
78
+ loud = st.slider("Loudness / Ses Yüksekliği", -60.0, 0.0, -10.0)
79
+ tempo = st.slider("Tempo / Tempo", 0.0, 250.0, 120.0)
80
+
81
+ with c3:
82
+ speech = st.slider("Speechiness / Konuşma Oranı", 0.0, 1.0, 0.1)
83
+
84
+ if st.button("Predict Cluster / Kümeyi Tahmin Et ✨"):
85
+ new_data = [[pop, dur, dance, energy, loud, tempo, speech]]
86
+ try:
87
+ new_data_scaled = scaler.transform(new_data)
88
+ res = model.predict(new_data_scaled)[0]
89
+ st.success(f"### Predicted Cluster / Tahmin Edilen Küme: {res}")
90
+ st.write("**Similar songs / Bu gruptaki benzer şarkılar:**")
91
+ samples = df[df['cluster'] == res][['track_name', 'artists']].head(5)
92
+ st.table(samples)
93
+ except Exception as e:
94
+ st.error(f"Prediction Error / Tahmin Hatası: {e}")
95
+
96
+ # --------------------------------------
97
+ # 6️⃣ Küme Ortalamaları
98
+ # --------------------------------------
99
+ st.divider()
100
+ st.subheader("🔍 Cluster Characteristics / Küme Özellikleri (Ortalamalar)")
101
+ numeric_only = df.select_dtypes(include=['float64', 'int64'])
102
+ if 'cluster' in df.columns:
103
+ means = numeric_only.groupby(df['cluster']).mean()
104
+ st.dataframe(means, use_container_width=True)