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

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -358
app.py DELETED
@@ -1,358 +0,0 @@
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(
200
- "Bi-Encoder", options=bi_enc_options, key='sbox')
201
- )
202
-
203
- top_k = st.sidebar.slider("Number of Top Hits Generated",min_value=1,max_value=5,value=2)
204
-
205
- # This function will search all wikipedia articles for passages that
206
- # answer the query
207
- def search_func(query, top_k=top_k):
208
-
209
- global bi_encoder, cross_encoder
210
-
211
- st.subheader(f"Search Query: {query}")
212
-
213
- if url_text:
214
-
215
- st.write(f"Document Header: {title}")
216
-
217
- elif pdf_title:
218
-
219
- st.write(f"Document Header: {pdf_title}")
220
-
221
- ##### BM25 search (lexical search) #####
222
- bm25_scores = bm25.get_scores(bm25_tokenizer(query))
223
- top_n = np.argpartition(bm25_scores, -5)[-5:]
224
- bm25_hits = [{'corpus_id': idx, 'score': bm25_scores[idx]} for idx in top_n]
225
- bm25_hits = sorted(bm25_hits, key=lambda x: x['score'], reverse=True)
226
-
227
- st.subheader(f"Top-{top_k} lexical search (BM25) hits")
228
-
229
- bm25_df = display_df_as_table(bm25_hits,top_k)
230
- st.write(bm25_df.to_html(index=False), unsafe_allow_html=True)
231
-
232
- ##### Sematic Search #####
233
- # Encode the query using the bi-encoder and find potentially relevant passages
234
- question_embedding = bi_encoder.encode(query, convert_to_tensor=True)
235
- question_embedding = question_embedding.cpu()
236
- hits = util.semantic_search(question_embedding, corpus_embeddings, top_k=top_k,score_function=util.dot_score)
237
- hits = hits[0] # Get the hits for the first query
238
-
239
- ##### Re-Ranking #####
240
- # Now, score all retrieved passages with the cross_encoder
241
- cross_inp = [[query, passages[hit['corpus_id']]] for hit in hits]
242
- cross_scores = cross_encoder.predict(cross_inp)
243
-
244
- # Sort results by the cross-encoder scores
245
- for idx in range(len(cross_scores)):
246
- hits[idx]['cross-score'] = cross_scores[idx]
247
-
248
- # Output of top-3 hits from bi-encoder
249
- st.markdown("\n-------------------------\n")
250
- st.subheader(f"Top-{top_k} Bi-Encoder Retrieval hits")
251
- hits = sorted(hits, key=lambda x: x['score'], reverse=True)
252
-
253
- cross_df = display_df_as_table(hits,top_k)
254
- st.write(cross_df.to_html(index=False), unsafe_allow_html=True)
255
-
256
- # Output of top-3 hits from re-ranker
257
- st.markdown("\n-------------------------\n")
258
- st.subheader(f"Top-{top_k} Cross-Encoder Re-ranker hits")
259
- hits = sorted(hits, key=lambda x: x['cross-score'], reverse=True)
260
-
261
- rerank_df = display_df_as_table(hits,top_k,'cross-score')
262
- st.write(rerank_df.to_html(index=False), unsafe_allow_html=True)
263
-
264
- st.markdown(
265
- """
266
- - 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.
267
- - 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.
268
- - 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.""")
269
-
270
- st.markdown("""There models available to choose from:""")
271
-
272
- st.markdown(
273
- """
274
- Model Source:
275
- - 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)
276
- - Cross-Encoder - [cross-encoder/ms-marco-MiniLM-L-12-v2](https://huggingface.co/cross-encoder/ms-marco-MiniLM-L-12-v2)""")
277
-
278
- st.markdown(
279
- """
280
- Code and App Inspiration Source: [Sentence Transformers](https://www.sbert.net/examples/applications/retrieve_rerank/README.html)""")
281
-
282
- st.markdown(
283
- """
284
- 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):""")
285
-
286
- st.markdown(
287
- """
288
- - 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.
289
- - 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.""")
290
-
291
- st.image(Image.open('encoder.png'), caption='Retrieval and Re-Rank')
292
-
293
- st.markdown("""
294
- In order to use the app:
295
- - Select the preferred Sentence Transformer model (Bi-Encoder).
296
- - 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.
297
- - Select the number of top hits to be generated.
298
- - Paste the URL with your corpus or upload your preferred document in txt, pdf or Word format.
299
- - Semantic Search away!! """
300
- )
301
-
302
- st.markdown("---")
303
-
304
- def clear_text():
305
- st.session_state["text_url"] = ""
306
- st.session_state["text_input"]= ""
307
-
308
- def clear_search_text():
309
- st.session_state["text_input"]= ""
310
-
311
- 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)
312
-
313
- st.markdown(
314
- "<h3 style='text-align: center; color: red;'>OR</h3>",
315
- unsafe_allow_html=True,
316
- )
317
-
318
- upload_doc = st.file_uploader("Upload a .txt, .pdf, .docx file",key="upload")
319
-
320
- search_query = st.text_input("Please Enter your search query here",value="What are the expectations for inflation for Australia?",key="text_input")
321
-
322
- if validators.url(url_text):
323
- #if input is URL
324
- title, text = extract_text_from_url(url_text)
325
- passages = preprocess_plain_text(text,window_size=window_size)
326
-
327
- elif upload_doc:
328
-
329
- text, pdf_title = extract_text_from_file(upload_doc)
330
- passages = preprocess_plain_text(text,window_size=window_size)
331
-
332
- col1, col2 = st.columns(2)
333
-
334
- with col1:
335
- search = st.button("Search",key='search_but', help='Click to Search!!')
336
-
337
- with col2:
338
- clear = st.button("Clear Text Input", on_click=clear_text,key='clear',help='Click to clear the URL input and search query')
339
-
340
- if search:
341
- if bi_encoder_type:
342
-
343
- with st.spinner(
344
- 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..."
345
- ):
346
- bi_encoder, corpus_embeddings = bi_encode(bi_encoder_type,passages)
347
- cross_encoder = cross_encode()
348
- bm25 = bm25_api(passages)
349
-
350
- with st.spinner(
351
- text="Embedding completed, searching for relevant text for given query and hits..."):
352
-
353
- search_func(search_query,top_k)
354
-
355
- st.markdown("""
356
- """)
357
-
358
- st.markdown("![visitor badge](https://visitor-badge.glitch.me/badge?page_id=nickmuchi-semantic-search-with-retrieve-and-rerank)")