Spaces:
Runtime error
Runtime error
Commit
·
faa00e9
1
Parent(s):
a02183e
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
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
|
9 |
+
from sklearn.neighbors import NearestNeighbors
|
10 |
+
|
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(file_path, start_page=1, end_page=None):
|
22 |
+
doc = fitz.open(file_path)
|
23 |
+
total_pages = doc.page_count
|
24 |
+
file_name = os.path.basename(file_path)
|
25 |
+
|
26 |
+
if end_page is None:
|
27 |
+
end_page = total_pages
|
28 |
+
|
29 |
+
text_list = []
|
30 |
+
|
31 |
+
for i in range(start_page-1, end_page):
|
32 |
+
text = doc.load_page(i).get_text("text")
|
33 |
+
text = preprocess(text)
|
34 |
+
text_list.append((file_name, text))
|
35 |
+
|
36 |
+
doc.close()
|
37 |
+
return text_list
|
38 |
+
|
39 |
+
|
40 |
+
def text_to_chunks(texts, word_length=150, start_page=1):
|
41 |
+
text_toks = [(file_name, t.split(' ')) for file_name, t in texts]
|
42 |
+
page_nums = []
|
43 |
+
chunks = []
|
44 |
+
|
45 |
+
for idx, (file_name, words) in enumerate(text_toks):
|
46 |
+
for i in range(0, len(words), word_length):
|
47 |
+
chunk = words[i:i+word_length]
|
48 |
+
if (i+word_length) > len(words) and (len(chunk) < word_length) and (
|
49 |
+
len(text_toks) != (idx+1)):
|
50 |
+
text_toks[idx+1] = (file_name, chunk + text_toks[idx+1][1])
|
51 |
+
continue
|
52 |
+
chunk = ' '.join(chunk).strip()
|
53 |
+
chunk = f'[{file_name}, Page no. {idx+start_page}]' + ' ' + '"' + chunk + '"'
|
54 |
+
chunks.append(chunk)
|
55 |
+
return chunks
|
56 |
+
|
57 |
+
class SemanticSearch:
|
58 |
+
|
59 |
+
def __init__(self):
|
60 |
+
self.use = hub.load('https://tfhub.dev/google/universal-sentence-encoder/4')
|
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, batch=batch)
|
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.use([text])
|
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 |
+
def get_text_embedding(self, texts, batch=1000):
|
84 |
+
embeddings = []
|
85 |
+
for i in range(0, len(texts), batch):
|
86 |
+
text_batch = texts[i:(i+batch)]
|
87 |
+
emb_batch = self.use(text_batch)
|
88 |
+
embeddings.append(emb_batch)
|
89 |
+
embeddings = np.vstack(embeddings)
|
90 |
+
return embeddings
|
91 |
+
|
92 |
+
|
93 |
+
|
94 |
+
def load_recommender(directory_path, start_page=1):
|
95 |
+
global recommender
|
96 |
+
|
97 |
+
texts = []
|
98 |
+
for file_path in glob.glob(os.path.join(directory_path, '*.pdf')):
|
99 |
+
texts.extend(pdf_to_text(file_path, start_page=start_page))
|
100 |
+
|
101 |
+
chunks = text_to_chunks(texts, start_page=start_page)
|
102 |
+
recommender.fit(chunks)
|
103 |
+
return 'Corpus Loaded.'
|
104 |
+
|
105 |
+
def generate_text(openAI_key,prompt, engine="text-davinci-003"):
|
106 |
+
openai.api_key = openAI_key
|
107 |
+
completions = openai.Completion.create(
|
108 |
+
engine=engine,
|
109 |
+
prompt=prompt,
|
110 |
+
max_tokens=512,
|
111 |
+
n=1,
|
112 |
+
stop=None,
|
113 |
+
temperature=0.7,
|
114 |
+
)
|
115 |
+
message = completions.choices[0].text
|
116 |
+
return message
|
117 |
+
|
118 |
+
def generate_answer(question,openAI_key):
|
119 |
+
topn_chunks = recommender(question)
|
120 |
+
prompt = ""
|
121 |
+
prompt += 'search results:\n\n'
|
122 |
+
for c in topn_chunks:
|
123 |
+
prompt += c + '\n\n'
|
124 |
+
|
125 |
+
prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
|
126 |
+
"Cite each reference using [ Page Number] notation (every result has this number at the beginning). "\
|
127 |
+
"Citation should be done at the end of each sentence. If the search results mention multiple subjects "\
|
128 |
+
"with the same name, create separate answers for each. Only include information found in the results and "\
|
129 |
+
"don't add any additional information. Make sure the answer is correct and don't output false content. "\
|
130 |
+
"If the text does not relate to the query, simply state 'Text Not Found in PDF'. Ignore outlier "\
|
131 |
+
"search results which has nothing to do with the question. Only answer what is asked. The "\
|
132 |
+
"answer should be short and concise. Answer step-by-step. \n\nQuery: {question}\nAnswer: "
|
133 |
+
|
134 |
+
prompt += f"Query: {question}\nAnswer:"
|
135 |
+
answer = generate_text(openAI_key, prompt,"text-davinci-003")
|
136 |
+
return answer
|
137 |
+
|
138 |
+
|
139 |
+
def question_answer(directory_path, question, openAI_key):
|
140 |
+
if openAI_key.strip() == '':
|
141 |
+
return '[ERROR]: Please enter your Open AI Key. Get your key here : https://platform.openai.com/account/api-keys'
|
142 |
+
|
143 |
+
if not os.path.isdir(directory_path):
|
144 |
+
return '[ERROR]: Invalid directory path.'
|
145 |
+
|
146 |
+
load_recommender(directory_path)
|
147 |
+
|
148 |
+
if question.strip() == '':
|
149 |
+
return '[ERROR]: Question field is empty'
|
150 |
+
|
151 |
+
return generate_answer(question, openAI_key)
|
152 |
+
|
153 |
+
|
154 |
+
recommender = SemanticSearch()
|
155 |
+
|
156 |
+
title = 'PDF GPT'
|
157 |
+
description = """ PDF GPT allows you to chat with your PDF file using Universal Sentence Encoder and Open AI. It gives hallucination free response than other tools as the embeddings are better than OpenAI. 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."""
|
158 |
+
|
159 |
+
with gr.Blocks() as demo:
|
160 |
+
|
161 |
+
gr.Markdown(f'<center><h1>{title}</h1></center>')
|
162 |
+
gr.Markdown(description)
|
163 |
+
|
164 |
+
with gr.Row():
|
165 |
+
|
166 |
+
with gr.Group():
|
167 |
+
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>')
|
168 |
+
openAI_key = gr.Textbox(label='Enter your OpenAI API key here')
|
169 |
+
directory_path = gr.Textbox(label='Enter the directory path containing PDF files')
|
170 |
+
question = gr.Textbox(label='Enter your question here')
|
171 |
+
btn = gr.Button(value='Submit')
|
172 |
+
|
173 |
+
with gr.Group():
|
174 |
+
answer = gr.Textbox(label='The answer to your question is :')
|
175 |
+
|
176 |
+
btn.click(question_answer, inputs=[url, file, question,openAI_key], outputs=[answer])
|
177 |
+
#openai.api_key = os.getenv('Your_Key_Here')
|
178 |
+
demo.launch()
|