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