Spaces:
Runtime error
Runtime error
File size: 15,256 Bytes
f34f7ed b7e4e4f f34f7ed b7e4e4f f34f7ed b7e4e4f 3533ee2 b7e4e4f f34f7ed b7e4e4f 3533ee2 b7e4e4f f34f7ed b7e4e4f f34f7ed b7e4e4f f34f7ed b7e4e4f f34f7ed |
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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 |
# import gradio as gr
# import torch
# import torch.nn as nn
# from joblib import load
# # Define the same neural network model
# class ImprovedSongRecommender(nn.Module):
# def __init__(self, input_size, num_titles):
# super(ImprovedSongRecommender, self).__init__()
# self.fc1 = nn.Linear(input_size, 128)
# self.bn1 = nn.BatchNorm1d(128)
# self.fc2 = nn.Linear(128, 256)
# self.bn2 = nn.BatchNorm1d(256)
# self.fc3 = nn.Linear(256, 128)
# self.bn3 = nn.BatchNorm1d(128)
# self.output = nn.Linear(128, num_titles)
# self.dropout = nn.Dropout(0.5)
# def forward(self, x):
# x = torch.relu(self.bn1(self.fc1(x)))
# x = self.dropout(x)
# x = torch.relu(self.bn2(self.fc2(x)))
# x = self.dropout(x)
# x = torch.relu(self.bn3(self.fc3(x)))
# x = self.dropout(x)
# x = self.output(x)
# return x
# # Load the trained model
# model_path = "models/improved_model.pth"
# num_unique_titles = 4855
# model = ImprovedSongRecommender(input_size=2, num_titles=num_unique_titles)
# model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
# model.eval()
# # Load the label encoders and scaler
# label_encoders_path = "data/new_label_encoders.joblib"
# scaler_path = "data/new_scaler.joblib"
# label_encoders = load(label_encoders_path)
# scaler = load(scaler_path)
# # Create a mapping from encoded indices to actual song titles
# index_to_song_title = {index: title for index, title in enumerate(label_encoders['title'].classes_)}
# def encode_input(tags, artist_name):
# tags = tags.strip().replace('\n', '')
# artist_name = artist_name.strip().replace('\n', '')
# try:
# encoded_tags = label_encoders['tags'].transform([tags])[0]
# except ValueError:
# encoded_tags = label_encoders['tags'].transform(['unknown'])[0]
# if artist_name:
# try:
# encoded_artist = label_encoders['artist_name'].transform([artist_name])[0]
# except ValueError:
# encoded_artist = label_encoders['artist_name'].transform(['unknown'])[0]
# else:
# encoded_artist = label_encoders['artist_name'].transform(['unknown'])[0]
# return [encoded_tags, encoded_artist]
# def recommend_songs(tags, artist_name):
# encoded_input = encode_input(tags, artist_name)
# input_tensor = torch.tensor([encoded_input]).float()
# with torch.no_grad():
# output = model(input_tensor)
# recommendations_indices = torch.topk(output, 5).indices.squeeze().tolist()
# recommendations = [index_to_song_title.get(idx, "Unknown song") for idx in recommendations_indices]
# formatted_output = [f"Recommendation {i+1}: {rec}" for i, rec in enumerate(recommendations)]
# return formatted_output
# # Set up the Gradio interface
# interface = gr.Interface(
# fn=recommend_songs,
# inputs=[gr.Textbox(lines=1, placeholder="Enter Tags (e.g., rock)"), gr.Textbox(lines=1, placeholder="Enter Artist Name (optional)")],
# outputs=gr.Textbox(label="Recommendations"),
# title="Music Recommendation System",
# description="Enter tags and (optionally) artist name to get music recommendations."
# )
# interface.launch()
# import gradio as gr
# import torch
# import torch.nn as nn
# from joblib import load
# import numpy as np
# import json
# class ImprovedSongRecommender(nn.Module):
# def __init__(self, input_size, num_titles):
# super(ImprovedSongRecommender, self).__init__()
# self.fc1 = nn.Linear(input_size, 128)
# self.bn1 = nn.BatchNorm1d(128)
# self.fc2 = nn.Linear(128, 256)
# self.bn2 = nn.BatchNorm1d(256)
# self.fc3 = nn.Linear(256, 128)
# self.bn3 = nn.BatchNorm1d(128)
# self.output = nn.Linear(128, num_titles)
# self.dropout = nn.Dropout(0.5)
# def forward(self, x):
# x = torch.relu(self.bn1(self.fc1(x)))
# x = self.dropout(x)
# x = torch.relu(self.bn2(self.fc2(x)))
# x = self.dropout(x)
# x = torch.relu(self.bn3(self.fc3(x)))
# x = self.dropout(x)
# x = self.output(x)
# return x
# # Load the trained model
# model_path = "models/improved_model.pth"
# num_unique_titles = 4855
# model = ImprovedSongRecommender(input_size=2, num_titles=num_unique_titles)
# model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
# model.eval()
# # Load the label encoders and scaler
# label_encoders_path = "data/new_label_encoders.joblib"
# scaler_path = "data/new_scaler.joblib"
# label_encoders = load(label_encoders_path)
# scaler = load(scaler_path)
# index_to_song_title = {index: title for index, title in enumerate(label_encoders['title'].classes_)}
# def encode_input(tags, artist_name):
# tags_list = [tag.strip() for tag in tags.split(',')]
# encoded_tags_list = []
# for tag in tags_list:
# try:
# encoded_tags_list.append(label_encoders['tags'].transform([tag])[0])
# except ValueError:
# encoded_tags_list.append(label_encoders['tags'].transform(['unknown'])[0])
# encoded_tags = np.mean(encoded_tags_list).astype(int) if encoded_tags_list else label_encoders['tags'].transform(['unknown'])[0]
# try:
# encoded_artist = label_encoders['artist_name'].transform([artist_name])[0] if artist_name else label_encoders['artist_name'].transform(['unknown'])[0]
# except ValueError:
# encoded_artist = label_encoders['artist_name'].transform(['unknown'])[0]
# return [encoded_tags, encoded_artist]
# def recommend_songs(tags, artist_name):
# encoded_input = encode_input(tags, artist_name)
# input_tensor = torch.tensor([encoded_input]).float()
# with torch.no_grad():
# output = model(input_tensor)
# recommendations_indices = torch.topk(output, 5).indices.squeeze().tolist()
# recommendations = [index_to_song_title.get(idx, "Unknown song") for idx in recommendations_indices]
# feedback_html = []
# for idx, rec in enumerate(recommendations):
# feedback_html.append(f"{rec} <button onclick='gr.Interface.update(\"record_feedback\", {{\"recommendation\": \"{rec}\", \"feedback\": \"up\"}})'>π</button> <button onclick='gr.Interface.update(\"record_feedback\", {{\"recommendation\": \"{rec}\", \"feedback\": \"down\"}})'>π</button>")
# return "<br>".join(feedback_html)
# def record_feedback(recommendation, feedback):
# with open("feedback_data.csv", "a") as file:
# file.write(f"{recommendation},{feedback}\n")
# return f"Feedback recorded for {recommendation}: {feedback}"
# interface = gr.Interface(
# fn=recommend_songs,
# inputs=[
# gr.Textbox(lines=2, placeholder="Enter Tags (e.g., rock, jazz)"),
# gr.Textbox(lines=2, placeholder="Enter Artist Name (optional)")
# ],
# outputs=gr.HTML(label="Recommendations"),
# title="Music Recommendation System",
# description="Enter tags and (optionally) artist name to get music recommendations. Click on thumbs up/down to provide feedback on each song.",
# allow_flagging="never"
# )
# interface.launch()
# import gradio as gr
# import torch
# import torch.nn as nn
# from joblib import load
# import numpy as np
# import os
# class ImprovedSongRecommender(nn.Module):
# def __init__(self, input_size, num_titles):
# super(ImprovedSongRecommender, self).__init__()
# self.fc1 = nn.Linear(input_size, 128)
# self.bn1 = nn.BatchNorm1d(128)
# self.fc2 = nn.Linear(128, 256)
# self.bn2 = nn.BatchNorm1d(256)
# self.fc3 = nn.Linear(256, 128)
# self.bn3 = nn.BatchNorm1d(128)
# self.output = nn.Linear(128, num_titles)
# self.dropout = nn.Dropout(0.5)
# def forward(self, x):
# x = torch.relu(self.bn1(self.fc1(x)))
# x = self.dropout(x)
# x = torch.relu(self.bn2(self.fc2(x)))
# x = self.dropout(x)
# x = torch.relu(self.bn3(self.fc3(x)))
# x = self.dropout(x)
# x = self.output(x)
# return x
# # Load the trained model
# model_path = "models/improved_model.pth"
# num_unique_titles = 4855
# model = ImprovedSongRecommender(input_size=2, num_titles=num_unique_titles)
# model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
# model.eval()
# # Load the label encoders and scaler
# label_encoders_path = "data/new_label_encoders.joblib"
# scaler_path = "data/new_scaler.joblib"
# label_encoders = load(label_encoders_path)
# scaler = load(scaler_path)
# index_to_song_title = {index: title for index, title in enumerate(label_encoders['title'].classes_)}
# def encode_input(tags, artist_name):
# tags_list = [tag.strip() for tag in tags.split(',')]
# encoded_tags_list = []
# for tag in tags_list:
# try:
# encoded_tags_list.append(label_encoders['tags'].transform([tag])[0])
# except ValueError:
# encoded_tags_list.append(label_encoders['tags'].transform(['unknown'])[0])
# encoded_tags = np.mean(encoded_tags_list).astype(int) if encoded_tags_list else label_encoders['tags'].transform(['unknown'])[0]
# try:
# encoded_artist = label_encoders['artist_name'].transform([artist_name])[0] if artist_name else label_encoders['artist_name'].transform(['unknown'])[0]
# except ValueError:
# encoded_artist = label_encoders['artist_name'].transform(['unknown'])[0]
# return [encoded_tags, encoded_artist]
# def recommend_songs(tags, artist_name):
# encoded_input = encode_input(tags, artist_name)
# input_tensor = torch.tensor([encoded_input]).float()
# with torch.no_grad():
# output = model(input_tensor)
# recommendations_indices = torch.topk(output, 5).indices.squeeze().tolist()
# recommendations = [index_to_song_title.get(idx, "Unknown song") for idx in recommendations_indices]
# feedback_html = []
# for idx, rec in enumerate(recommendations):
# feedback_html.append(f"{rec} <button onclick='record_feedback(\"{rec}\", \"up\")'>π</button> <button onclick='record_feedback(\"{rec}\", \"down\")'>π</button>")
# return "<br>".join(feedback_html)
# def record_feedback(recommendation, feedback):
# print(f"Recording feedback for: {recommendation}, Feedback: {feedback}") # Debugging statement
# with open("feedback_data.csv", "a") as file:
# file.write(f"{recommendation},{feedback}\n")
# print("Feedback recorded successfully.")
# return f"Feedback recorded for {recommendation}: {feedback}"
# interface = gr.Interface(
# fn=recommend_songs,
# inputs=[
# gr.Textbox(lines=2, placeholder="Enter Tags (e.g., rock, jazz)"),
# gr.Textbox(lines=2, placeholder="Enter Artist Name (optional)")
# ],
# outputs=gr.HTML(label="Recommendations"),
# title="Music Recommendation System",
# description="Enter tags and (optionally) artist name to get music recommendations. Click on thumbs up/down to provide feedback on each song.",
# allow_flagging="never",
# live=True
# )
# interface.launch()
import gradio as gr
import torch
import torch.nn as nn
from joblib import load
import numpy as np
import os
# Define the neural network model
class ImprovedSongRecommender(nn.Module):
def __init__(self, input_size, num_titles):
super(ImprovedSongRecommender, self).__init__()
self.fc1 = nn.Linear(input_size, 128)
self.bn1 = nn.BatchNorm1d(128)
self.fc2 = nn.Linear(128, 256)
self.bn2 = nn.BatchNorm1d(256)
self.fc3 = nn.Linear(256, 128)
self.bn3 = nn.BatchNorm1d(128)
self.output = nn.Linear(128, num_titles)
self.dropout = nn.Dropout(0.5)
def forward(self, x):
x = torch.relu(self.bn1(self.fc1(x)))
x = self.dropout(x)
x = torch.relu(self.bn2(self.fc2(x)))
x = self.dropout(x)
x = torch.relu(self.bn3(self.fc3(x)))
x = self.dropout(x)
x = self.output(x)
return x
# Load the trained model
model_path = "models/improved_model.pth"
num_unique_titles = 4855
model = ImprovedSongRecommender(input_size=2, num_titles=num_unique_titles)
model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
model.eval()
# Load the label encoders and scaler
label_encoders_path = "data/new_label_encoders.joblib"
label_encoders = load(label_encoders_path)
def encode_input(tags, artist_name):
tags_list = [tag.strip() for tag in tags.split(',')]
encoded_tags_list = []
for tag in tags_list:
try:
encoded_tags_list.append(label_encoders['tags'].transform([tag])[0])
except ValueError:
encoded_tags_list.append(label_encoders['tags'].transform(['unknown'])[0])
encoded_tags = np.mean(encoded_tags_list).astype(int) if encoded_tags_list else label_encoders['tags'].transform(['unknown'])[0]
try:
encoded_artist = label_encoders['artist_name'].transform([artist_name])[0]
except ValueError:
encoded_artist = label_encoders['artist_name'].transform(['unknown'])[0]
return [encoded_tags, encoded_artist]
def recommend_songs(tags, artist_name):
encoded_input = encode_input(tags, artist_name)
input_tensor = torch.tensor([encoded_input]).float()
with torch.no_grad():
output = model(input_tensor)
recommendations_indices = torch.topk(output, 5).indices.squeeze().tolist()
recommendations = [label_encoders['title'].inverse_transform([idx])[0] for idx in recommendations_indices]
print("Recommendations:", recommendations) # Debugging statement
return recommendations
def record_feedback(recommendation, feedback):
feedback_path = "feedback_data.csv"
if not os.path.exists(feedback_path):
with open(feedback_path, 'w') as f:
f.write("Recommendation,Feedback\n")
with open(feedback_path, 'a') as f:
f.write(f"{recommendation},{feedback}\n")
return "Feedback recorded!"
app = gr.Blocks()
with app:
gr.Markdown("## Music Recommendation System")
tags_input = gr.Textbox(label="Enter Tags (e.g., rock, jazz, pop)", placeholder="rock, pop")
artist_name_input = gr.Textbox(label="Enter Artist Name (optional)", placeholder="The Beatles")
submit_button = gr.Button("Get Recommendations")
recommendations_output = gr.HTML(label="Recommendations")
feedback_input = gr.Radio(choices=["Thumbs Up", "Thumbs Down"], label="Feedback")
feedback_button = gr.Button("Submit Feedback")
feedback_result = gr.Label(label="Feedback Result")
def display_recommendations(tags, artist_name):
recommendations = recommend_songs(tags, artist_name)
if recommendations:
return recommendations
else:
return ["No recommendations found"]
submit_button.click(
fn=display_recommendations,
inputs=[tags_input, artist_name_input],
outputs=recommendations_output
)
feedback_button.click(
fn=record_feedback,
inputs=[recommendations_output, feedback_input],
outputs=feedback_result
)
app.launch()
|