nickmuchi commited on
Commit
6e97504
1 Parent(s): 70b6ae2

Create new file

Browse files
Files changed (1) hide show
  1. app.py +356 -0
app.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from sentence_transformers import SentenceTransformer, CrossEncoder, util
3
+ import os, re
4
+ import torch
5
+ from rank_bm25 import BM25Okapi
6
+ from sklearn.feature_extraction import _stop_words
7
+ import string
8
+ import numpy as np
9
+ import pandas as pd
10
+ from newspaper import Article
11
+ import base64
12
+ import docx2txt
13
+ from io import StringIO
14
+ from PyPDF2 import PdfFileReader
15
+ import validators
16
+ import nltk
17
+ import warnings
18
+ import streamlit as st
19
+ from PIL import Image
20
+
21
+
22
+ nltk.download('punkt')
23
+
24
+ from nltk import sent_tokenize
25
+
26
+ warnings.filterwarnings("ignore")
27
+
28
+ def extract_text_from_url(url: str):
29
+
30
+ '''Extract text from url'''
31
+
32
+ article = Article(url)
33
+ article.download()
34
+ article.parse()
35
+
36
+ # get text
37
+ text = article.text
38
+
39
+ # get article title
40
+ title = article.title
41
+
42
+ return title, text
43
+
44
+ def extract_text_from_file(file):
45
+
46
+ '''Extract text from uploaded file'''
47
+
48
+ # read text file
49
+ if file.type == "text/plain":
50
+ # To convert to a string based IO:
51
+ stringio = StringIO(file.getvalue().decode("utf-8"))
52
+
53
+ # To read file as string:
54
+ file_text = stringio.read()
55
+
56
+ return file_text, None
57
+
58
+ # read pdf file
59
+ elif file.type == "application/pdf":
60
+ pdfReader = PdfFileReader(file)
61
+ count = pdfReader.numPages
62
+ all_text = ""
63
+ pdf_title = pdfReader.getDocumentInfo().title
64
+
65
+ for i in range(count):
66
+
67
+ try:
68
+ page = pdfReader.getPage(i)
69
+ all_text += page.extractText()
70
+
71
+ except:
72
+ continue
73
+
74
+ file_text = all_text
75
+
76
+ return file_text, pdf_title
77
+
78
+ # read docx file
79
+ elif (
80
+ file.type
81
+ == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
82
+ ):
83
+ file_text = docx2txt.process(file)
84
+
85
+ return file_text, None
86
+
87
+ def preprocess_plain_text(text,window_size=3):
88
+
89
+ text = text.encode("ascii", "ignore").decode() # unicode
90
+ text = re.sub(r"https*\S+", " ", text) # url
91
+ text = re.sub(r"@\S+", " ", text) # mentions
92
+ text = re.sub(r"#\S+", " ", text) # hastags
93
+ text = re.sub(r"\s{2,}", " ", text) # over spaces
94
+ #text = re.sub("[^.,!?%$A-Za-z0-9]+", " ", text) # special characters except .,!?
95
+
96
+ #break into lines and remove leading and trailing space on each
97
+ lines = [line.strip() for line in text.splitlines()]
98
+
99
+ # #break multi-headlines into a line each
100
+ chunks = [phrase.strip() for line in lines for phrase in line.split(" ")]
101
+
102
+ # # drop blank lines
103
+ text = '\n'.join(chunk for chunk in chunks if chunk)
104
+
105
+ ## We split this article into paragraphs and then every paragraph into sentences
106
+ paragraphs = []
107
+ for paragraph in text.replace('\n',' ').split("\n\n"):
108
+ if len(paragraph.strip()) > 0:
109
+ paragraphs.append(sent_tokenize(paragraph.strip()))
110
+
111
+ #We combine up to 3 sentences into a passage. You can choose smaller or larger values for window_size
112
+ #Smaller value: Context from other sentences might get lost
113
+ #Lager values: More context from the paragraph remains, but results are longer
114
+ window_size = window_size
115
+ passages = []
116
+ for paragraph in paragraphs:
117
+ for start_idx in range(0, len(paragraph), window_size):
118
+ end_idx = min(start_idx+window_size, len(paragraph))
119
+ passages.append(" ".join(paragraph[start_idx:end_idx]))
120
+
121
+ st.write(f"Sentences: {sum([len(p) for p in paragraphs])}")
122
+ st.write(f"Passages: {len(passages)}")
123
+
124
+ return passages
125
+
126
+ @st.cache(allow_output_mutation=True,suppress_st_warning=True)
127
+ def bi_encode(bi_enc,passages):
128
+
129
+ global bi_encoder
130
+ #We use the Bi-Encoder to encode all passages, so that we can use it with sematic search
131
+ bi_encoder = SentenceTransformer(bi_enc)
132
+
133
+ #quantize the model
134
+ #bi_encoder = quantize_dynamic(model, {Linear, Embedding})
135
+
136
+ #Compute the embeddings using the multi-process pool
137
+ with st.spinner('Encoding passages into a vector space...'):
138
+
139
+ corpus_embeddings = bi_encoder.encode(passages, convert_to_tensor=True, show_progress_bar=True)
140
+
141
+ st.success(f"Embeddings computed. Shape: {corpus_embeddings.shape}")
142
+
143
+ return bi_encoder, corpus_embeddings
144
+
145
+ @st.cache(allow_output_mutation=True)
146
+ def cross_encode():
147
+
148
+ global cross_encoder
149
+ #The bi-encoder will retrieve 100 documents. We use a cross-encoder, to re-rank the results list to improve the quality
150
+ cross_encoder = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-12-v2')
151
+ return cross_encoder
152
+
153
+ @st.cache(allow_output_mutation=True)
154
+ def bm25_tokenizer(text):
155
+
156
+ # We also compare the results to lexical search (keyword search). Here, we use
157
+ # the BM25 algorithm which is implemented in the rank_bm25 package.
158
+ # We lower case our text and remove stop-words from indexing
159
+ tokenized_doc = []
160
+ for token in text.lower().split():
161
+ token = token.strip(string.punctuation)
162
+
163
+ if len(token) > 0 and token not in _stop_words.ENGLISH_STOP_WORDS:
164
+ tokenized_doc.append(token)
165
+ return tokenized_doc
166
+
167
+ @st.cache(allow_output_mutation=True)
168
+ def bm25_api(passages):
169
+
170
+ tokenized_corpus = []
171
+
172
+ for passage in passages:
173
+ tokenized_corpus.append(bm25_tokenizer(passage))
174
+
175
+ bm25 = BM25Okapi(tokenized_corpus)
176
+
177
+ return bm25
178
+
179
+ bi_enc_options = ["multi-qa-mpnet-base-dot-v1","all-mpnet-base-v2","multi-qa-MiniLM-L6-cos-v1"]
180
+
181
+ def display_df_as_table(model,top_k,score='score'):
182
+ # Display the df with text and scores as a table
183
+ df = pd.DataFrame([(hit[score],passages[hit['corpus_id']]) for hit in model[0:top_k]],columns=['Score','Text'])
184
+ df['Score'] = round(df['Score'],2)
185
+
186
+ return df
187
+
188
+ #Streamlit App
189
+
190
+ st.title("Semantic Search with Retrieve & Rerank 📝")
191
+
192
+ """
193
+ [![](https://img.shields.io/twitter/follow/nickmuchi?label=@nickmuchi&style=social)](https://twitter.com/nickmuchi)
194
+ """
195
+
196
+ window_size = st.sidebar.slider("Paragraph Window Size",min_value=1,max_value=10,value=3,key=
197
+ 'slider')
198
+
199
+ bi_encoder_type = st.sidebar.selectbox("Bi-Encoder", options=bi_enc_options, key='sbox')
200
+
201
+ top_k = st.sidebar.slider("Number of Top Hits Generated",min_value=1,max_value=5,value=2)
202
+
203
+ # This function will search all wikipedia articles for passages that
204
+ # answer the query
205
+ def search_func(query, top_k=top_k):
206
+
207
+ global bi_encoder, cross_encoder
208
+
209
+ st.subheader(f"Search Query: {query}")
210
+
211
+ if url_text:
212
+
213
+ st.write(f"Document Header: {title}")
214
+
215
+ elif pdf_title:
216
+
217
+ st.write(f"Document Header: {pdf_title}")
218
+
219
+ ##### BM25 search (lexical search) #####
220
+ bm25_scores = bm25.get_scores(bm25_tokenizer(query))
221
+ top_n = np.argpartition(bm25_scores, -5)[-5:]
222
+ bm25_hits = [{'corpus_id': idx, 'score': bm25_scores[idx]} for idx in top_n]
223
+ bm25_hits = sorted(bm25_hits, key=lambda x: x['score'], reverse=True)
224
+
225
+ st.subheader(f"Top-{top_k} lexical search (BM25) hits")
226
+
227
+ bm25_df = display_df_as_table(bm25_hits,top_k)
228
+ st.write(bm25_df.to_html(index=False), unsafe_allow_html=True)
229
+
230
+ ##### Sematic Search #####
231
+ # Encode the query using the bi-encoder and find potentially relevant passages
232
+ question_embedding = bi_encoder.encode(query, convert_to_tensor=True)
233
+ question_embedding = question_embedding.cpu()
234
+ hits = util.semantic_search(question_embedding, corpus_embeddings, top_k=top_k,score_function=util.dot_score)
235
+ hits = hits[0] # Get the hits for the first query
236
+
237
+ ##### Re-Ranking #####
238
+ # Now, score all retrieved passages with the cross_encoder
239
+ cross_inp = [[query, passages[hit['corpus_id']]] for hit in hits]
240
+ cross_scores = cross_encoder.predict(cross_inp)
241
+
242
+ # Sort results by the cross-encoder scores
243
+ for idx in range(len(cross_scores)):
244
+ hits[idx]['cross-score'] = cross_scores[idx]
245
+
246
+ # Output of top-3 hits from bi-encoder
247
+ st.markdown("\n-------------------------\n")
248
+ st.subheader(f"Top-{top_k} Bi-Encoder Retrieval hits")
249
+ hits = sorted(hits, key=lambda x: x['score'], reverse=True)
250
+
251
+ cross_df = display_df_as_table(hits,top_k)
252
+ st.write(cross_df.to_html(index=False), unsafe_allow_html=True)
253
+
254
+ # Output of top-3 hits from re-ranker
255
+ st.markdown("\n-------------------------\n")
256
+ st.subheader(f"Top-{top_k} Cross-Encoder Re-ranker hits")
257
+ hits = sorted(hits, key=lambda x: x['cross-score'], reverse=True)
258
+
259
+ rerank_df = display_df_as_table(hits,top_k,'cross-score')
260
+ st.write(rerank_df.to_html(index=False), unsafe_allow_html=True)
261
+
262
+ st.markdown(
263
+ """
264
+ - The app supports asymmetric Semantic search which seeks to improve search accuracy of documents/URL by understanding the content of the search query in contrast to traditional search engines which only find documents based on lexical matches.
265
+ - The idea behind semantic search is to embed all entries in your corpus, whether they be sentences, paragraphs, or documents, into a vector space. At search time, the query is embedded into the same vector space and the closest embeddings from your corpus are found. These entries should have a high semantic overlap with the query.
266
+ - The all-* models where trained on all available training data (more than 1 billion training pairs) and are designed as general purpose models. The all-mpnet-base-v2 model provides the best quality, while all-MiniLM-L6-v2 is 5 times faster and still offers good quality. The models used have been trained on broad datasets, however, if your document/corpus is specialised, such as for science or economics, the results returned might be unsatisfactory.""")
267
+
268
+ st.markdown("""There models available to choose from:""")
269
+
270
+ st.markdown(
271
+ """
272
+ Model Source:
273
+ - Bi-Encoders - [multi-qa-mpnet-base-dot-v1](https://huggingface.co/sentence-transformers/multi-qa-mpnet-base-dot-v1), [all-mpnet-base-v2](https://huggingface.co/sentence-transformers/all-mpnet-base-v2), [multi-qa-MiniLM-L6-cos-v1](https://huggingface.co/sentence-transformers/multi-qa-MiniLM-L6-cos-v1) and [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2)
274
+ - Cross-Encoder - [cross-encoder/ms-marco-MiniLM-L-12-v2](https://huggingface.co/cross-encoder/ms-marco-MiniLM-L-12-v2)""")
275
+
276
+ st.markdown(
277
+ """
278
+ Code and App Inspiration Source: [Sentence Transformers](https://www.sbert.net/examples/applications/retrieve_rerank/README.html)""")
279
+
280
+ st.markdown(
281
+ """
282
+ Quick summary of the purposes of a Bi and Cross-encoder below, the image and info were adapted from [www.sbert.net](https://www.sbert.net/examples/applications/semantic-search/README.html):""")
283
+
284
+ st.markdown(
285
+ """
286
+ - Bi-Encoder (Retrieval): The Bi-encoder is responsible for independently embedding the sentences and search queries into a vector space. The result is then passed to the cross-encoder for checking the relevance/similarity between the query and sentences.
287
+ - Cross-Encoder (Re-Ranker): A re-ranker based on a Cross-Encoder can substantially improve the final results for the user. The query and a possible document is passed simultaneously to transformer network, which then outputs a single score between 0 and 1 indicating how relevant the document is for the given query. The cross-encoder further boost the performance, especially when you search over a corpus for which the bi-encoder was not trained for.""")
288
+
289
+ st.image(Image.open('encoder.png'), caption='Retrieval and Re-Rank')
290
+
291
+ st.markdown("""
292
+ In order to use the app:
293
+ - Select the preferred Sentence Transformer model (Bi-Encoder).
294
+ - Select the number of sentences per paragraph to partition your corpus (Window-Size), if you choose a small value the context from the other sentences might get lost and for larger values the results might take longer to generate.
295
+ - Select the number of top hits to be generated.
296
+ - Paste the URL with your corpus or upload your preferred document in txt, pdf or Word format.
297
+ - Semantic Search away!! """
298
+ )
299
+
300
+ st.markdown("---")
301
+
302
+ def clear_text():
303
+ st.session_state["text_url"] = ""
304
+ st.session_state["text_input"]= ""
305
+
306
+ def clear_search_text():
307
+ st.session_state["text_input"]= ""
308
+
309
+ url_text = st.text_input("Please Enter a url here",value="https://www.rba.gov.au/monetary-policy/rba-board-minutes/2022/2022-05-03.html",key='text_url',on_change=clear_search_text)
310
+
311
+ st.markdown(
312
+ "<h3 style='text-align: center; color: red;'>OR</h3>",
313
+ unsafe_allow_html=True,
314
+ )
315
+
316
+ upload_doc = st.file_uploader("Upload a .txt, .pdf, .docx file",key="upload")
317
+
318
+ search_query = st.text_input("Please Enter your search query here",value="What are the expectations for inflation for Australia?",key="text_input")
319
+
320
+ if validators.url(url_text):
321
+ #if input is URL
322
+ title, text = extract_text_from_url(url_text)
323
+ passages = preprocess_plain_text(text,window_size=window_size)
324
+
325
+ elif upload_doc:
326
+
327
+ text, pdf_title = extract_text_from_file(upload_doc)
328
+ passages = preprocess_plain_text(text,window_size=window_size)
329
+
330
+ col1, col2 = st.columns(2)
331
+
332
+ with col1:
333
+ search = st.button("Search",key='search_but', help='Click to Search!!')
334
+
335
+ with col2:
336
+ clear = st.button("Clear Text Input", on_click=clear_text,key='clear',help='Click to clear the URL input and search query')
337
+
338
+ if search:
339
+ if bi_encoder_type:
340
+
341
+ with st.spinner(
342
+ text=f"Loading {bi_encoder_type} bi-encoder and embedding document into vector space. This might take a few seconds depending on the length of your document..."
343
+ ):
344
+ bi_encoder, corpus_embeddings = bi_encode(bi_encoder_type,passages)
345
+ cross_encoder = cross_encode()
346
+ bm25 = bm25_api(passages)
347
+
348
+ with st.spinner(
349
+ text="Embedding completed, searching for relevant text for given query and hits..."):
350
+
351
+ search_func(search_query,top_k)
352
+
353
+ st.markdown("""
354
+ """)
355
+
356
+ st.markdown("![visitor badge](https://visitor-badge.glitch.me/badge?page_id=nickmuchi-semantic-search-with-retrieve-and-rerank)")