-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmusic_app.py
More file actions
239 lines (177 loc) · 9.33 KB
/
Copy pathmusic_app.py
File metadata and controls
239 lines (177 loc) · 9.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import streamlit as st
import pandas as pd
import numpy as np
import pickle
from sklearn.metrics.pairwise import cosine_similarity
# Page Configuration
st.set_page_config(
page_title="MelodyMind: Hybrid Music Recommender",
page_icon="🎵",
layout="wide",
initial_sidebar_state="expanded"
)
# Load Saved Components
@st.cache_resource
def load_components(filepath='music_recommender_components.pkl'):
"""Loads the saved model components."""
try:
with open(filepath, 'rb') as f:
components = pickle.load(f)
st.success("Model components loaded successfully!", icon="✅")
return components
except FileNotFoundError:
st.error(f"Error: '{filepath}' not found. Please ensure the file is in the same directory as app.py.", icon="❌")
st.stop()
except Exception as e:
st.error(f"Error loading components: {e}", icon="❌")
st.stop()
components = load_components()
# Extract components
lightfm_model = components['lightfm_model']
# scaler = components['scaler']
scaled_features = components['scaled_features']
data_lookup = components['data']
user_encoder = components['user_encoder']
# lightfm_user_id_map = components['lightfm_user_id_map']
original_item_id_map = components['original_item_id_map']
item_id_to_details = components['item_id_to_details']
idx_to_track_name = components['idx_to_track_name']
idx_to_artist_name = components['idx_to_artist_name']
num_items = len(original_item_id_map)
# Helper Functions (Adapted from Notebook)
def get_content_recommendations(track_name, all_features, data_df, idx_to_track, idx_to_artist, num_recommendations=10):
# Generates song recommendations based on content similarity, calculating similarity on-demand using scaled features. Returns a larger list (num_recommendations * 2) for hybrid combining.
matching_indices = data_df[data_df['track_name'] == track_name].index
if not matching_indices.any(): return []
idx = matching_indices[0]
target_features = all_features[idx].reshape(1, -1)
sim_scores_vector = cosine_similarity(target_features, all_features)[0]
sim_scores = list(enumerate(sim_scores_vector))
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
# Get top N similar songs (exclude the track itself)
try:
input_track_sim_index = [i[0] for i in sim_scores].index(idx)
top_indices = [i[0] for i in sim_scores if i[0] != idx][:num_recommendations * 2]
except ValueError:
# Fallback slicing
top_indices = [i[0] for i in sim_scores[1:num_recommendations * 2 + 1]]
return [(idx_to_track.get(i, 'Unknown'), idx_to_artist.get(i, 'Unknown')) for i in top_indices]
def get_lightfm_recommendations(user_id, model, num_recommendations=10):
# Generates recommendations for a given user_id using a trained LightFM model. Returns a larger list (num_recommendations * 2) for hybrid combining.
lightfm_user_id_map = components['lightfm_user_id_map']
if user_id not in lightfm_user_id_map:
st.warning(f"User ID for selected artist not found in LightFM mapping.", icon="⚠️")
return []
internal_user_id = lightfm_user_id_map[user_id]
all_item_indices = np.arange(num_items)
scores = model.predict(internal_user_id, all_item_indices)
# Get top N item indices based on scores
top_internal_item_indices = np.argsort(-scores)[:num_recommendations * 2]
# Map internal item indices back to original item IDs
recommended_item_ids = [original_item_id_map.get(i) for i in top_internal_item_indices]
# Get track details for the recommended item IDs
recommendations = [item_id_to_details.get(item_id) for item_id in recommended_item_ids if item_id is not None and item_id in item_id_to_details]
return recommendations
# This function's logic was already correct for combining and slicing the final output
def hybrid_recommendation(user_id, reference_track_name, num_recommendations=10):
# Generates hybrid recommendations combining content-based and collaborative filtering. Combines results from larger lists and returns the top N unique recommendations.
st.info(f"Generating recommendations for User: **{user_encoder.classes_[user_id]}**, based on track: **'{reference_track_name}'**...", icon="🎧")
# Generate recommendations from both methods (requesting more candidates)
content_recs = get_content_recommendations(
reference_track_name,
scaled_features,
data_lookup,
idx_to_track_name,
idx_to_artist_name,
num_recommendations=num_recommendations # Pass the requested number here, slicing happens inside helper functions
)
collab_recs = get_lightfm_recommendations(user_id, lightfm_model, num_recommendations) # Pass the requested number here
# Combine and deduplicate
combined_recs = {}
for track, artist in collab_recs:
if (track, artist) not in combined_recs:
combined_recs[(track, artist)] = "collab"
for track, artist in content_recs:
if (track, artist) not in combined_recs:
combined_recs[(track, artist)] = "content"
# Convert back to a list of tuples and take the top N unique recommendations
final_recommendations = list(combined_recs.keys())
# This slice ensures we return exactly the requested number (or fewer if not enough unique)
return final_recommendations[:num_recommendations]
# Streamlit UI
st.title("🎧 MelodyMind: Hybrid Music Recommender")
st.markdown("""
Welcome to MelodyMind! This application provides personalized music recommendations
by combining insights from both the audio features of songs (Content-Based Filtering)
and patterns learned from user interactions (Collaborative Filtering).
**Simply select an artist (as a simulated user) and a reference track, and let MelodyMind find new music for you!**
""")
st.divider()
# Sidebar for Input
with st.sidebar:
st.header("Configure Your Recommendations")
available_artists = sorted(list(user_encoder.classes_))
selected_artist = st.selectbox(
"1. Choose an Artist (Simulated User):",
available_artists,
index=available_artists.index('Unknown') if 'Unknown' in available_artists else 0,
help="Select an artist whose listening preferences we'll simulate."
)
tracks_by_selected_artist = data_lookup[data_lookup['primary_artist'] == selected_artist]['track_name'].unique()
if len(tracks_by_selected_artist) > 0:
available_tracks = sorted(list(tracks_by_selected_artist))
selected_track = st.selectbox(
"2. Choose a Reference Track:",
available_tracks,
index=0,
help="Select a track that the system will use as a starting point for content-based similarity."
)
else:
st.warning(f"No tracks found for '{selected_artist}'. Select a different artist or track.", icon="⚠️")
available_tracks = sorted(data_lookup['track_name'].unique())
selected_track = st.selectbox(
"2. Choose a Reference Track:",
available_tracks,
index=min(100, len(available_tracks)-1),
help="Select a track that the system will use as a starting point for content-based similarity."
)
num_recs = st.slider(
"3. Number of Recommendations:",
min_value=5,
max_value=25,
value=10,
step=1,
help="How many song recommendations would you like? (Max 25)"
)
st.markdown("---")
if st.button("Get Recommendations", use_container_width=True, type="primary"):
st.session_state['get_recs'] = True
else:
if 'get_recs' not in st.session_state:
st.session_state['get_recs'] = False
# Display Recommendations
if st.session_state['get_recs']:
st.subheader("🔮 Your Personalized Recommendations:")
try:
user_id = user_encoder.transform([selected_artist])[0]
recommendations = hybrid_recommendation(user_id=user_id,
reference_track_name=selected_track,
num_recommendations=num_recs) # Pass the requested number from slider
if recommendations:
recs_df = pd.DataFrame(recommendations, columns=['Track Title', 'Artist'])
recs_df.index = np.arange(1, len(recs_df) + 1)
st.dataframe(recs_df, use_container_width=True)
st.markdown("---")
st.markdown("Enjoy your new music discoveries! ✨")
else:
st.warning("Could not generate recommendations. Please try selecting a different artist or reference track.", icon="⚠️")
except ValueError as ve:
st.error(f"Error processing input artist: {ve}", icon="❌")
except Exception as e:
st.error(f"An unexpected error occurred: {e}", icon="❌")
st.exception(e)
else:
st.info("Select your preferences in the sidebar and click 'Get Recommendations' to begin!", icon="👆")
st.markdown("---")
st.markdown("Built with using LightFM and Streamlit.")
st.markdown("Find the project notebook [here](https://github.com/indranil143/Hybrid-Music-Recommendation-System)")