DeepSoft-Tech commited on
Commit
9acf74a
·
verified ·
1 Parent(s): 0149b5c

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +263 -0
  2. requirements.txt +14 -0
app.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ from io import BytesIO
4
+ from PyPDF2 import PdfReader
5
+ import pandas as pd
6
+ from openai.embeddings_utils import get_embedding, cosine_similarity
7
+ import openai
8
+ import streamlit as st
9
+ import numpy as np
10
+ import base64
11
+ import faiss
12
+
13
+
14
+
15
+ messages = [
16
+ {"role": "system", "content": "You are SummarizeGPT, a large language model whose expertise is reading and summarizing scientific papers."}
17
+ ]
18
+
19
+ class Chatbot():
20
+
21
+ def parse_paper(self, pdf):
22
+ # This function parses the PDF and returns a list of dictionaries with the text,
23
+ # font size, and x and y coordinates of each text element in the PDF
24
+ print("Parsing paper")
25
+ number_of_pages = len(pdf.pages)
26
+ print(f"Total number of pages: {number_of_pages}")
27
+ # This is the list that will contain all the text elements in the PDF and will be returned by the function
28
+ paper_text = []
29
+
30
+ for i in range(number_of_pages):
31
+ # Iterate through each page in the PDF, and extract the text elements. pdf.pages is a list of Page objects.
32
+ page = pdf.pages[i]
33
+ # This is the list that will contain all the text elements in the current page
34
+ page_text = []
35
+
36
+ def visitor_body(text, cm, tm, fontDict, fontSize):
37
+ # tm is a 6-element tuple of floats that represent a 2x3 matrix, which is the text matrix for the text.
38
+ # The first two elements are the horizontal and vertical scaling factors, the third and fourth elements
39
+ # are the horizontal and vertical shear factors, and the fifth and sixth elements are the horizontal and vertical translation factors.
40
+
41
+ # x and y are the coordinates of the text element
42
+ x = tm[4]
43
+ y = tm[5]
44
+
45
+ # ignore header/footer, and empty text.
46
+ # The y coordinate is used to filter out the header and footer of the paper
47
+ # The length of the text is used to filter out empty text
48
+ if (y > 50 and y < 720) and (len(text.strip()) > 1):
49
+ page_text.append({
50
+ # The fontsize is used to separate paragraphs into different elements in the paper_text list
51
+ 'fontsize': fontSize,
52
+ # The text is stripped of whitespace and the \x03 character
53
+ 'text': text.strip().replace('\x03', ''),
54
+ # The x and y coordinates are used to separate paragraphs into different elements in the paper_text list
55
+ 'x': x,
56
+ 'y': y
57
+ })
58
+
59
+ # Extract the text elements from the page
60
+ _ = page.extract_text(visitor_text=visitor_body)
61
+ print(f'Page {i} text", {page_text}')
62
+
63
+
64
+ blob_font_size = None
65
+ blob_text = ''
66
+ processed_text = []
67
+
68
+ for t in page_text:
69
+ if t['fontsize'] == blob_font_size:
70
+ blob_text += f" {t['text']}"
71
+ if len(blob_text) >= 2000:
72
+ processed_text.append({
73
+ 'fontsize': blob_font_size,
74
+ 'text': blob_text,
75
+ 'page': i
76
+ })
77
+ blob_font_size = None
78
+ blob_text = ''
79
+ else:
80
+ if blob_font_size is not None and len(blob_text) >= 1:
81
+ processed_text.append({
82
+ 'fontsize': blob_font_size,
83
+ 'text': blob_text,
84
+ 'page': i
85
+ })
86
+ blob_font_size = t['fontsize']
87
+ blob_text = t['text']
88
+ paper_text += processed_text
89
+ print("Done parsing paper")
90
+ print(paper_text)
91
+
92
+ return paper_text
93
+
94
+ def paper_df(self, pdf):
95
+ print('Creating dataframe')
96
+ filtered_pdf= []
97
+ for row in pdf:
98
+ # This will use the get method to safely access the 'text' key in the row dictionary,
99
+ # and if the key is not present, it will use an empty string as a default value. This
100
+ # should prevent a KeyError from occurring.
101
+ if len(row.get('text', '')) < 30:
102
+ continue
103
+ filtered_pdf.append(row)
104
+ print("Filtered paper_text", filtered_pdf)
105
+ df = pd.DataFrame(filtered_pdf)
106
+ print(df.shape)
107
+ print(df.head)
108
+ # remove elements with identical df[text] and df[page] values
109
+ df = df.drop_duplicates(subset=['text', 'page'], keep='first')
110
+ df['length'] = df['text'].apply(lambda x: len(x))
111
+ print('Done creating dataframe')
112
+ return df
113
+
114
+ def calculate_embeddings(self, df):
115
+ print('Calculating embeddings')
116
+ openai.api_key = os.getenv('OPENAI_API_KEY')
117
+ embedding_model = "text-embedding-ada-002"
118
+ # Get the embeddings for each text element in the dataframe
119
+ embeddings = df.text.apply(lambda x: get_embedding(x, engine=embedding_model))
120
+ embeddings = np.vstack(embeddings, dtype=np.float32)
121
+ return embeddings
122
+
123
+ def search_embeddings(self, embeddings, df, query, n=3, pprint=True):
124
+
125
+ # Step 1. Get an embedding for the question being asked to the PDF
126
+ query_embedding = get_embedding(query, engine="text-embedding-ada-002")
127
+ query_embedding = np.array(query_embedding, dtype=np.float32)
128
+ # Step 2. Create a FAISS index and add the embeddings
129
+ d = embeddings.shape[1]
130
+ # Use the L2 distance metric
131
+ index = faiss.IndexFlatL2(d)
132
+ print("Embeddings shape:", embeddings.shape)
133
+ print("Embeddings data type:", type(embeddings))
134
+ index.add(embeddings)
135
+
136
+
137
+ # Step 3. Search the index for the embedding of the question
138
+
139
+ D, I = index.search(query_embedding.reshape(1,d), n)
140
+
141
+ # Step 4. Get the top n results from the dataframe
142
+ results = df.iloc[I[0]]
143
+ results['similarity'] = D[0]
144
+ results = results.reset_index(drop=True)
145
+
146
+ # Make a dictionary of the first n results with the page number as the key and the text as the value
147
+
148
+ global sources
149
+ sources = []
150
+ for i in range(n):
151
+ # append the page number and the text as a dict to the sources list
152
+ sources.append({'Page '+str(results.iloc[i]['page']): results.iloc[i]['text'][:150]+'...'})
153
+ print(sources)
154
+ return results.head(n)
155
+
156
+ def create_prompt(self, embeddings, df, user_input):
157
+ result = self.search_embeddings(embeddings, df, user_input, n=3)
158
+ print(result)
159
+ prompt = """
160
+ You are Research Paper Guru
161
+ The user is going to ask you a question about a research paper after uploading a PDF of the paper.
162
+ You are a large language model whose expertise is reading and and providing answers to their queries, based on what you know about the subject as well as what you know about the text given to you.
163
+
164
+ The user asks: """+ user_input + """
165
+
166
+ And the information about the paper that is relevant to the question is:
167
+
168
+ 1.""" + str(result.iloc[0]['text']) + """
169
+ 2.""" + str(result.iloc[1]['text']) + """
170
+ 3.""" + str(result.iloc[2]['text']) + """
171
+
172
+ Knowing what you know about this answer, as well as being able to navigate this knowledge in conjuction with what is being said in the paper, provide an answer to the user. If the person asks you to summarize what is in the paper, do your best to provide a summary of the paper.
173
+ The goal here is to keep the user happy and satisfied that you have given them the best answer to the question to the best of your knowledge. If necessary, you can also point them to outside resources for more information.:"""
174
+
175
+ print('Done creating prompt')
176
+ return prompt
177
+
178
+ def gpt(self, prompt):
179
+ openai.api_key = os.getenv('OPENAI_API_KEY')
180
+ print('got API key')
181
+ messages.append({"role": "user", "content": prompt})
182
+ r = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages)
183
+ answer = r['choices'][0]['message']['content']
184
+ response = {'answer': answer, 'sources': sources}
185
+ return response
186
+
187
+ def reply(self, embeddings, user_input):
188
+ print(user_input)
189
+ prompt = self.create_prompt(embeddings, df, user_input)
190
+ return self.gpt(prompt)
191
+
192
+ def process_pdf(file):
193
+ print("Processing pdf")
194
+ pdf = PdfReader(BytesIO(file))
195
+ chatbot = Chatbot()
196
+ paper_text = chatbot.parse_paper(pdf)
197
+ global df
198
+ df = chatbot.paper_df(paper_text)
199
+ embeddings = chatbot.calculate_embeddings(df)
200
+ print("Done processing pdf")
201
+ return embeddings
202
+
203
+ def download_pdf(url):
204
+ chatbot = Chatbot()
205
+ r = requests.get(str(url))
206
+ print(r.headers)
207
+ pdf = PdfReader(BytesIO(r.content))
208
+ paper_text = chatbot.parse_paper(pdf)
209
+ global df
210
+ df = chatbot.paper_df(paper_text)
211
+ embeddings = chatbot.calculate_embeddings(df)
212
+ print("Done processing pdf")
213
+ return embeddings
214
+
215
+ def show_pdf(file_content):
216
+ base64_pdf = base64.b64encode(file_content).decode('utf-8')
217
+ pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="800" height="800" type="application/pdf"></iframe>'
218
+ st.markdown(pdf_display, unsafe_allow_html=True)
219
+
220
+
221
+ def main():
222
+ st.title("Research Paper Guru")
223
+ st.subheader("Upload PDF or Enter URL")
224
+ embeddings = None
225
+ pdf_option = st.selectbox("Choose an option:", ["Upload PDF", "Enter URL"])
226
+ chatbot = Chatbot()
227
+
228
+ if pdf_option == "Upload PDF":
229
+ uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
230
+ if uploaded_file is not None:
231
+ file_content = uploaded_file.read()
232
+ embeddings = process_pdf(file_content)
233
+ st.success("PDF uploaded and processed successfully!")
234
+ show_pdf(file_content)
235
+
236
+ elif pdf_option == "Enter URL":
237
+ url = st.text_input("Enter the URL of the PDF:")
238
+ if url:
239
+ if st.button("Download and process PDF"):
240
+ try:
241
+ r = requests.get(str(url))
242
+ content = r.content
243
+ embeddings = download_pdf(url)
244
+ st.success("PDF downloaded and processed successfully!")
245
+ show_pdf(content)
246
+ except Exception as e:
247
+ st.error(f"An error occurred while processing the PDF: {e}")
248
+ st.subheader("Ask a question about a research paper and get an answer with sources!")
249
+ query = st.text_input("Enter your query:")
250
+ if query:
251
+ if st.button("Get answer"):
252
+ if embeddings is not None:
253
+ response = chatbot.reply(embeddings, query)
254
+ else:
255
+ st.warning("Please upload a PDF or enter a URL first.")
256
+ st.write(response['answer'])
257
+ st.write("Sources:")
258
+ for source in response['sources']:
259
+ st.write(source)
260
+
261
+ if __name__ == "__main__":
262
+ main()
263
+
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
13
+ faiss-cpu
14
+ altair<5