Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files
app.py
CHANGED
@@ -3,22 +3,22 @@ import pandas as pd
|
|
3 |
import numpy as np
|
4 |
from sklearn.decomposition import TruncatedSVD
|
5 |
import time
|
6 |
-
from model import MatrixFactorization
|
7 |
|
8 |
try:
|
9 |
-
# Load data
|
10 |
print("Loading data...")
|
11 |
df = pd.read_csv('data.csv')
|
12 |
|
13 |
-
# Initialize model
|
14 |
print("Initializing model...")
|
15 |
mf_recommender = MatrixFactorization(n_factors=100)
|
16 |
mf_recommender.fit(df)
|
17 |
|
18 |
-
# Create interface
|
19 |
print("Creating interface...")
|
20 |
-
demo = mf_recommender
|
21 |
-
demo
|
|
|
|
|
|
|
22 |
|
23 |
except Exception as e:
|
24 |
print(f"Error: {str(e)}")
|
|
|
3 |
import numpy as np
|
4 |
from sklearn.decomposition import TruncatedSVD
|
5 |
import time
|
6 |
+
from model import MatrixFactorization, create_gradio_interface
|
7 |
|
8 |
try:
|
|
|
9 |
print("Loading data...")
|
10 |
df = pd.read_csv('data.csv')
|
11 |
|
|
|
12 |
print("Initializing model...")
|
13 |
mf_recommender = MatrixFactorization(n_factors=100)
|
14 |
mf_recommender.fit(df)
|
15 |
|
|
|
16 |
print("Creating interface...")
|
17 |
+
demo = create_gradio_interface(mf_recommender)
|
18 |
+
if demo is not None:
|
19 |
+
demo.launch(share=False)
|
20 |
+
else:
|
21 |
+
print("Error: Interface creation failed")
|
22 |
|
23 |
except Exception as e:
|
24 |
print(f"Error: {str(e)}")
|
model.py
CHANGED
@@ -17,7 +17,6 @@ class MatrixFactorization:
|
|
17 |
print("Training model...")
|
18 |
start_time = time.time()
|
19 |
|
20 |
-
# Create pivot table and store columns
|
21 |
pivot = pd.pivot_table(
|
22 |
df,
|
23 |
values='play_count',
|
@@ -27,7 +26,6 @@ class MatrixFactorization:
|
|
27 |
)
|
28 |
self.column_names = pivot.columns
|
29 |
|
30 |
-
# Convert to sparse matrix
|
31 |
self.user_title_matrix = csr_matrix(pivot.values)
|
32 |
|
33 |
self.titles_df = df.groupby('title').agg({
|
@@ -44,7 +42,7 @@ class MatrixFactorization:
|
|
44 |
print(f"Matrix shape: {self.user_title_matrix.shape}")
|
45 |
print(f"Explained variance ratio: {self.model.explained_variance_ratio_.sum():.4f}")
|
46 |
|
47 |
-
def
|
48 |
if not selected_titles:
|
49 |
return []
|
50 |
|
@@ -75,8 +73,8 @@ class MatrixFactorization:
|
|
75 |
except Exception as e:
|
76 |
print(f"Error in recommendations: {str(e)}")
|
77 |
return []
|
78 |
-
|
79 |
-
def
|
80 |
title_choices = []
|
81 |
for title, row in self.titles_df.iterrows():
|
82 |
display_text = f"{title} β’ by {row['artist_name']}"
|
@@ -88,39 +86,45 @@ class MatrixFactorization:
|
|
88 |
if extra_info:
|
89 |
display_text += f" [{', '.join(extra_info)}]"
|
90 |
title_choices.append(display_text)
|
|
|
91 |
|
92 |
def create_gradio_interface(mf_model):
|
93 |
-
|
94 |
-
gr.
|
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 |
-
return demo
|
|
|
17 |
print("Training model...")
|
18 |
start_time = time.time()
|
19 |
|
|
|
20 |
pivot = pd.pivot_table(
|
21 |
df,
|
22 |
values='play_count',
|
|
|
26 |
)
|
27 |
self.column_names = pivot.columns
|
28 |
|
|
|
29 |
self.user_title_matrix = csr_matrix(pivot.values)
|
30 |
|
31 |
self.titles_df = df.groupby('title').agg({
|
|
|
42 |
print(f"Matrix shape: {self.user_title_matrix.shape}")
|
43 |
print(f"Explained variance ratio: {self.model.explained_variance_ratio_.sum():.4f}")
|
44 |
|
45 |
+
def get_recommendations_from_titles(self, selected_titles):
|
46 |
if not selected_titles:
|
47 |
return []
|
48 |
|
|
|
73 |
except Exception as e:
|
74 |
print(f"Error in recommendations: {str(e)}")
|
75 |
return []
|
76 |
+
|
77 |
+
def create_title_choices(self):
|
78 |
title_choices = []
|
79 |
for title, row in self.titles_df.iterrows():
|
80 |
display_text = f"{title} β’ by {row['artist_name']}"
|
|
|
86 |
if extra_info:
|
87 |
display_text += f" [{', '.join(extra_info)}]"
|
88 |
title_choices.append(display_text)
|
89 |
+
return title_choices
|
90 |
|
91 |
def create_gradio_interface(mf_model):
|
92 |
+
try:
|
93 |
+
with gr.Blocks() as demo:
|
94 |
+
gr.Markdown("""# π΅ Music Recommendation System πΆ
|
95 |
+
|
96 |
+
### Instructions:
|
97 |
+
1. β³ Given our large corpus, it will take ~1 min to load the model
|
98 |
+
2. π Search songs using title, artist, album, or year
|
99 |
+
3. π§ Select up to 5 songs from the dropdown
|
100 |
+
4. π Click 'Get Recommendations' for similar songs
|
101 |
+
5. π Results show song details with confidence scores (30-100%)
|
102 |
+
""")
|
103 |
+
|
104 |
+
with gr.Row():
|
105 |
+
input_songs = gr.Dropdown(
|
106 |
+
choices=sorted(mf_model.create_title_choices()),
|
107 |
+
label="Search and select songs (up to 5)",
|
108 |
+
info="Format: Title β’ by Artist [Album, Year]",
|
109 |
+
multiselect=True,
|
110 |
+
max_choices=5,
|
111 |
+
filterable=True
|
112 |
+
)
|
113 |
+
|
114 |
+
with gr.Column():
|
115 |
+
recommend_btn = gr.Button("Get Recommendations", size="lg")
|
116 |
+
output_table = gr.DataFrame(
|
117 |
+
headers=["Song", "Artist", "Year", "Confidence"],
|
118 |
+
label="Recommended Songs"
|
119 |
+
)
|
120 |
+
|
121 |
+
recommend_btn.click(
|
122 |
+
fn=mf_model.get_recommendations_from_titles,
|
123 |
+
inputs=input_songs,
|
124 |
+
outputs=output_table
|
125 |
)
|
126 |
|
127 |
+
return demo
|
128 |
+
except Exception as e:
|
129 |
+
print(f"Error creating interface: {str(e)}")
|
130 |
+
return None
|
|
|
|
|
|