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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import requests
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
from PyPDF2 import PdfReader
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from openai.embeddings_utils import get_embedding, cosine_similarity
|
| 12 |
+
import openai
|
| 13 |
+
import pkg_resources
|
| 14 |
+
import streamlit as st
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
messages = [
|
| 20 |
+
{"role": "system", "content": "You are SummarizeGPT, a large language model whose expertise is reading and summarizing scientific papers."}
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
class Chatbot():
|
| 24 |
+
|
| 25 |
+
def parse_paper(self, pdf):
|
| 26 |
+
print("Parsing paper")
|
| 27 |
+
number_of_pages = len(pdf.pages)
|
| 28 |
+
print(f"Total number of pages: {number_of_pages}")
|
| 29 |
+
paper_text = []
|
| 30 |
+
for i in range(number_of_pages):
|
| 31 |
+
page = pdf.pages[i]
|
| 32 |
+
page_text = []
|
| 33 |
+
|
| 34 |
+
def visitor_body(text, cm, tm, fontDict, fontSize):
|
| 35 |
+
x = tm[4]
|
| 36 |
+
y = tm[5]
|
| 37 |
+
# ignore header/footer
|
| 38 |
+
if (y > 50 and y < 720) and (len(text.strip()) > 1):
|
| 39 |
+
page_text.append({
|
| 40 |
+
'fontsize': fontSize,
|
| 41 |
+
'text': text.strip().replace('\x03', ''),
|
| 42 |
+
'x': x,
|
| 43 |
+
'y': y
|
| 44 |
+
})
|
| 45 |
+
|
| 46 |
+
_ = page.extract_text(visitor_text=visitor_body)
|
| 47 |
+
|
| 48 |
+
blob_font_size = None
|
| 49 |
+
blob_text = ''
|
| 50 |
+
processed_text = []
|
| 51 |
+
|
| 52 |
+
for t in page_text:
|
| 53 |
+
if t['fontsize'] == blob_font_size:
|
| 54 |
+
blob_text += f" {t['text']}"
|
| 55 |
+
if len(blob_text) >= 2000:
|
| 56 |
+
processed_text.append({
|
| 57 |
+
'fontsize': blob_font_size,
|
| 58 |
+
'text': blob_text,
|
| 59 |
+
'page': i
|
| 60 |
+
})
|
| 61 |
+
blob_font_size = None
|
| 62 |
+
blob_text = ''
|
| 63 |
+
else:
|
| 64 |
+
if blob_font_size is not None and len(blob_text) >= 1:
|
| 65 |
+
processed_text.append({
|
| 66 |
+
'fontsize': blob_font_size,
|
| 67 |
+
'text': blob_text,
|
| 68 |
+
'page': i
|
| 69 |
+
})
|
| 70 |
+
blob_font_size = t['fontsize']
|
| 71 |
+
blob_text = t['text']
|
| 72 |
+
paper_text += processed_text
|
| 73 |
+
print("Done parsing paper")
|
| 74 |
+
# print(paper_text)
|
| 75 |
+
return paper_text
|
| 76 |
+
|
| 77 |
+
def paper_df(self, pdf):
|
| 78 |
+
print('Creating dataframe')
|
| 79 |
+
filtered_pdf= []
|
| 80 |
+
for row in pdf:
|
| 81 |
+
if len(row['text']) < 30:
|
| 82 |
+
continue
|
| 83 |
+
filtered_pdf.append(row)
|
| 84 |
+
df = pd.DataFrame(filtered_pdf)
|
| 85 |
+
print(df.shape)
|
| 86 |
+
print(df.head)
|
| 87 |
+
# remove elements with identical df[text] and df[page] values
|
| 88 |
+
df = df.drop_duplicates(subset=['text', 'page'], keep='first')
|
| 89 |
+
df['length'] = df['text'].apply(lambda x: len(x))
|
| 90 |
+
print('Done creating dataframe')
|
| 91 |
+
return df
|
| 92 |
+
|
| 93 |
+
def calculate_embeddings(self, df):
|
| 94 |
+
print('Calculating embeddings')
|
| 95 |
+
openai.api_key = os.getenv('OPENAI_API_KEY')
|
| 96 |
+
embedding_model = "text-embedding-ada-002"
|
| 97 |
+
# This is going to create embeddings for subsets of the PDF
|
| 98 |
+
embeddings = df.text.apply([lambda x: get_embedding(x, engine=embedding_model)])
|
| 99 |
+
df["embeddings"] = embeddings
|
| 100 |
+
print('Done calculating embeddings')
|
| 101 |
+
print(pkg_resources.get_distribution("openai").version)
|
| 102 |
+
return df
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def search_embeddings(self, df, query, n=3, pprint=True):
|
| 107 |
+
|
| 108 |
+
# Step 1. Get an embedding for the question being asked to the PDF
|
| 109 |
+
query_embedding = get_embedding(
|
| 110 |
+
query,
|
| 111 |
+
engine="text-embedding-ada-002"
|
| 112 |
+
)
|
| 113 |
+
# Step 2. Create a column in the dataframe that contains the cosine similarity (distance) between the query and the text in the dataframe
|
| 114 |
+
df["similarity"] = df.embeddings.apply(lambda x: cosine_similarity(x, query_embedding))
|
| 115 |
+
# Step 3. Sort the dataframe by the similarity column
|
| 116 |
+
results = df.sort_values("similarity", ascending=False, ignore_index=True)
|
| 117 |
+
# make a dictionary of the the first three results with the page number as the key and the text as the value. The page number is a column in the dataframe.
|
| 118 |
+
results = results.head(n)
|
| 119 |
+
global sources
|
| 120 |
+
sources = []
|
| 121 |
+
for i in range(n):
|
| 122 |
+
# append the page number and the text as a dict to the sources list
|
| 123 |
+
sources.append({'Page '+str(results.iloc[i]['page']): results.iloc[i]['text'][:150]+'...'})
|
| 124 |
+
print(sources)
|
| 125 |
+
return results.head(n)
|
| 126 |
+
|
| 127 |
+
def create_prompt(self, df, user_input):
|
| 128 |
+
result = self.search_embeddings(df, user_input, n=3)
|
| 129 |
+
print(result)
|
| 130 |
+
prompt = """You are a large language model whose expertise is reading and and providing answers about research papers.
|
| 131 |
+
You are given a query and a series of text embeddings from a paper in order of their cosine similarity to the query.
|
| 132 |
+
You must take the given embeddings, as well as what you know from your model weights and knowledge of various fields of research to provide an answer to the query
|
| 133 |
+
that lines up with what was provided in the text.
|
| 134 |
+
|
| 135 |
+
Given the question: """+ user_input + """
|
| 136 |
+
|
| 137 |
+
and the following embeddings as data:
|
| 138 |
+
|
| 139 |
+
1.""" + str(result.iloc[0]['text']) + """
|
| 140 |
+
2.""" + str(result.iloc[1]['text']) + """
|
| 141 |
+
3.""" + str(result.iloc[2]['text']) + """
|
| 142 |
+
|
| 143 |
+
Return a detailed answer based on the paper. If the person asks you to summarize what is in the paper, do your best to provide a summary of the paper.:"""
|
| 144 |
+
|
| 145 |
+
print('Done creating prompt')
|
| 146 |
+
return prompt
|
| 147 |
+
|
| 148 |
+
def gpt(self, prompt):
|
| 149 |
+
openai.api_key = os.getenv('OPENAI_API_KEY')
|
| 150 |
+
print('got API key')
|
| 151 |
+
messages.append({"role": "user", "content": prompt})
|
| 152 |
+
r = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages)
|
| 153 |
+
answer = r['choices'][0]['message']['content']
|
| 154 |
+
response = {'answer': answer, 'sources': sources}
|
| 155 |
+
return response
|
| 156 |
+
|
| 157 |
+
def reply(self, prompt):
|
| 158 |
+
print(prompt)
|
| 159 |
+
prompt = self.create_prompt(df, prompt)
|
| 160 |
+
return self.gpt(prompt)
|
| 161 |
+
|
| 162 |
+
def process_pdf(file):
|
| 163 |
+
print("Processing pdf")
|
| 164 |
+
pdf = PdfReader(BytesIO(file))
|
| 165 |
+
chatbot = Chatbot()
|
| 166 |
+
paper_text = chatbot.parse_paper(pdf)
|
| 167 |
+
global df
|
| 168 |
+
df = chatbot.paper_df(paper_text)
|
| 169 |
+
df = chatbot.calculate_embeddings(df)
|
| 170 |
+
print("Done processing pdf")
|
| 171 |
+
|
| 172 |
+
def download_pdf(url):
|
| 173 |
+
chatbot = Chatbot()
|
| 174 |
+
r = requests.get(str(url))
|
| 175 |
+
print(r.headers)
|
| 176 |
+
pdf = PdfReader(BytesIO(r.content))
|
| 177 |
+
paper_text = chatbot.parse_paper(pdf)
|
| 178 |
+
global df
|
| 179 |
+
df = chatbot.paper_df(paper_text)
|
| 180 |
+
df = chatbot.calculate_embeddings(df)
|
| 181 |
+
print("Done processing pdf")
|
| 182 |
+
|
| 183 |
+
def show_pdf(file_content):
|
| 184 |
+
base64_pdf = base64.b64encode(file_content).decode('utf-8')
|
| 185 |
+
pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="800" height="800" type="application/pdf"></iframe>'
|
| 186 |
+
st.markdown(pdf_display, unsafe_allow_html=True)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def main():
|
| 190 |
+
st.title("Research Paper Guru")
|
| 191 |
+
st.subheader("Upload PDF or Enter URL")
|
| 192 |
+
|
| 193 |
+
pdf_option = st.selectbox("Choose an option:", ["Upload PDF", "Enter URL"])
|
| 194 |
+
chatbot = Chatbot()
|
| 195 |
+
|
| 196 |
+
if pdf_option == "Upload PDF":
|
| 197 |
+
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
|
| 198 |
+
if uploaded_file is not None:
|
| 199 |
+
file_content = uploaded_file.read()
|
| 200 |
+
process_pdf(uploaded_file.read())
|
| 201 |
+
st.success("PDF uploaded and processed successfully!")
|
| 202 |
+
show_pdf(file_content)
|
| 203 |
+
|
| 204 |
+
elif pdf_option == "Enter URL":
|
| 205 |
+
url = st.text_input("Enter the URL of the PDF:")
|
| 206 |
+
if url:
|
| 207 |
+
if st.button("Download and process PDF"):
|
| 208 |
+
try:
|
| 209 |
+
r = requests.get(str(url))
|
| 210 |
+
content = r.content
|
| 211 |
+
download_pdf(url)
|
| 212 |
+
st.success("PDF downloaded and processed successfully!")
|
| 213 |
+
show_pdf(content)
|
| 214 |
+
except Exception as e:
|
| 215 |
+
st.error(f"An error occurred while processing the PDF: {e}")
|
| 216 |
+
|
| 217 |
+
query = st.text_input("Enter your query:")
|
| 218 |
+
if query:
|
| 219 |
+
if st.button("Get answer"):
|
| 220 |
+
response = chatbot.reply(query)
|
| 221 |
+
st.write(response['answer'])
|
| 222 |
+
st.write("Sources:")
|
| 223 |
+
for source in response['sources']:
|
| 224 |
+
st.write(source)
|
| 225 |
+
|
| 226 |
+
if __name__ == "__main__":
|
| 227 |
+
main()
|
| 228 |
+
|
requirements.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask
|
| 2 |
+
PyPDF2
|
| 3 |
+
pandas
|
| 4 |
+
openai==0.27.2
|
| 5 |
+
requests
|
| 6 |
+
flask-cors
|
| 7 |
+
matplotlib
|
| 8 |
+
scipy
|
| 9 |
+
plotly
|
| 10 |
+
google-cloud-storage
|
| 11 |
+
gunicorn==20.1.0
|
| 12 |
+
scikit-learn==0.24.1
|
| 13 |
+
streamlit
|