ESMATUGBA commited on
Commit
ad79de0
·
verified ·
1 Parent(s): bb3092a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -141
app.py CHANGED
@@ -1,141 +1,111 @@
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
+ # 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 aynı klasöre 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
+
91
+ if st.button("Predict Cluster / Kümeyi Tahmin Et ✨"):
92
+ new_data = [[pop, dur, dance, energy, loud, tempo, speech]]
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)