GouthamVarma commited on
Commit
e803c5d
1 Parent(s): 9bf2b1d

initial commit

Browse files
Files changed (1) hide show
  1. app.py +147 -0
app.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Convert the relevant parts of your notebook into a Python script
2
+ import numpy as np
3
+ import pandas as pd
4
+ from sklearn.metrics.pairwise import cosine_similarity
5
+ import gradio as gr
6
+
7
+ # Load the data
8
+ df = pd.read_csv('song_dataset.csv')
9
+
10
+ # Create user-song matrix
11
+ interaction_matrix = df.pivot_table(
12
+ index='user',
13
+ columns='song',
14
+ values='play_count',
15
+ fill_value=0
16
+ )
17
+
18
+ def search_songs(query):
19
+ if not query or len(query) < 2:
20
+ return gr.update(choices=[])
21
+ try:
22
+ matches = song_choices[
23
+ song_choices['display'].str.lower().str.contains(query.lower(), regex=False)
24
+ ]['display'].tolist()
25
+ return gr.update(choices=matches[:10])
26
+ except Exception as e:
27
+ print(f"Search error: {e}")
28
+ return gr.update(choices=[])
29
+
30
+ def add_to_selection(new_song, current_selections):
31
+ if not current_selections:
32
+ current_selections = []
33
+
34
+ if new_song and new_song not in current_selections and len(current_selections) < 5:
35
+ current_selections.append(new_song)
36
+
37
+ return gr.update(choices=current_selections, value=current_selections)
38
+
39
+ def make_recommendations(selected_songs, n_recommendations=5):
40
+ if not selected_songs:
41
+ return "Please select at least one song to get recommendations."
42
+
43
+ temp_user_profile = pd.Series(0, index=interaction_matrix.columns)
44
+ for song in selected_songs:
45
+ song_id = song_choices[song_choices['display'] == song]['song'].iloc[0]
46
+ temp_user_profile[song_id] = 1
47
+
48
+ user_sim = cosine_similarity([temp_user_profile], interaction_matrix)[0]
49
+
50
+ unheard_songs = list(set(interaction_matrix.columns) -
51
+ set([song_choices[song_choices['display'] == song]['song'].iloc[0]
52
+ for song in selected_songs]))
53
+
54
+ pred_ratings = []
55
+ for song in unheard_songs:
56
+ pred = np.sum(user_sim * interaction_matrix[song]) / np.sum(np.abs(user_sim))
57
+ pred_ratings.append((song, pred))
58
+
59
+ ratings = np.array([r[1] for r in pred_ratings])
60
+ if len(ratings) > 0:
61
+ min_rating, max_rating = ratings.min(), ratings.max()
62
+ if max_rating > min_rating:
63
+ normalized_ratings = 1 + 4 * (ratings - min_rating) / (max_rating - min_rating)
64
+ else:
65
+ normalized_ratings = [3.0] * len(ratings)
66
+ else:
67
+ return "No recommendations found for the selected songs."
68
+
69
+ recommendations = list(zip([r[0] for r in pred_ratings], normalized_ratings))
70
+ recommendations = sorted(recommendations, key=lambda x: x[1], reverse=True)[:n_recommendations]
71
+
72
+ output = ""
73
+ for song_id, rating in recommendations:
74
+ song_details = df[df['song'] == song_id].iloc[0]
75
+ output += f"Title: {song_details['title']}\n"
76
+ output += f"Artist: {song_details['artist_name']}\n"
77
+ output += f"Year: {song_details['year']}\n"
78
+ output += f"Rating: {rating:.2f}/5.00\n"
79
+ output += "-" * 50 + "\n"
80
+
81
+ return output
82
+
83
+ # Create song choices for dropdown
84
+ song_choices = df[['song', 'title', 'artist_name']].drop_duplicates()
85
+ song_choices['display'] = song_choices['title'] + " - " + song_choices['artist_name']
86
+ song_list = song_choices['display'].tolist()
87
+
88
+ # Create Gradio interface
89
+ with gr.Blocks(title="Wanna Be Spotify") as iface:
90
+ gr.Markdown("# 🎵 Wanna Be Spotify")
91
+ gr.Markdown("Search and select up to 5 songs you've enjoyed to get personalized recommendations!")
92
+
93
+ with gr.Row():
94
+ search_box = gr.Textbox(
95
+ label="Search for songs",
96
+ placeholder="Type song or artist name...",
97
+ show_label=True
98
+ )
99
+
100
+ with gr.Row():
101
+ search_results = gr.Radio(
102
+ choices=[],
103
+ label="Search Results",
104
+ interactive=True,
105
+ show_label=True
106
+ )
107
+
108
+ with gr.Row():
109
+ selected_songs = gr.Dropdown(
110
+ choices=[],
111
+ label="Selected Songs",
112
+ interactive=True,
113
+ multiselect=True,
114
+ max_choices=5,
115
+ show_label=True
116
+ )
117
+
118
+ with gr.Row():
119
+ recommendations = gr.Textbox(
120
+ label="Recommendations",
121
+ interactive=False,
122
+ lines=10,
123
+ show_label=True
124
+ )
125
+
126
+ submit_btn = gr.Button("Get Recommendations")
127
+
128
+ search_box.change(
129
+ fn=search_songs,
130
+ inputs=[search_box],
131
+ outputs=[search_results]
132
+ )
133
+
134
+ search_results.change(
135
+ fn=add_to_selection,
136
+ inputs=[search_results, selected_songs],
137
+ outputs=[selected_songs]
138
+ )
139
+
140
+ submit_btn.click(
141
+ fn=make_recommendations,
142
+ inputs=[selected_songs],
143
+ outputs=[recommendations]
144
+ )
145
+
146
+ # Launch the interface
147
+ iface.launch()