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