awacke1 commited on
Commit
fbe0fa0
β€’
1 Parent(s): 36b008b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -0
app.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import re
3
+ import pandas as pd
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from transformers import AutoTokenizer, AutoModel
8
+ from tokenizers import Tokenizer, AddedToken
9
+ import streamlit as st
10
+ from st_click_detector import click_detector
11
+
12
+ DEVICE = "cpu"
13
+ MODEL_OPTIONS = ["msmarco-distilbert-base-tas-b", "all-mpnet-base-v2"]
14
+ DESCRIPTION = """
15
+ # Semantic search
16
+ **Enter your query and hit enter**
17
+ Built with πŸ€— Hugging Face's [transformers](https://huggingface.co/transformers/) library, [SentenceBert](https://www.sbert.net/) models, [Streamlit](https://streamlit.io/) and 44k movie descriptions from the Kaggle [Movies Dataset](https://www.kaggle.com/rounakbanik/the-movies-dataset)
18
+ """
19
+
20
+
21
+ @st.cache(
22
+ show_spinner=False,
23
+ hash_funcs={
24
+ AutoModel: lambda _: None,
25
+ AutoTokenizer: lambda _: None,
26
+ dict: lambda _: None,
27
+ },
28
+ )
29
+ def load():
30
+ models, tokenizers, embeddings = [], [], []
31
+ for model_option in MODEL_OPTIONS:
32
+ tokenizers.append(
33
+ AutoTokenizer.from_pretrained(f"sentence-transformers/{model_option}")
34
+ )
35
+ models.append(
36
+ AutoModel.from_pretrained(f"sentence-transformers/{model_option}").to(
37
+ DEVICE
38
+ )
39
+ )
40
+ embeddings.append(np.load("embeddings.npy"))
41
+ embeddings.append(np.load("embeddings2.npy"))
42
+ df = pd.read_csv("movies.csv")
43
+ return tokenizers, models, embeddings, df
44
+
45
+
46
+ tokenizers, models, embeddings, df = load()
47
+
48
+
49
+ def pooling(model_output):
50
+ return model_output.last_hidden_state[:, 0]
51
+
52
+
53
+ def compute_embeddings(texts):
54
+ encoded_input = tokenizers[0](
55
+ texts, padding=True, truncation=True, return_tensors="pt"
56
+ ).to(DEVICE)
57
+
58
+ with torch.no_grad():
59
+ model_output = models[0](**encoded_input, return_dict=True)
60
+
61
+ embeddings = pooling(model_output)
62
+
63
+ return embeddings.cpu().numpy()
64
+
65
+
66
+ def pooling2(model_output, attention_mask):
67
+ token_embeddings = model_output[0]
68
+ input_mask_expanded = (
69
+ attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
70
+ )
71
+ return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
72
+ input_mask_expanded.sum(1), min=1e-9
73
+ )
74
+
75
+
76
+ def compute_embeddings2(list_of_strings):
77
+ encoded_input = tokenizers[1](
78
+ list_of_strings, padding=True, truncation=True, return_tensors="pt"
79
+ ).to(DEVICE)
80
+ with torch.no_grad():
81
+ model_output = models[1](**encoded_input)
82
+ sentence_embeddings = pooling2(model_output, encoded_input["attention_mask"])
83
+ return F.normalize(sentence_embeddings, p=2, dim=1).cpu().numpy()
84
+
85
+
86
+ @st.cache(
87
+ show_spinner=False,
88
+ hash_funcs={Tokenizer: lambda _: None, AddedToken: lambda _: None},
89
+ )
90
+ def semantic_search(query, model_id):
91
+ start = time.time()
92
+ if len(query.strip()) == 0:
93
+ return ""
94
+ if "[Similar:" not in query:
95
+ if model_id == 0:
96
+ query_embedding = compute_embeddings([query])
97
+ else:
98
+ query_embedding = compute_embeddings2([query])
99
+ else:
100
+ match = re.match(r"\[Similar:(\d{1,5}).*", query)
101
+ if match:
102
+ idx = int(match.groups()[0])
103
+ query_embedding = embeddings[model_id][idx : idx + 1, :]
104
+ if query_embedding.shape[0] == 0:
105
+ return ""
106
+ else:
107
+ return ""
108
+ indices = np.argsort(embeddings[model_id] @ np.transpose(query_embedding)[:, 0])[
109
+ -1:-11:-1
110
+ ]
111
+ if len(indices) == 0:
112
+ return ""
113
+ result = "<ol>"
114
+ for i in indices:
115
+ result += f"<li style='padding-top: 10px'><b>{df.iloc[i].title}</b> ({df.iloc[i].release_date}). {df.iloc[i].overview} "
116
+ result += f"<a id='{i}' href='#'>Similar movies</a></li>"
117
+ delay = "%.3f" % (time.time() - start)
118
+ return f"<p><i>Computation time: {delay} seconds</i></p>{result}</ol>"
119
+
120
+
121
+ st.sidebar.markdown(DESCRIPTION)
122
+
123
+ model_choice = st.sidebar.selectbox("Similarity model", options=MODEL_OPTIONS)
124
+ model_id = 0 if model_choice == MODEL_OPTIONS[0] else 1
125
+
126
+ if "query" in st.session_state:
127
+ query = st.text_input("", value=st.session_state["query"])
128
+ else:
129
+ query = st.text_input("", value="time travel")
130
+
131
+ clicked = click_detector(semantic_search(query, model_id))
132
+
133
+ if clicked != "":
134
+ st.markdown(clicked)
135
+ change_query = False
136
+ if "last_clicked" not in st.session_state:
137
+ st.session_state["last_clicked"] = clicked
138
+ change_query = True
139
+ else:
140
+ if clicked != st.session_state["last_clicked"]:
141
+ st.session_state["last_clicked"] = clicked
142
+ change_query = True
143
+ if change_query:
144
+ st.session_state["query"] = f"[Similar:{clicked}] {df.iloc[int(clicked)].title}"
145
+ st.experimental_rerun()