Spaces:
Runtime error
Runtime error
Santarabantoosoo
commited on
Commit
•
50ebde2
1
Parent(s):
413eacd
Delete app.py
Browse files
app.py
DELETED
@@ -1,166 +0,0 @@
|
|
1 |
-
# -*- coding: utf-8 -*-
|
2 |
-
"""semantic_song_search.ipynb
|
3 |
-
|
4 |
-
Automatically generated by Colaboratory.
|
5 |
-
|
6 |
-
Original file is located at
|
7 |
-
https://colab.research.google.com/drive/17IwipreOw_cvu1TsA4WUrfzxTBBHMiVh
|
8 |
-
"""
|
9 |
-
|
10 |
-
from sentence_transformers import SentenceTransformer, util
|
11 |
-
import gradio as gr
|
12 |
-
import pandas as pd
|
13 |
-
import torch
|
14 |
-
import numpy as np
|
15 |
-
|
16 |
-
from google.colab import drive
|
17 |
-
drive.mount('/content/gdrive')
|
18 |
-
|
19 |
-
# Commented out IPython magic to ensure Python compatibility.
|
20 |
-
# %cd gdrive/MyDrive/song_sentiment
|
21 |
-
|
22 |
-
"""### model all mini -- small dataset """
|
23 |
-
|
24 |
-
model_all_mini = SentenceTransformer('all-MiniLM-L12-v2')
|
25 |
-
|
26 |
-
sds = pd.read_csv("data/small_dataset.csv")
|
27 |
-
|
28 |
-
embeddings_sds = model_all_mini.encode(sds['lyrics'])
|
29 |
-
sds['embeddings'] = list(embeddings_sds)
|
30 |
-
|
31 |
-
def relevance_scores(query_embed):
|
32 |
-
scores = [cosine_similarity(query_embed, v2) for v2 in sds['embeddings']]
|
33 |
-
scores = pd.Series(scores)
|
34 |
-
return(scores)
|
35 |
-
|
36 |
-
|
37 |
-
def semantic_search(query_sentence, df = sds, return_top = False):
|
38 |
-
query_embed = model_all_mini.encode(query_sentence)
|
39 |
-
scores = relevance_scores(query_embed)
|
40 |
-
df['scores'] = scores
|
41 |
-
sorted_df = df.sort_values(by = 'scores', ascending = False)
|
42 |
-
if return_top == False:
|
43 |
-
sorted_df['scores'] = round(sorted_df['scores'],3)
|
44 |
-
return sorted_df[['title','artist','scores']].head(3)
|
45 |
-
else:
|
46 |
-
return sorted_df.iloc[0]['lyrics'][:200]
|
47 |
-
|
48 |
-
def cosine_similarity(v1, v2):
|
49 |
-
d = np.dot(v1, v2)
|
50 |
-
cos_theta = d / (np.linalg.norm(v1) * np.linalg.norm(v2))
|
51 |
-
return(cos_theta)
|
52 |
-
|
53 |
-
semantic_search("i'm pleased you are doing well after we left each other")
|
54 |
-
|
55 |
-
print(semantic_search("i'm pleased you are doing well after we left each other", return_top = True))
|
56 |
-
|
57 |
-
"""### model msmarco-distilbert-base-dot-prod-v3 with hf dataset (with song name)"""
|
58 |
-
|
59 |
-
query = ["i'm pleased you are doing well after we left each other"]
|
60 |
-
|
61 |
-
hf_data = pd.read_csv('data/hf_train_with_SName.csv')
|
62 |
-
|
63 |
-
hf_data['Lyric'] = hf_data['Lyric'].str.replace('\\n', "")
|
64 |
-
|
65 |
-
hf_data.head()
|
66 |
-
|
67 |
-
model_msmarco_v3 = SentenceTransformer('msmarco-distilbert-base-dot-prod-v3')
|
68 |
-
|
69 |
-
query_embedding = model_msmarco_v3.encode(query)
|
70 |
-
|
71 |
-
passage_embedding = model_msmarco_v3.encode(hf_data[:1000].Lyric)
|
72 |
-
|
73 |
-
corpus_embeddings = torch.from_numpy(passage_embedding).float().to('cuda')
|
74 |
-
corpus_embeddings = util.normalize_embeddings(corpus_embeddings)
|
75 |
-
|
76 |
-
# query_embeddings = torch.from_numpy(query_embedding).float().to('cuda')
|
77 |
-
# query_embeddings = util.normalize_embeddings(query_embeddings)
|
78 |
-
# hits = util.semantic_search(query_embeddings, corpus_embeddings, score_function=util.dot_score)
|
79 |
-
|
80 |
-
# best_match = hits[0][0]['corpus_id']
|
81 |
-
|
82 |
-
hf_data.iloc[best_match, :]
|
83 |
-
|
84 |
-
hf_data.iloc[best_match]['Lyric']
|
85 |
-
|
86 |
-
hf_data.head()
|
87 |
-
|
88 |
-
def msmarco_match(query, return_top = True):
|
89 |
-
query_embedding = model_msmarco_v3.encode(query)
|
90 |
-
query_embeddings = torch.from_numpy(query_embedding).float().to('cuda')
|
91 |
-
query_embeddings = util.normalize_embeddings(query_embeddings)
|
92 |
-
hits = util.semantic_search(query_embeddings, corpus_embeddings, score_function=util.dot_score)
|
93 |
-
top_hits = hits[0][0:3]
|
94 |
-
|
95 |
-
ids = [item['corpus_id'] for item in top_hits]
|
96 |
-
scores = pd.Series([round(item['score'],3) for item in top_hits])
|
97 |
-
|
98 |
-
if return_top == True:
|
99 |
-
return hf_data.iloc[ids[0]]['Lyric'][:200]
|
100 |
-
else:
|
101 |
-
songs = hf_data.iloc[ids].reset_index()
|
102 |
-
songs = pd.concat([songs, scores], axis = 1)
|
103 |
-
|
104 |
-
songs.rename(columns={0: 'Score'},
|
105 |
-
inplace=True)
|
106 |
-
return songs.drop(columns = 'index')
|
107 |
-
|
108 |
-
msmarco_match(query, return_top= False)
|
109 |
-
|
110 |
-
msmarco_match(query)
|
111 |
-
|
112 |
-
msmarco_match(query, return_top = False)
|
113 |
-
|
114 |
-
"""## Fine-tuned all-mini -- small dataset"""
|
115 |
-
|
116 |
-
model_fine_tuned = SentenceTransformer('models/finetune_mnr_final')
|
117 |
-
|
118 |
-
embeddings_sds_ft = model_fine_tuned.encode(sds['lyrics'])
|
119 |
-
sds['embeddings_ft'] = list(embeddings_sds_ft)
|
120 |
-
|
121 |
-
def relevance_scores_ft(query_embed):
|
122 |
-
scores = [cosine_similarity(query_embed, v2) for v2 in sds['embeddings_ft']]
|
123 |
-
scores = pd.Series(scores)
|
124 |
-
return(scores)
|
125 |
-
|
126 |
-
|
127 |
-
def semantic_search_ft(query_sentence, df = sds, return_top = False):
|
128 |
-
query_embed = model_fine_tuned.encode(query_sentence)
|
129 |
-
scores = relevance_scores(query_embed)
|
130 |
-
df['scores'] = scores
|
131 |
-
sorted_df = df.sort_values(by = 'scores', ascending = False)
|
132 |
-
if return_top == False:
|
133 |
-
sorted_df['scores'] = round(sorted_df['scores'],3)
|
134 |
-
return sorted_df[['title','artist','scores']].head(3)
|
135 |
-
else:
|
136 |
-
return sorted_df.iloc[0]['lyrics'][:200]
|
137 |
-
|
138 |
-
"""## Gradio App """
|
139 |
-
|
140 |
-
def get_recom(choice, query):
|
141 |
-
if choice == "all-MiniLM":
|
142 |
-
return semantic_search(query), semantic_search(query, return_top = True)
|
143 |
-
elif choice == "all-MiniLM-fine-tuned":
|
144 |
-
return semantic_search_ft(query), semantic_search_ft(query, return_top = True)
|
145 |
-
else:
|
146 |
-
list_query = []
|
147 |
-
query2 = query
|
148 |
-
list_query.append([query, query2])
|
149 |
-
return msmarco_match(list_query, return_top = False) , msmarco_match(list_query)
|
150 |
-
|
151 |
-
|
152 |
-
iface = gr.Interface(
|
153 |
-
title = 'Enjoy our recommendations',
|
154 |
-
description = 'Do you think we can guess what you like?',
|
155 |
-
fn=get_recom,
|
156 |
-
inputs= [ gr.Radio(choices = ["all-MiniLM", "all-MiniLM-fine-tuned", "msmarco"], label="Choose ur model"),
|
157 |
-
gr.Textbox(lines=4, placeholder="Enter ur query...", label = 'Query', show_label = True)],
|
158 |
-
outputs = [gr.Dataframe(label = "Top songs", show_label = True),
|
159 |
-
gr.Text(label = 'A glimpse of the closest match', show_label = True)]
|
160 |
-
,live = False,
|
161 |
-
interpretation="default",
|
162 |
-
)
|
163 |
-
|
164 |
-
|
165 |
-
iface.launch()
|
166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|