Spaces:
Running
Running
bhaskartripathi
commited on
Commit
·
efee337
1
Parent(s):
9efa4bb
Update app.py
Browse files
app.py
CHANGED
@@ -2,7 +2,6 @@ import urllib.request
|
|
2 |
import fitz
|
3 |
import re
|
4 |
import numpy as np
|
5 |
-
import tensorflow_hub as hub
|
6 |
import openai
|
7 |
import gradio as gr
|
8 |
import os
|
@@ -11,13 +10,11 @@ from sklearn.neighbors import NearestNeighbors
|
|
11 |
def download_pdf(url, output_path):
|
12 |
urllib.request.urlretrieve(url, output_path)
|
13 |
|
14 |
-
|
15 |
def preprocess(text):
|
16 |
text = text.replace('\n', ' ')
|
17 |
text = re.sub('\s+', ' ', text)
|
18 |
return text
|
19 |
|
20 |
-
|
21 |
def pdf_to_text(path, start_page=1, end_page=None):
|
22 |
doc = fitz.open(path)
|
23 |
total_pages = doc.page_count
|
@@ -35,12 +32,11 @@ def pdf_to_text(path, start_page=1, end_page=None):
|
|
35 |
doc.close()
|
36 |
return text_list
|
37 |
|
38 |
-
|
39 |
def text_to_chunks(texts, word_length=150, start_page=1):
|
40 |
text_toks = [t.split(' ') for t in texts]
|
41 |
page_nums = []
|
42 |
chunks = []
|
43 |
-
|
44 |
for idx, words in enumerate(text_toks):
|
45 |
for i in range(0, len(words), word_length):
|
46 |
chunk = words[i:i+word_length]
|
@@ -53,72 +49,63 @@ def text_to_chunks(texts, word_length=150, start_page=1):
|
|
53 |
chunks.append(chunk)
|
54 |
return chunks
|
55 |
|
56 |
-
|
57 |
class SemanticSearch:
|
58 |
-
|
59 |
-
def __init__(self):
|
60 |
-
self.
|
61 |
self.fitted = False
|
62 |
-
|
63 |
-
|
64 |
-
def fit(self, data, batch=1000, n_neighbors=5):
|
65 |
self.data = data
|
66 |
-
self.embeddings = self.get_text_embedding(data
|
67 |
n_neighbors = min(n_neighbors, len(self.embeddings))
|
68 |
self.nn = NearestNeighbors(n_neighbors=n_neighbors)
|
69 |
self.nn.fit(self.embeddings)
|
70 |
self.fitted = True
|
71 |
-
|
72 |
-
|
73 |
def __call__(self, text, return_data=True):
|
74 |
-
inp_emb = self.
|
75 |
neighbors = self.nn.kneighbors(inp_emb, return_distance=False)[0]
|
76 |
-
|
77 |
if return_data:
|
78 |
return [self.data[i] for i in neighbors]
|
79 |
else:
|
80 |
return neighbors
|
81 |
-
|
82 |
-
|
83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
embeddings = []
|
85 |
-
for
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
|
|
90 |
return embeddings
|
91 |
|
92 |
-
|
93 |
-
|
94 |
-
#def load_recommender(path, start_page=1):
|
95 |
-
# global recommender
|
96 |
-
# texts = pdf_to_text(path, start_page=start_page)
|
97 |
-
# chunks = text_to_chunks(texts, start_page=start_page)
|
98 |
-
# recommender.fit(chunks)
|
99 |
-
# return 'Corpus Loaded.'
|
100 |
-
|
101 |
-
# The modified function generates embeddings based on PDF file name and page number and checks if the embeddings file exists before loading or generating it.
|
102 |
-
def load_recommender(path, start_page=1):
|
103 |
global recommender
|
104 |
-
pdf_file = os.path.basename(path)
|
105 |
-
embeddings_file = f"{pdf_file}_{start_page}.npy"
|
106 |
-
|
107 |
-
if os.path.isfile(embeddings_file):
|
108 |
-
embeddings = np.load(embeddings_file)
|
109 |
-
recommender.embeddings = embeddings
|
110 |
-
recommender.fitted = True
|
111 |
-
return "Embeddings loaded from file"
|
112 |
-
|
113 |
texts = pdf_to_text(path, start_page=start_page)
|
114 |
-
chunks = text_to_chunks(texts, start_page=start_page
|
|
|
115 |
recommender.fit(chunks)
|
116 |
-
np.save(embeddings_file, recommender.embeddings)
|
117 |
return 'Corpus Loaded.'
|
118 |
|
119 |
-
|
120 |
-
|
121 |
-
def generate_text(openAI_key,prompt, engine="text-davinci-003"):
|
122 |
openai.api_key = openAI_key
|
123 |
completions = openai.Completion.create(
|
124 |
engine=engine,
|
@@ -130,30 +117,14 @@ def generate_text(openAI_key,prompt, engine="text-davinci-003"):
|
|
130 |
)
|
131 |
message = completions.choices[0].text
|
132 |
return message
|
133 |
-
|
134 |
-
def generate_text2(openAI_key, prompt, engine="gpt-3.5-turbo-0301"):
|
135 |
-
openai.api_key = openAI_key
|
136 |
-
messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
|
137 |
-
{'role': 'user', 'content': prompt}]
|
138 |
-
|
139 |
-
completions = openai.ChatCompletion.create(
|
140 |
-
model=engine,
|
141 |
-
messages=messages,
|
142 |
-
max_tokens=512,
|
143 |
-
n=1,
|
144 |
-
stop=None,
|
145 |
-
temperature=0.7,
|
146 |
-
)
|
147 |
-
message = completions.choices[0].message['content']
|
148 |
-
return message
|
149 |
|
150 |
-
def generate_answer(question,openAI_key):
|
151 |
topn_chunks = recommender(question)
|
152 |
prompt = ""
|
153 |
prompt += 'search results:\n\n'
|
154 |
for c in topn_chunks:
|
155 |
prompt += c + '\n\n'
|
156 |
-
|
157 |
prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
|
158 |
"Cite each reference using [ Page Number] notation (every result has this number at the beginning). "\
|
159 |
"Citation should be done at the end of each sentence. If the search results mention multiple subjects "\
|
@@ -162,45 +133,42 @@ def generate_answer(question,openAI_key):
|
|
162 |
"If the text does not relate to the query, simply state 'Text Not Found in PDF'. Ignore outlier "\
|
163 |
"search results which has nothing to do with the question. Only answer what is asked. The "\
|
164 |
"answer should be short and concise. Answer step-by-step. \n\nQuery: {question}\nAnswer: "
|
165 |
-
|
166 |
prompt += f"Query: {question}\nAnswer:"
|
167 |
-
answer = generate_text(openAI_key, prompt,"text-davinci-003")
|
168 |
return answer
|
169 |
|
170 |
-
|
171 |
-
|
172 |
-
if openAI_key.strip()=='':
|
173 |
return '[ERROR]: Please enter you Open AI Key. Get your key here : https://platform.openai.com/account/api-keys'
|
174 |
if url.strip() == '' and file == None:
|
175 |
-
return '[ERROR]: Both URL and PDF is empty. Provide
|
176 |
-
|
177 |
if url.strip() != '' and file != None:
|
178 |
-
return '[ERROR]: Both URL and PDF is provided. Please provide only one (
|
179 |
|
180 |
if url.strip() != '':
|
181 |
glob_url = url
|
182 |
download_pdf(glob_url, 'corpus.pdf')
|
183 |
-
load_recommender('corpus.pdf')
|
184 |
|
185 |
else:
|
186 |
old_file_name = file.name
|
187 |
file_name = file.name
|
188 |
file_name = file_name[:-12] + file_name[-4:]
|
189 |
os.rename(old_file_name, file_name)
|
190 |
-
load_recommender(file_name)
|
191 |
|
192 |
if question.strip() == '':
|
193 |
return '[ERROR]: Question field is empty'
|
194 |
|
195 |
-
return generate_answer(question,openAI_key)
|
196 |
-
|
197 |
|
198 |
-
recommender =
|
199 |
|
|
|
200 |
title = 'PDF GPT'
|
201 |
-
description = """
|
202 |
-
1. The problem is that Open AI has a 4K token limit and cannot take an entire PDF file as input. Additionally, it sometimes returns irrelevant responses due to poor embeddings. ChatGPT cannot directly talk to external data. The solution is PDF GPT, which allows you to chat with an uploaded PDF file using GPT functionalities. The application breaks the document into smaller chunks and generates embeddings using a powerful Deep Averaging Network Encoder. A semantic search is performed on your query, and the top relevant chunks are used to generate a response.
|
203 |
-
2. The returned response can even cite the page number in square brackets([]) where the information is located, adding credibility to the responses and helping to locate pertinent information quickly. The Responses are much better than the naive responses by Open AI."""
|
204 |
|
205 |
with gr.Blocks() as demo:
|
206 |
|
@@ -208,7 +176,7 @@ with gr.Blocks() as demo:
|
|
208 |
gr.Markdown(description)
|
209 |
|
210 |
with gr.Row():
|
211 |
-
|
212 |
with gr.Group():
|
213 |
gr.Markdown(f'<p style="text-align:center">Get your Open AI API key <a href="https://platform.openai.com/account/api-keys">here</a></p>')
|
214 |
openAI_key=gr.Textbox(label='Enter your OpenAI API key here')
|
@@ -222,32 +190,6 @@ with gr.Blocks() as demo:
|
|
222 |
with gr.Group():
|
223 |
answer = gr.Textbox(label='The answer to your question is :')
|
224 |
|
225 |
-
btn.click(question_answer, inputs=[url, file, question,openAI_key], outputs=[answer])
|
226 |
-
#openai.api_key = os.getenv('Your_Key_Here')
|
227 |
-
demo.launch()
|
228 |
-
|
229 |
-
|
230 |
-
# import streamlit as st
|
231 |
-
|
232 |
-
# #Define the app layout
|
233 |
-
# st.markdown(f'<center><h1>{title}</h1></center>', unsafe_allow_html=True)
|
234 |
-
# st.markdown(description)
|
235 |
|
236 |
-
|
237 |
-
|
238 |
-
# # Define the inputs in the first column
|
239 |
-
# with col1:
|
240 |
-
# url = st.text_input('URL')
|
241 |
-
# st.markdown("<center><h6>or<h6></center>", unsafe_allow_html=True)
|
242 |
-
# file = st.file_uploader('PDF', type='pdf')
|
243 |
-
# question = st.text_input('question')
|
244 |
-
# btn = st.button('Submit')
|
245 |
-
|
246 |
-
# # Define the output in the second column
|
247 |
-
# with col2:
|
248 |
-
# answer = st.text_input('answer')
|
249 |
-
|
250 |
-
# # Define the button action
|
251 |
-
# if btn:
|
252 |
-
# answer_value = question_answer(url, file, question)
|
253 |
-
# answer.value = answer_value
|
|
|
2 |
import fitz
|
3 |
import re
|
4 |
import numpy as np
|
|
|
5 |
import openai
|
6 |
import gradio as gr
|
7 |
import os
|
|
|
10 |
def download_pdf(url, output_path):
|
11 |
urllib.request.urlretrieve(url, output_path)
|
12 |
|
|
|
13 |
def preprocess(text):
|
14 |
text = text.replace('\n', ' ')
|
15 |
text = re.sub('\s+', ' ', text)
|
16 |
return text
|
17 |
|
|
|
18 |
def pdf_to_text(path, start_page=1, end_page=None):
|
19 |
doc = fitz.open(path)
|
20 |
total_pages = doc.page_count
|
|
|
32 |
doc.close()
|
33 |
return text_list
|
34 |
|
|
|
35 |
def text_to_chunks(texts, word_length=150, start_page=1):
|
36 |
text_toks = [t.split(' ') for t in texts]
|
37 |
page_nums = []
|
38 |
chunks = []
|
39 |
+
|
40 |
for idx, words in enumerate(text_toks):
|
41 |
for i in range(0, len(words), word_length):
|
42 |
chunk = words[i:i+word_length]
|
|
|
49 |
chunks.append(chunk)
|
50 |
return chunks
|
51 |
|
|
|
52 |
class SemanticSearch:
|
53 |
+
|
54 |
+
def __init__(self, openAI_key):
|
55 |
+
self.openAI_key = openAI_key
|
56 |
self.fitted = False
|
57 |
+
|
58 |
+
def fit(self, data, n_neighbors=5):
|
|
|
59 |
self.data = data
|
60 |
+
self.embeddings = self.get_text_embedding(data)
|
61 |
n_neighbors = min(n_neighbors, len(self.embeddings))
|
62 |
self.nn = NearestNeighbors(n_neighbors=n_neighbors)
|
63 |
self.nn.fit(self.embeddings)
|
64 |
self.fitted = True
|
65 |
+
|
|
|
66 |
def __call__(self, text, return_data=True):
|
67 |
+
inp_emb = self.get_text_embedding([text])
|
68 |
neighbors = self.nn.kneighbors(inp_emb, return_distance=False)[0]
|
69 |
+
|
70 |
if return_data:
|
71 |
return [self.data[i] for i in neighbors]
|
72 |
else:
|
73 |
return neighbors
|
74 |
+
|
75 |
+
def get_text_embedding(self, texts):
|
76 |
+
prompt = "Embed the following texts:"
|
77 |
+
for text in texts:
|
78 |
+
prompt += f"\n\n{text}"
|
79 |
+
|
80 |
+
openai.api_key = self.openAI_key
|
81 |
+
completions = openai.Completion.create(
|
82 |
+
engine="text-davinci-003",
|
83 |
+
prompt=prompt,
|
84 |
+
max_tokens=len(texts) * 128,
|
85 |
+
n=1,
|
86 |
+
stop=None,
|
87 |
+
temperature=0.5,
|
88 |
+
)
|
89 |
+
|
90 |
+
message = completions.choices[0].text
|
91 |
embeddings = []
|
92 |
+
for emb_str in message.split("\n"):
|
93 |
+
emb_str = emb_str.strip()
|
94 |
+
if emb_str:
|
95 |
+
emb = np.array([float(x) for x in emb_str.split()])
|
96 |
+
embeddings.append(emb)
|
97 |
+
embeddings = np.array(embeddings)
|
98 |
return embeddings
|
99 |
|
100 |
+
def load_recommender(path, openAI_key, start_page=1):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
global recommender
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
texts = pdf_to_text(path, start_page=start_page)
|
103 |
+
chunks = text_to_chunks(texts, start_page=start_page
|
104 |
+
recommender = SemanticSearch(openAI_key)
|
105 |
recommender.fit(chunks)
|
|
|
106 |
return 'Corpus Loaded.'
|
107 |
|
108 |
+
def generate_text(openAI_key, prompt, engine="text-davinci-003"):
|
|
|
|
|
109 |
openai.api_key = openAI_key
|
110 |
completions = openai.Completion.create(
|
111 |
engine=engine,
|
|
|
117 |
)
|
118 |
message = completions.choices[0].text
|
119 |
return message
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
|
121 |
+
def generate_answer(question, openAI_key):
|
122 |
topn_chunks = recommender(question)
|
123 |
prompt = ""
|
124 |
prompt += 'search results:\n\n'
|
125 |
for c in topn_chunks:
|
126 |
prompt += c + '\n\n'
|
127 |
+
|
128 |
prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
|
129 |
"Cite each reference using [ Page Number] notation (every result has this number at the beginning). "\
|
130 |
"Citation should be done at the end of each sentence. If the search results mention multiple subjects "\
|
|
|
133 |
"If the text does not relate to the query, simply state 'Text Not Found in PDF'. Ignore outlier "\
|
134 |
"search results which has nothing to do with the question. Only answer what is asked. The "\
|
135 |
"answer should be short and concise. Answer step-by-step. \n\nQuery: {question}\nAnswer: "
|
136 |
+
|
137 |
prompt += f"Query: {question}\nAnswer:"
|
138 |
+
answer = generate_text(openAI_key, prompt, "text-davinci-003")
|
139 |
return answer
|
140 |
|
141 |
+
def question_answer(url, file, question, openAI_key):
|
142 |
+
if openAI_key.strip() == '':
|
|
|
143 |
return '[ERROR]: Please enter you Open AI Key. Get your key here : https://platform.openai.com/account/api-keys'
|
144 |
if url.strip() == '' and file == None:
|
145 |
+
return '[ERROR]: Both URL and PDF is empty. Provide at least one.'
|
146 |
+
|
147 |
if url.strip() != '' and file != None:
|
148 |
+
return '[ERROR]: Both URL and PDF is provided. Please provide only one (either URL or PDF).'
|
149 |
|
150 |
if url.strip() != '':
|
151 |
glob_url = url
|
152 |
download_pdf(glob_url, 'corpus.pdf')
|
153 |
+
load_recommender('corpus.pdf', openAI_key)
|
154 |
|
155 |
else:
|
156 |
old_file_name = file.name
|
157 |
file_name = file.name
|
158 |
file_name = file_name[:-12] + file_name[-4:]
|
159 |
os.rename(old_file_name, file_name)
|
160 |
+
load_recommender(file_name, openAI_key)
|
161 |
|
162 |
if question.strip() == '':
|
163 |
return '[ERROR]: Question field is empty'
|
164 |
|
165 |
+
return generate_answer(question, openAI_key)
|
|
|
166 |
|
167 |
+
recommender = None
|
168 |
|
169 |
+
# Add your Gradio UI code here
|
170 |
title = 'PDF GPT'
|
171 |
+
description = """With PDF GPT, you can chat with your PDF files/books and get precise answers."""
|
|
|
|
|
172 |
|
173 |
with gr.Blocks() as demo:
|
174 |
|
|
|
176 |
gr.Markdown(description)
|
177 |
|
178 |
with gr.Row():
|
179 |
+
|
180 |
with gr.Group():
|
181 |
gr.Markdown(f'<p style="text-align:center">Get your Open AI API key <a href="https://platform.openai.com/account/api-keys">here</a></p>')
|
182 |
openAI_key=gr.Textbox(label='Enter your OpenAI API key here')
|
|
|
190 |
with gr.Group():
|
191 |
answer = gr.Textbox(label='The answer to your question is :')
|
192 |
|
193 |
+
btn.click(question_answer, inputs=[url, file, question, openAI_key], outputs=[answer])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
194 |
|
195 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|