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import streamlit as st
|
3 |
+
import torch
|
4 |
+
import string
|
5 |
+
from io import StringIO
|
6 |
+
import json
|
7 |
+
from transformers import BertTokenizer, BertForMaskedLM
|
8 |
+
|
9 |
+
MAX_INPUT = 1000
|
10 |
+
|
11 |
+
model_names = [
|
12 |
+
{ "name":"SGPT-125M",
|
13 |
+
"model":"Muennighoff/SGPT-125M-weightedmean-nli-bitfit",
|
14 |
+
"mark":False,
|
15 |
+
"class":"SGPTModel"},
|
16 |
+
|
17 |
+
|
18 |
+
{ "name":"SGPT-5.8B",
|
19 |
+
"model": "Muennighoff/SGPT-5.8B-weightedmean-msmarco-specb-bitfit" ,
|
20 |
+
"fork_url":"https://github.com/taskswithcode/sgpt",
|
21 |
+
"orig_author_url":"https://github.com/Muennighoff",
|
22 |
+
"orig_author":"Niklas Muennighoff",
|
23 |
+
"sota_info": {
|
24 |
+
"task":"#1 in multiple information retrieval & search tasks",
|
25 |
+
"sota_link":"https://paperswithcode.com/paper/sgpt-gpt-sentence-embeddings-for-semantic",
|
26 |
+
},
|
27 |
+
"paper_url":"https://arxiv.org/abs/2202.08904v5",
|
28 |
+
"mark":True,
|
29 |
+
"class":"SGPTModel"},
|
30 |
+
|
31 |
+
{ "name":"SGPT-1.3B",
|
32 |
+
"model": "Muennighoff/SGPT-1.3B-weightedmean-msmarco-specb-bitfit",
|
33 |
+
"mark":False,
|
34 |
+
"class":"SGPTModel"},
|
35 |
+
|
36 |
+
{ "name":"sentence-transformers/all-MiniLM-L6-v2",
|
37 |
+
"model":"sentence-transformers/all-MiniLM-L6-v2",
|
38 |
+
"fork_url":"https://github.com/taskswithcode/sentence_similarity_hf_model",
|
39 |
+
"orig_author_url":"https://github.com/UKPLab",
|
40 |
+
"orig_author":"Ubiquitous Knowledge Processing Lab",
|
41 |
+
"sota_info": {
|
42 |
+
"task":"Nearly 4 million downloads from huggingface",
|
43 |
+
"sota_link":"https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2"
|
44 |
+
},
|
45 |
+
"paper_url":"https://arxiv.org/abs/1908.10084",
|
46 |
+
"mark":True,
|
47 |
+
"class":"HFModel"},
|
48 |
+
|
49 |
+
]
|
50 |
+
|
51 |
+
|
52 |
+
|
53 |
+
example_file_names = {
|
54 |
+
"Machine learning terms (30+ phrases)": "tests/small_test.txt",
|
55 |
+
"Customer feedback mixed with noise (50+ sentences)":"tests/larger_test.txt"
|
56 |
+
}
|
57 |
+
|
58 |
+
|
59 |
+
def construct_model_info_for_display():
|
60 |
+
options_arr = []
|
61 |
+
markdown_str = "<div style=\"font-size:16px; color: #2f2f2f; text-align: left\"><br/><b>Models evaluated</b></div>"
|
62 |
+
for node in model_names:
|
63 |
+
options_arr .append(node["name"])
|
64 |
+
if (node["mark"] == True):
|
65 |
+
markdown_str += f"<div style=\"font-size:16px; color: #5f5f5f; text-align: left\"> • Model: <a href=\'{node['paper_url']}\' target='_blank'>{node['name']}</a><br/> Code released by: <a href=\'{node['orig_author_url']}\' target='_blank'>{node['orig_author']}</a><br/> Model info: <a href=\'{node['sota_info']['sota_link']}\' target='_blank'>{node['sota_info']['task']}</a><br/> Forked <a href=\'{node['fork_url']}\' target='_blank'>code</a><br/><br/></div>"
|
66 |
+
markdown_str += "<div style=\"font-size:12px; color: #9f9f9f; text-align: left\"><b>Note:</b><br/>• Uploaded files are loaded into non-persistent memory for the duration of the computation. They are not saved</div>"
|
67 |
+
limit = "{:,}".format(MAX_INPUT)
|
68 |
+
markdown_str += f"<div style=\"font-size:12px; color: #9f9f9f; text-align: left\">• User uploaded file has a maximum limit of {limit} sentences.</div>"
|
69 |
+
return options_arr,markdown_str
|
70 |
+
|
71 |
+
|
72 |
+
st.set_page_config(page_title='TWC - Compare state-of-the-art models for Sentence Similarity task', page_icon="logo.jpg", layout='centered', initial_sidebar_state='auto',
|
73 |
+
menu_items={
|
74 |
+
'Get help': "mailto:taskswithcode@gmail.com",
|
75 |
+
'Report a Bug': "mailto:taskswithcode@gmail.com",
|
76 |
+
'About': 'This app was created by taskswithcode. http://taskswithcode.com'
|
77 |
+
})
|
78 |
+
col,pad = st.columns([85,15])
|
79 |
+
|
80 |
+
with col:
|
81 |
+
st.image("long_form_logo_with_icon.png")
|
82 |
+
|
83 |
+
|
84 |
+
@st.experimental_memo
|
85 |
+
def load_model(model_name):
|
86 |
+
try:
|
87 |
+
ret_model = None
|
88 |
+
for node in model_names:
|
89 |
+
if (model_name.startswith(node["name"])):
|
90 |
+
obj_class = globals()[node["class"]]
|
91 |
+
ret_model = obj_class()
|
92 |
+
ret_model.init_model(node["model"])
|
93 |
+
assert(ret_model is not None)
|
94 |
+
except Exception as e:
|
95 |
+
st.error("Unable to load model:" + model_name + " " + str(e))
|
96 |
+
pass
|
97 |
+
return ret_model
|
98 |
+
|
99 |
+
|
100 |
+
@st.experimental_memo
|
101 |
+
def cached_compute_similarity(sentences,_model,model_name,main_index):
|
102 |
+
texts,embeddings = _model.compute_embeddings(sentences,is_file=False)
|
103 |
+
results = _model.output_results(None,texts,embeddings,main_index)
|
104 |
+
return results
|
105 |
+
|
106 |
+
|
107 |
+
def uncached_compute_similarity(sentences,_model,model_name,main_index):
|
108 |
+
with st.spinner('Computing vectors for sentences'):
|
109 |
+
texts,embeddings = _model.compute_embeddings(sentences,is_file=False)
|
110 |
+
results = _model.output_results(None,texts,embeddings,main_index)
|
111 |
+
#st.success("Similarity computation complete")
|
112 |
+
return results
|
113 |
+
|
114 |
+
def run_test(model_name,sentences,display_area,main_index,user_uploaded):
|
115 |
+
display_area.text("Loading model:" + model_name)
|
116 |
+
model = load_model(model_name)
|
117 |
+
display_area.text("Model " + model_name + " load complete")
|
118 |
+
try:
|
119 |
+
if (user_uploaded):
|
120 |
+
results = uncached_compute_similarity(sentences,model,model_name,main_index)
|
121 |
+
else:
|
122 |
+
display_area.text("Computing vectors for sentences")
|
123 |
+
results = cached_compute_similarity(sentences,model,model_name,main_index)
|
124 |
+
display_area.text("Similarity computation complete")
|
125 |
+
return results
|
126 |
+
|
127 |
+
except Exception as e:
|
128 |
+
st.error("Some error occurred during prediction" + str(e))
|
129 |
+
st.stop()
|
130 |
+
return {}
|
131 |
+
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
|
136 |
+
def display_results(orig_sentences,main_index,results,response_info):
|
137 |
+
main_sent = f"<div style=\"font-size:14px; color: #2f2f2f; text-align: left\">{response_info}<br/><br/></div>"
|
138 |
+
main_sent += "<div style=\"font-size:14px; color: #6f6f6f; text-align: left\">Results sorted by cosine distance. Closest(1) to furthest(-1) away from main sentence</div>"
|
139 |
+
main_sent += f"<div style=\"font-size:16px; color: #2f2f2f; text-align: left\"><b>Main sentence:</b> {orig_sentences[main_index]}</div>"
|
140 |
+
body_sent = []
|
141 |
+
download_data = {}
|
142 |
+
for key in results:
|
143 |
+
index = orig_sentences.index(key) + 1
|
144 |
+
body_sent.append(f"<div style=\"font-size:16px; color: #2f2f2f; text-align: left\">{index}] {key} <b>{results[key]:.2f}</b></div>")
|
145 |
+
download_data[key] = f"{results[key]:.2f}"
|
146 |
+
main_sent = main_sent + "\n" + '\n'.join(body_sent)
|
147 |
+
st.markdown(main_sent,unsafe_allow_html=True)
|
148 |
+
st.session_state["download_ready"] = json.dumps(download_data,indent=4)
|
149 |
+
|
150 |
+
|
151 |
+
def init_session():
|
152 |
+
st.session_state["download_ready"] = None
|
153 |
+
st.session_state["model_name"] = "ss_test"
|
154 |
+
st.session_state["main_index"] = 1
|
155 |
+
st.session_state["file_name"] = "default"
|
156 |
+
|
157 |
+
def main():
|
158 |
+
init_session()
|
159 |
+
st.markdown("<h4 style='text-align: center;'>Compare state-of-the-art models for Sentence Similarity task</h4>", unsafe_allow_html=True)
|
160 |
+
|
161 |
+
|
162 |
+
try:
|
163 |
+
|
164 |
+
|
165 |
+
with st.form('twc_form'):
|
166 |
+
|
167 |
+
uploaded_file = st.file_uploader("Step 1. Upload text file(one sentence in a line) or choose an example text file below.", type=".txt")
|
168 |
+
|
169 |
+
selected_file_index = st.selectbox(label='Example files ',
|
170 |
+
options = list(dict.keys(example_file_names)), index=0, key = "twc_file")
|
171 |
+
st.write("")
|
172 |
+
options_arr,markdown_str = construct_model_info_for_display()
|
173 |
+
selected_model = st.selectbox(label='Step 2. Select Model',
|
174 |
+
options = options_arr, index=0, key = "twc_model")
|
175 |
+
st.write("")
|
176 |
+
main_index = st.number_input('Step 3. Enter index of sentence in file to make it the main sentence:',value=1,min_value = 1)
|
177 |
+
st.write("")
|
178 |
+
submit_button = st.form_submit_button('Run')
|
179 |
+
|
180 |
+
|
181 |
+
input_status_area = st.empty()
|
182 |
+
display_area = st.empty()
|
183 |
+
if submit_button:
|
184 |
+
start = time.time()
|
185 |
+
if uploaded_file is not None:
|
186 |
+
st.session_state["file_name"] = uploaded_file.name
|
187 |
+
sentences = StringIO(uploaded_file.getvalue().decode("utf-8")).read()
|
188 |
+
else:
|
189 |
+
st.session_state["file_name"] = example_file_names[selected_file_index]
|
190 |
+
sentences = open(example_file_names[selected_file_index]).read()
|
191 |
+
sentences = sentences.split("\n")[:-1]
|
192 |
+
if (len(sentences) < main_index):
|
193 |
+
main_index = len(sentences)
|
194 |
+
st.info("Selected sentence index is larger than number of sentences in file. Truncating to " + str(main_index))
|
195 |
+
if (len(sentences) > MAX_INPUT):
|
196 |
+
st.info(f"Input sentence count exceeds maximum sentence limit. First {MAX_INPUT} out of {len(sentences)} sentences chosen")
|
197 |
+
sentences = sentences[:MAX_INPUT]
|
198 |
+
st.session_state["model_name"] = selected_model
|
199 |
+
st.session_state["main_index"] = main_index
|
200 |
+
results = run_test(selected_model,sentences,display_area,main_index - 1,(uploaded_file is not None))
|
201 |
+
display_area.empty()
|
202 |
+
with display_area.container():
|
203 |
+
response_info = f"Response time - {time.time() - start:.2f} secs for {len(sentences)} sentences"
|
204 |
+
display_results(sentences,main_index - 1,results,response_info)
|
205 |
+
#st.json(results)
|
206 |
+
st.download_button(
|
207 |
+
label="Download results as json",
|
208 |
+
data= st.session_state["download_ready"] if st.session_state["download_ready"] != None else "",
|
209 |
+
disabled = False if st.session_state["download_ready"] != None else True,
|
210 |
+
file_name= (st.session_state["model_name"] + "_" + str(st.session_state["main_index"]) + "_" + '_'.join(st.session_state["file_name"].split(".")[:-1]) + ".json").replace("/","_"),
|
211 |
+
mime='text/json',
|
212 |
+
key ="download"
|
213 |
+
)
|
214 |
+
|
215 |
+
|
216 |
+
|
217 |
+
except Exception as e:
|
218 |
+
st.error("Some error occurred during loading" + str(e))
|
219 |
+
st.stop()
|
220 |
+
|
221 |
+
st.markdown(markdown_str, unsafe_allow_html=True)
|
222 |
+
|
223 |
+
|
224 |
+
|
225 |
+
if __name__ == "__main__":
|
226 |
+
main()
|
227 |
+
|