Joash2024 commited on
Commit
d6155b9
·
1 Parent(s): dc5fe07

Remove junk

Browse files
Files changed (2) hide show
  1. app.py +20 -393
  2. feedback_data/feedback_data.json +2 -0
app.py CHANGED
@@ -1,395 +1,4 @@
1
- # import gradio as gr
2
- # import torch
3
- # import torch.nn as nn
4
- # from joblib import load
5
 
6
- # # Define the same neural network model
7
- # class ImprovedSongRecommender(nn.Module):
8
- # def __init__(self, input_size, num_titles):
9
- # super(ImprovedSongRecommender, self).__init__()
10
- # self.fc1 = nn.Linear(input_size, 128)
11
- # self.bn1 = nn.BatchNorm1d(128)
12
- # self.fc2 = nn.Linear(128, 256)
13
- # self.bn2 = nn.BatchNorm1d(256)
14
- # self.fc3 = nn.Linear(256, 128)
15
- # self.bn3 = nn.BatchNorm1d(128)
16
- # self.output = nn.Linear(128, num_titles)
17
- # self.dropout = nn.Dropout(0.5)
18
-
19
- # def forward(self, x):
20
- # x = torch.relu(self.bn1(self.fc1(x)))
21
- # x = self.dropout(x)
22
- # x = torch.relu(self.bn2(self.fc2(x)))
23
- # x = self.dropout(x)
24
- # x = torch.relu(self.bn3(self.fc3(x)))
25
- # x = self.dropout(x)
26
- # x = self.output(x)
27
- # return x
28
-
29
- # # Load the trained model
30
- # model_path = "models/improved_model.pth"
31
- # num_unique_titles = 4855
32
-
33
- # model = ImprovedSongRecommender(input_size=2, num_titles=num_unique_titles)
34
- # model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
35
- # model.eval()
36
-
37
- # # Load the label encoders and scaler
38
- # label_encoders_path = "data/new_label_encoders.joblib"
39
- # scaler_path = "data/new_scaler.joblib"
40
-
41
- # label_encoders = load(label_encoders_path)
42
- # scaler = load(scaler_path)
43
-
44
- # # Create a mapping from encoded indices to actual song titles
45
- # index_to_song_title = {index: title for index, title in enumerate(label_encoders['title'].classes_)}
46
-
47
- # def encode_input(tags, artist_name):
48
- # tags = tags.strip().replace('\n', '')
49
- # artist_name = artist_name.strip().replace('\n', '')
50
-
51
- # try:
52
- # encoded_tags = label_encoders['tags'].transform([tags])[0]
53
- # except ValueError:
54
- # encoded_tags = label_encoders['tags'].transform(['unknown'])[0]
55
-
56
- # if artist_name:
57
- # try:
58
- # encoded_artist = label_encoders['artist_name'].transform([artist_name])[0]
59
- # except ValueError:
60
- # encoded_artist = label_encoders['artist_name'].transform(['unknown'])[0]
61
- # else:
62
- # encoded_artist = label_encoders['artist_name'].transform(['unknown'])[0]
63
-
64
- # return [encoded_tags, encoded_artist]
65
-
66
- # def recommend_songs(tags, artist_name):
67
- # encoded_input = encode_input(tags, artist_name)
68
- # input_tensor = torch.tensor([encoded_input]).float()
69
-
70
- # with torch.no_grad():
71
- # output = model(input_tensor)
72
-
73
- # recommendations_indices = torch.topk(output, 5).indices.squeeze().tolist()
74
- # recommendations = [index_to_song_title.get(idx, "Unknown song") for idx in recommendations_indices]
75
-
76
- # formatted_output = [f"Recommendation {i+1}: {rec}" for i, rec in enumerate(recommendations)]
77
- # return formatted_output
78
-
79
- # # Set up the Gradio interface
80
- # interface = gr.Interface(
81
- # fn=recommend_songs,
82
- # inputs=[gr.Textbox(lines=1, placeholder="Enter Tags (e.g., rock)"), gr.Textbox(lines=1, placeholder="Enter Artist Name (optional)")],
83
- # outputs=gr.Textbox(label="Recommendations"),
84
- # title="Music Recommendation System",
85
- # description="Enter tags and (optionally) artist name to get music recommendations."
86
- # )
87
-
88
- # interface.launch()
89
-
90
- # import gradio as gr
91
- # import torch
92
- # import torch.nn as nn
93
- # from joblib import load
94
- # import numpy as np
95
- # import json
96
-
97
- # class ImprovedSongRecommender(nn.Module):
98
- # def __init__(self, input_size, num_titles):
99
- # super(ImprovedSongRecommender, self).__init__()
100
- # self.fc1 = nn.Linear(input_size, 128)
101
- # self.bn1 = nn.BatchNorm1d(128)
102
- # self.fc2 = nn.Linear(128, 256)
103
- # self.bn2 = nn.BatchNorm1d(256)
104
- # self.fc3 = nn.Linear(256, 128)
105
- # self.bn3 = nn.BatchNorm1d(128)
106
- # self.output = nn.Linear(128, num_titles)
107
- # self.dropout = nn.Dropout(0.5)
108
-
109
- # def forward(self, x):
110
- # x = torch.relu(self.bn1(self.fc1(x)))
111
- # x = self.dropout(x)
112
- # x = torch.relu(self.bn2(self.fc2(x)))
113
- # x = self.dropout(x)
114
- # x = torch.relu(self.bn3(self.fc3(x)))
115
- # x = self.dropout(x)
116
- # x = self.output(x)
117
- # return x
118
-
119
- # # Load the trained model
120
- # model_path = "models/improved_model.pth"
121
- # num_unique_titles = 4855
122
- # model = ImprovedSongRecommender(input_size=2, num_titles=num_unique_titles)
123
- # model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
124
- # model.eval()
125
-
126
- # # Load the label encoders and scaler
127
- # label_encoders_path = "data/new_label_encoders.joblib"
128
- # scaler_path = "data/new_scaler.joblib"
129
- # label_encoders = load(label_encoders_path)
130
- # scaler = load(scaler_path)
131
-
132
- # index_to_song_title = {index: title for index, title in enumerate(label_encoders['title'].classes_)}
133
-
134
- # def encode_input(tags, artist_name):
135
- # tags_list = [tag.strip() for tag in tags.split(',')]
136
- # encoded_tags_list = []
137
- # for tag in tags_list:
138
- # try:
139
- # encoded_tags_list.append(label_encoders['tags'].transform([tag])[0])
140
- # except ValueError:
141
- # encoded_tags_list.append(label_encoders['tags'].transform(['unknown'])[0])
142
-
143
- # encoded_tags = np.mean(encoded_tags_list).astype(int) if encoded_tags_list else label_encoders['tags'].transform(['unknown'])[0]
144
-
145
- # try:
146
- # encoded_artist = label_encoders['artist_name'].transform([artist_name])[0] if artist_name else label_encoders['artist_name'].transform(['unknown'])[0]
147
- # except ValueError:
148
- # encoded_artist = label_encoders['artist_name'].transform(['unknown'])[0]
149
-
150
- # return [encoded_tags, encoded_artist]
151
-
152
- # def recommend_songs(tags, artist_name):
153
- # encoded_input = encode_input(tags, artist_name)
154
- # input_tensor = torch.tensor([encoded_input]).float()
155
- # with torch.no_grad():
156
- # output = model(input_tensor)
157
- # recommendations_indices = torch.topk(output, 5).indices.squeeze().tolist()
158
- # recommendations = [index_to_song_title.get(idx, "Unknown song") for idx in recommendations_indices]
159
-
160
- # feedback_html = []
161
- # for idx, rec in enumerate(recommendations):
162
- # 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>")
163
- # return "<br>".join(feedback_html)
164
-
165
- # def record_feedback(recommendation, feedback):
166
-
167
- # with open("feedback_data.csv", "a") as file:
168
- # file.write(f"{recommendation},{feedback}\n")
169
- # return f"Feedback recorded for {recommendation}: {feedback}"
170
-
171
- # interface = gr.Interface(
172
- # fn=recommend_songs,
173
- # inputs=[
174
- # gr.Textbox(lines=2, placeholder="Enter Tags (e.g., rock, jazz)"),
175
- # gr.Textbox(lines=2, placeholder="Enter Artist Name (optional)")
176
- # ],
177
- # outputs=gr.HTML(label="Recommendations"),
178
- # title="Music Recommendation System",
179
- # description="Enter tags and (optionally) artist name to get music recommendations. Click on thumbs up/down to provide feedback on each song.",
180
- # allow_flagging="never"
181
- # )
182
-
183
- # interface.launch()
184
-
185
-
186
- # import gradio as gr
187
- # import torch
188
- # import torch.nn as nn
189
- # from joblib import load
190
- # import numpy as np
191
- # import os
192
-
193
- # class ImprovedSongRecommender(nn.Module):
194
- # def __init__(self, input_size, num_titles):
195
- # super(ImprovedSongRecommender, self).__init__()
196
- # self.fc1 = nn.Linear(input_size, 128)
197
- # self.bn1 = nn.BatchNorm1d(128)
198
- # self.fc2 = nn.Linear(128, 256)
199
- # self.bn2 = nn.BatchNorm1d(256)
200
- # self.fc3 = nn.Linear(256, 128)
201
- # self.bn3 = nn.BatchNorm1d(128)
202
- # self.output = nn.Linear(128, num_titles)
203
- # self.dropout = nn.Dropout(0.5)
204
-
205
- # def forward(self, x):
206
- # x = torch.relu(self.bn1(self.fc1(x)))
207
- # x = self.dropout(x)
208
- # x = torch.relu(self.bn2(self.fc2(x)))
209
- # x = self.dropout(x)
210
- # x = torch.relu(self.bn3(self.fc3(x)))
211
- # x = self.dropout(x)
212
- # x = self.output(x)
213
- # return x
214
-
215
- # # Load the trained model
216
- # model_path = "models/improved_model.pth"
217
- # num_unique_titles = 4855
218
- # model = ImprovedSongRecommender(input_size=2, num_titles=num_unique_titles)
219
- # model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
220
- # model.eval()
221
-
222
- # # Load the label encoders and scaler
223
- # label_encoders_path = "data/new_label_encoders.joblib"
224
- # scaler_path = "data/new_scaler.joblib"
225
- # label_encoders = load(label_encoders_path)
226
- # scaler = load(scaler_path)
227
-
228
- # index_to_song_title = {index: title for index, title in enumerate(label_encoders['title'].classes_)}
229
-
230
- # def encode_input(tags, artist_name):
231
- # tags_list = [tag.strip() for tag in tags.split(',')]
232
- # encoded_tags_list = []
233
- # for tag in tags_list:
234
- # try:
235
- # encoded_tags_list.append(label_encoders['tags'].transform([tag])[0])
236
- # except ValueError:
237
- # encoded_tags_list.append(label_encoders['tags'].transform(['unknown'])[0])
238
-
239
- # encoded_tags = np.mean(encoded_tags_list).astype(int) if encoded_tags_list else label_encoders['tags'].transform(['unknown'])[0]
240
-
241
- # try:
242
- # encoded_artist = label_encoders['artist_name'].transform([artist_name])[0] if artist_name else label_encoders['artist_name'].transform(['unknown'])[0]
243
- # except ValueError:
244
- # encoded_artist = label_encoders['artist_name'].transform(['unknown'])[0]
245
-
246
- # return [encoded_tags, encoded_artist]
247
-
248
- # def recommend_songs(tags, artist_name):
249
- # encoded_input = encode_input(tags, artist_name)
250
- # input_tensor = torch.tensor([encoded_input]).float()
251
- # with torch.no_grad():
252
- # output = model(input_tensor)
253
- # recommendations_indices = torch.topk(output, 5).indices.squeeze().tolist()
254
- # recommendations = [index_to_song_title.get(idx, "Unknown song") for idx in recommendations_indices]
255
-
256
- # feedback_html = []
257
- # for idx, rec in enumerate(recommendations):
258
- # feedback_html.append(f"{rec} <button onclick='record_feedback(\"{rec}\", \"up\")'>👍</button> <button onclick='record_feedback(\"{rec}\", \"down\")'>👎</button>")
259
- # return "<br>".join(feedback_html)
260
-
261
- # def record_feedback(recommendation, feedback):
262
- # print(f"Recording feedback for: {recommendation}, Feedback: {feedback}") # Debugging statement
263
- # with open("feedback_data.csv", "a") as file:
264
- # file.write(f"{recommendation},{feedback}\n")
265
- # print("Feedback recorded successfully.")
266
- # return f"Feedback recorded for {recommendation}: {feedback}"
267
-
268
- # interface = gr.Interface(
269
- # fn=recommend_songs,
270
- # inputs=[
271
- # gr.Textbox(lines=2, placeholder="Enter Tags (e.g., rock, jazz)"),
272
- # gr.Textbox(lines=2, placeholder="Enter Artist Name (optional)")
273
- # ],
274
- # outputs=gr.HTML(label="Recommendations"),
275
- # title="Music Recommendation System",
276
- # description="Enter tags and (optionally) artist name to get music recommendations. Click on thumbs up/down to provide feedback on each song.",
277
- # allow_flagging="never",
278
- # live=True
279
- # )
280
-
281
- # interface.launch()
282
-
283
- # import gradio as gr
284
- # import torch
285
- # import torch.nn as nn
286
- # from joblib import load
287
- # import numpy as np
288
- # import os
289
-
290
- # # Define the neural network model
291
- # class ImprovedSongRecommender(nn.Module):
292
- # def __init__(self, input_size, num_titles):
293
- # super(ImprovedSongRecommender, self).__init__()
294
- # self.fc1 = nn.Linear(input_size, 128)
295
- # self.bn1 = nn.BatchNorm1d(128)
296
- # self.fc2 = nn.Linear(128, 256)
297
- # self.bn2 = nn.BatchNorm1d(256)
298
- # self.fc3 = nn.Linear(256, 128)
299
- # self.bn3 = nn.BatchNorm1d(128)
300
- # self.output = nn.Linear(128, num_titles)
301
- # self.dropout = nn.Dropout(0.5)
302
-
303
- # def forward(self, x):
304
- # x = torch.relu(self.bn1(self.fc1(x)))
305
- # x = self.dropout(x)
306
- # x = torch.relu(self.bn2(self.fc2(x)))
307
- # x = self.dropout(x)
308
- # x = torch.relu(self.bn3(self.fc3(x)))
309
- # x = self.dropout(x)
310
- # x = self.output(x)
311
- # return x
312
-
313
- # # Load the trained model
314
- # model_path = "models/improved_model.pth"
315
- # num_unique_titles = 4855
316
- # model = ImprovedSongRecommender(input_size=2, num_titles=num_unique_titles)
317
- # model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
318
- # model.eval()
319
-
320
- # # Load the label encoders and scaler
321
- # label_encoders_path = "data/new_label_encoders.joblib"
322
- # label_encoders = load(label_encoders_path)
323
-
324
- # def encode_input(tags, artist_name):
325
- # tags_list = [tag.strip() for tag in tags.split(',')]
326
- # encoded_tags_list = []
327
- # for tag in tags_list:
328
- # try:
329
- # encoded_tags_list.append(label_encoders['tags'].transform([tag])[0])
330
- # except ValueError:
331
- # encoded_tags_list.append(label_encoders['tags'].transform(['unknown'])[0])
332
-
333
- # encoded_tags = np.mean(encoded_tags_list).astype(int) if encoded_tags_list else label_encoders['tags'].transform(['unknown'])[0]
334
-
335
- # try:
336
- # encoded_artist = label_encoders['artist_name'].transform([artist_name])[0]
337
- # except ValueError:
338
- # encoded_artist = label_encoders['artist_name'].transform(['unknown'])[0]
339
-
340
- # return [encoded_tags, encoded_artist]
341
-
342
- # def recommend_songs(tags, artist_name):
343
- # encoded_input = encode_input(tags, artist_name)
344
- # input_tensor = torch.tensor([encoded_input]).float()
345
- # with torch.no_grad():
346
- # output = model(input_tensor)
347
- # recommendations_indices = torch.topk(output, 5).indices.squeeze().tolist()
348
- # recommendations = [label_encoders['title'].inverse_transform([idx])[0] for idx in recommendations_indices]
349
- # print("Recommendations:", recommendations)
350
- # return recommendations
351
-
352
- # def record_feedback(recommendation, feedback):
353
- # feedback_path = "feedback_data.csv"
354
- # if not os.path.exists(feedback_path):
355
- # with open(feedback_path, 'w') as f:
356
- # f.write("Recommendation,Feedback\n")
357
- # with open(feedback_path, 'a') as f:
358
- # f.write(f"{recommendation},{feedback}\n")
359
- # return "Feedback recorded!"
360
-
361
- # app = gr.Blocks()
362
-
363
- # with app:
364
- # gr.Markdown("## Music Recommendation System")
365
- # tags_input = gr.Textbox(label="Enter Tags (e.g., rock, jazz, pop)", placeholder="rock, pop")
366
- # artist_name_input = gr.Textbox(label="Enter Artist Name (optional)", placeholder="The Beatles")
367
- # submit_button = gr.Button("Get Recommendations")
368
- # recommendations_output = gr.HTML(label="Recommendations")
369
- # feedback_input = gr.Radio(choices=["Thumbs Up", "Thumbs Down"], label="Feedback")
370
- # feedback_button = gr.Button("Submit Feedback")
371
- # feedback_result = gr.Label(label="Feedback Result")
372
-
373
- # def display_recommendations(tags, artist_name):
374
- # recommendations = recommend_songs(tags, artist_name)
375
- # if recommendations:
376
- # return recommendations
377
- # else:
378
- # return ["No recommendations found"]
379
-
380
- # submit_button.click(
381
- # fn=display_recommendations,
382
- # inputs=[tags_input, artist_name_input],
383
- # outputs=recommendations_output
384
- # )
385
-
386
- # feedback_button.click(
387
- # fn=record_feedback,
388
- # inputs=[recommendations_output, feedback_input],
389
- # outputs=feedback_result
390
- # )
391
-
392
- # app.launch()
393
 
394
  import gradio as gr
395
  import torch
@@ -463,7 +72,8 @@ def recommend_songs(tags, artist_name):
463
  def record_feedback(recommendation, feedback):
464
  # Load the dataset or create a new one if it doesn't exist
465
  try:
466
- feedback_dataset = load_dataset("feedback_data", split='train')
 
467
  except:
468
  feedback_dataset = Dataset.from_dict({"Recommendation": [], "Feedback": []})
469
 
@@ -472,10 +82,18 @@ def record_feedback(recommendation, feedback):
472
  feedback_dataset = feedback_dataset.add_item(new_feedback)
473
 
474
  # Save the dataset
475
- feedback_dataset.save_to_disk("feedback_data")
476
 
477
  return "Feedback recorded!"
478
 
 
 
 
 
 
 
 
 
479
  app = gr.Blocks()
480
 
481
  with app:
@@ -487,6 +105,8 @@ with app:
487
  feedback_input = gr.Radio(choices=["Thumbs Up", "Thumbs Down"], label="Feedback")
488
  feedback_button = gr.Button("Submit Feedback")
489
  feedback_result = gr.Label(label="Feedback Result")
 
 
490
 
491
  def display_recommendations(tags, artist_name):
492
  recommendations = recommend_songs(tags, artist_name)
@@ -507,5 +127,12 @@ with app:
507
  outputs=feedback_result
508
  )
509
 
 
 
 
 
 
 
510
  app.launch()
511
 
 
 
 
 
 
 
1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  import gradio as gr
4
  import torch
 
72
  def record_feedback(recommendation, feedback):
73
  # Load the dataset or create a new one if it doesn't exist
74
  try:
75
+ feedback_dataset = load_dataset("json", data_files="feedback_data/feedback_data.json")
76
+ feedback_dataset = feedback_dataset['train']
77
  except:
78
  feedback_dataset = Dataset.from_dict({"Recommendation": [], "Feedback": []})
79
 
 
82
  feedback_dataset = feedback_dataset.add_item(new_feedback)
83
 
84
  # Save the dataset
85
+ feedback_dataset.to_json("feedback_data/feedback_data.json")
86
 
87
  return "Feedback recorded!"
88
 
89
+ def show_feedback():
90
+ try:
91
+ feedback_dataset = load_dataset("json", data_files="feedback_data/feedback_data.json")
92
+ feedback_dataset = feedback_dataset['train']
93
+ return feedback_dataset.to_pandas().to_html()
94
+ except:
95
+ return "No feedback data found."
96
+
97
  app = gr.Blocks()
98
 
99
  with app:
 
105
  feedback_input = gr.Radio(choices=["Thumbs Up", "Thumbs Down"], label="Feedback")
106
  feedback_button = gr.Button("Submit Feedback")
107
  feedback_result = gr.Label(label="Feedback Result")
108
+ show_feedback_button = gr.Button("Show Feedback Data")
109
+ feedback_data_output = gr.HTML(label="Feedback Data")
110
 
111
  def display_recommendations(tags, artist_name):
112
  recommendations = recommend_songs(tags, artist_name)
 
127
  outputs=feedback_result
128
  )
129
 
130
+ show_feedback_button.click(
131
+ fn=show_feedback,
132
+ inputs=[],
133
+ outputs=feedback_data_output
134
+ )
135
+
136
  app.launch()
137
 
138
+
feedback_data/feedback_data.json ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ {"Recommendation":["Helium","Heartburn","Let's Get It Started","Dame Un Besito (Version Salsa)","Long Live The Party"],"Feedback":"Thumbs Up"}
2
+ {"Recommendation":["Heartburn","Hurry Up And Come","Helium","Crazy","Hotel"],"Feedback":"Thumbs Down"},