Create new file
Browse files
app.py
ADDED
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder, util
|
2 |
+
import re
|
3 |
+
from newspaper3k import Article
|
4 |
+
import docx2txt
|
5 |
+
from io import StringIO
|
6 |
+
from PyPDF2 import PdfFileReader
|
7 |
+
import validators
|
8 |
+
import streamlit as st
|
9 |
+
import nltk
|
10 |
+
import pandas as pd
|
11 |
+
import requests
|
12 |
+
|
13 |
+
nltk.download('punkt')
|
14 |
+
|
15 |
+
from nltk import sent_tokenize
|
16 |
+
|
17 |
+
warnings.filterwarnings("ignore")
|
18 |
+
|
19 |
+
|
20 |
+
def extarct_test_from_url(url: str):
|
21 |
+
article = Article(url)
|
22 |
+
article.download()
|
23 |
+
article.parse
|
24 |
+
|
25 |
+
# receiving text
|
26 |
+
text = article.text
|
27 |
+
title = article.title
|
28 |
+
return title, text
|
29 |
+
|
30 |
+
|
31 |
+
def extract_text_from_file(file):
|
32 |
+
if file.type == "text/plain":
|
33 |
+
# To convert to a string based IO:
|
34 |
+
stringio = StringIO(file.getvalue().decode("utf-8"))
|
35 |
+
file_text = stringio.read()
|
36 |
+
return file_text, None
|
37 |
+
elif file.type == "application/pdf":
|
38 |
+
pdfReader = PdfFileReader(file)
|
39 |
+
count = pdfReader.numPages
|
40 |
+
all_text = ""
|
41 |
+
pdf_title = pdfReader.getDocumentInfo().title
|
42 |
+
for i in range(count):
|
43 |
+
try:
|
44 |
+
page = pdfReader.getPage(i)
|
45 |
+
all_text += page.extractText()
|
46 |
+
except:
|
47 |
+
continue
|
48 |
+
file_text = all_text
|
49 |
+
return file_text, pdf_title
|
50 |
+
# read docx file
|
51 |
+
elif (
|
52 |
+
file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"):
|
53 |
+
file_text = docx2txt.process(file)
|
54 |
+
return file_text, None
|
55 |
+
|
56 |
+
|
57 |
+
def preprocess_plain_text(text, window_size=3):
|
58 |
+
text = text.encode("ascii", "ignore").decode() # unicode
|
59 |
+
text = re.sub(r"https*\S+", " ", text) # url
|
60 |
+
text = re.sub(r"@\S+", " ", text) # mentions
|
61 |
+
text = re.sub(r"#\S+", " ", text) # hastags
|
62 |
+
text = re.sub(r"\s{2,}", " ", text) # over spaces
|
63 |
+
text = re.sub("[^.,!?%$A-Za-z0-9]+", " ", text) # special characters except .,!?
|
64 |
+
# removing spaces
|
65 |
+
lines = [line.strip() for line in text.splitlines()]
|
66 |
+
# break multi-headlines into a line each
|
67 |
+
chunks = [phrase.strip() for line in lines for phrase in line.split(" ")]
|
68 |
+
# drop blank lines
|
69 |
+
text = '\n'.join(chunk for chunk in chunks if chunk)
|
70 |
+
paragraphs = []
|
71 |
+
for paragraph in text.replace('\n', ' ').split("\n\n"):
|
72 |
+
if len(paragraph.strip()) > 0:
|
73 |
+
paragraphs.append(sent_tokenize(paragraph.strip()))
|
74 |
+
|
75 |
+
window_size = window_size
|
76 |
+
passages = []
|
77 |
+
for paragraph in paragraphs:
|
78 |
+
for start_idx in range(0, len(paragraph), window_size):
|
79 |
+
end_idx = min(start_idx + window_size, len(paragraph))
|
80 |
+
passages.append(" ".join(paragraph[start_idx:end_idx]))
|
81 |
+
|
82 |
+
return passages
|
83 |
+
|
84 |
+
|
85 |
+
def biencode(bi_enc, passages):
|
86 |
+
global bi_encoder
|
87 |
+
bi_encoder = SentenceTransformer(bi_enc)
|
88 |
+
|
89 |
+
# Compute the embeddings using the multi-process pool
|
90 |
+
with st.spinner('Encoding passages into a vector space...'):
|
91 |
+
corpus_embeddings = bi_encoder.encode(passages, convert_to_tensor=True, show_progress_bar=True)
|
92 |
+
|
93 |
+
st.success(f"Embeddings computed. Shape: {corpus_embeddings.shape}")
|
94 |
+
|
95 |
+
return bi_encoder, corpus_embeddings
|
96 |
+
|
97 |
+
|
98 |
+
def cross_encode():
|
99 |
+
global cross_encoder
|
100 |
+
# cross-encoder to re-rank the results list to improve the quality
|
101 |
+
cross_encoder = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-12-v2')
|
102 |
+
return cross_encoder
|
103 |
+
|
104 |
+
|
105 |
+
def display_as_table(model, top_k, score='score'):
|
106 |
+
# Display the df with text and scores as a table
|
107 |
+
df = pd.DataFrame([(hit[score], passages[hit['corpus_id']]) for hit in model[0:top_k]], columns=['Score', 'Text'])
|
108 |
+
df['Score'] = round(df['Score'], 2)
|
109 |
+
|
110 |
+
return df
|
111 |
+
|
112 |
+
|
113 |
+
def search_func(query, top_k=top_k):
|
114 |
+
global bi_encoder, cross_encoder
|
115 |
+
st.subheader(f"Search Query: {query}")
|
116 |
+
if url_text:
|
117 |
+
st.write(f"Document Header: {title}")
|
118 |
+
elif pdf_title:
|
119 |
+
st.write(f"Document Header: {pdf_title}")
|
120 |
+
question_embedding = bi_encoder.encode(query, convert_to_tensor=True)
|
121 |
+
question_embedding = question_embedding.cpu()
|
122 |
+
hits = util.semantic_search(question_embedding, corpus_embeddings, top_k=top_k, score_function=util.dot_score)
|
123 |
+
hits = hits[0]
|
124 |
+
# score all retrieved passages with the cross_encoder
|
125 |
+
cross_inp = [[query, passages[hit['corpus_id']]] for hit in hits]
|
126 |
+
cross_scores = cross_encoder.predict(cross_inp)
|
127 |
+
# Sort results by the cross-encoder scores
|
128 |
+
for idx in range(len(cross_scores)):
|
129 |
+
hits[idx]['cross-score'] = cross_scores[idx]
|
130 |
+
# Output of top-3 hits
|
131 |
+
st.markdown("\n-------------------------\n")
|
132 |
+
st.subheader(f"Top-{top_k} Cross-Encoder Re-ranker hits")
|
133 |
+
hits = sorted(hits, key=lambda x: x['cross-score'], reverse=True)
|
134 |
+
|
135 |
+
rerank_df = display_df_as_table(hits, top_k, 'cross-score')
|
136 |
+
st.write(rerank_df.to_html(index=False), unsafe_allow_html=True)
|
137 |
+
|
138 |
+
def clear_text():
|
139 |
+
st.session_state["text_url"] = ""
|
140 |
+
st.session_state["text_input"] = ""
|
141 |
+
|
142 |
+
def clear_search_text():
|
143 |
+
st.session_state["text_input"] = ""
|
144 |
+
|
145 |
+
url_text = st.text_input("Enter a url here", value="https://en.wikipedia.org/wiki/Virat_Kohli", key='text_url',
|
146 |
+
on_change=clear_search_text)
|
147 |
+
st.markdown(
|
148 |
+
"<h3 style='text-align: center; color: red;'>OR</h3>",
|
149 |
+
unsafe_allow_html=True, )
|
150 |
+
upload_doc = st.file_uploader("Upload a .txt, .pdf, .docx file", key="upload")
|
151 |
+
|
152 |
+
search_query = st.text_input("Enter your search query here", value="How many Centuries Virat Kohli scored?",
|
153 |
+
key="text_input")
|
154 |
+
if validators.url(url_text):
|
155 |
+
# if input is URL
|
156 |
+
title, text = extract_text_from_url(url_text)
|
157 |
+
passages = preprocess_plain_text(text, window_size=window_size)
|
158 |
+
|
159 |
+
elif upload_doc:
|
160 |
+
|
161 |
+
text, pdf_title = extract_text_from_file(upload_doc)
|
162 |
+
passages = preprocess_plain_text(text, window_size=window_size)
|
163 |
+
|
164 |
+
col1, col2 = st.columns(2)
|
165 |
+
|
166 |
+
with col1:
|
167 |
+
search = st.button("Search", key='search_but', help='Click to Search!!')
|
168 |
+
|
169 |
+
with col2:
|
170 |
+
clear = st.button("Clear Text Input", on_click=clear_text, key='clear',
|
171 |
+
help='Click to clear the URL input and search query')
|
172 |
+
|
173 |
+
if search:
|
174 |
+
if bi_encoder_type:
|
175 |
+
with st.spinner(
|
176 |
+
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..."
|
177 |
+
):
|
178 |
+
bi_encoder, corpus_embeddings = bi_encode(bi_encoder_type, passages)
|
179 |
+
cross_encoder = cross_encode()
|
180 |
+
bm25 = bm25_api(passages)
|
181 |
+
|
182 |
+
with st.spinner(
|
183 |
+
text="Embedding completed, searching for relevant text for given query and hits..."):
|
184 |
+
search_func(search_query, top_k)
|
185 |
+
|
186 |
+
st.markdown(""" """)
|