ESMATUGBA commited on
Commit
a6034bc
·
verified ·
1 Parent(s): 7ec6f4d

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +16 -44
src/streamlit_app.py CHANGED
@@ -2,40 +2,24 @@ 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():
@@ -60,12 +44,6 @@ 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
  # --------------------------------------
@@ -73,7 +51,7 @@ 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
 
@@ -83,7 +61,7 @@ with col1:
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")
@@ -115,9 +93,9 @@ if st.button("Predict Cluster / Kümeyi Tahmin Et ✨"):
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}")
@@ -125,17 +103,11 @@ if st.session_state.prediction is not None:
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())
 
2
  import pandas as pd
3
  import joblib
4
  import matplotlib.pyplot as plt
 
5
 
6
  # --------------------------------------
7
  # PAGE CONFIG
8
  # --------------------------------------
9
  st.set_page_config(page_title="Spotify Clustering", layout="wide")
10
+ st.title("🎵 Spotify Music Clustering / Spotify Müzik Kümeleme")
11
+ st.markdown("---")
12
 
13
  # --------------------------------------
14
+ # FILE PATHS
15
+ # Dosyalar aynı klasörde olduğu için sadece isim yeter
16
+ # --------------------------------------
17
+ DATA_PATH = "spotify_clustered.csv"
18
+ MODEL_PATH = "kmeans_music_model.pkl"
19
+ SCALER_PATH = "scaler_music.pkl"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  # --------------------------------------
22
+ # LOAD DATA & MODEL
23
  # --------------------------------------
24
  @st.cache_data
25
  def load_data():
 
44
  st.session_state.prediction = None
45
  st.session_state.samples = None
46
 
 
 
 
 
 
 
47
  # --------------------------------------
48
  # DATA PREVIEW
49
  # --------------------------------------
 
51
  st.dataframe(df_display.head(10), use_container_width=True)
52
 
53
  # --------------------------------------
54
+ # VISUALIZATIONS
55
  # --------------------------------------
56
  col1, col2 = st.columns(2)
57
 
 
61
 
62
  with col2:
63
  st.subheader("🎯 Feature Analysis / Özellik Analizi")
64
+ fig, ax = plt.subplots(figsize=(6,4))
65
  scatter = ax.scatter(df['danceability'], df['energy'], c=df['cluster'], cmap='viridis', alpha=0.6)
66
  ax.set_xlabel("Danceability / Dans Edilebilirlik")
67
  ax.set_ylabel("Energy / Enerji")
 
93
  new_data_scaled = scaler.transform(new_data)
94
  res = model.predict(new_data_scaled)[0]
95
  st.session_state.prediction = res
96
+ st.session_state.samples = df[df['cluster']==res][['track_name','artists']].head(5)
97
  except Exception as e:
98
+ st.error(f"Prediction Error / Tahmin Hatası: {e}")
99
 
100
  if st.session_state.prediction is not None:
101
  st.success(f"### Predicted Cluster / Tahmin Edilen Küme: {st.session_state.prediction}")
 
103
  st.table(st.session_state.samples)
104
 
105
  # --------------------------------------
106
+ # CLUSTER CHARACTERISTICS
107
  # --------------------------------------
108
  st.divider()
109
  st.subheader("🔍 Cluster Characteristics / Küme Özellikleri")
110
+ numeric_only = df.select_dtypes(include=['float64','int64'])
111
  if 'cluster' in df.columns:
112
  means = numeric_only.groupby(df['cluster']).mean()
113
+ st.dataframe(means, use_container_width=True)