hieult44 commited on
Commit
8c7b475
1 Parent(s): d0b50a0

Add application file

Browse files
Files changed (1) hide show
  1. app.py +194 -0
app.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module provides functions for working with PDF files and URLs. It uses the urllib.request library
3
+ to download files from URLs, and the fitz library to extract text from PDF files. And GPT3 modules to generate
4
+ text completions.
5
+ """
6
+ import urllib.request
7
+ import fitz
8
+ import re
9
+ import numpy as np
10
+ import tensorflow_hub as hub
11
+ import openai
12
+ import gradio as gr
13
+ import os
14
+ from sklearn.neighbors import NearestNeighbors
15
+
16
+ def download_pdf(url, output_path):
17
+ urllib.request.urlretrieve(url, output_path)
18
+
19
+
20
+ def preprocess(text):
21
+ text = text.replace('\n', ' ')
22
+ text = re.sub('\s+', ' ', text)
23
+ return text
24
+
25
+
26
+ def pdf_to_text(path, start_page=1, end_page=None):
27
+ doc = fitz.open(path)
28
+ total_pages = doc.page_count
29
+
30
+ if end_page is None:
31
+ end_page = total_pages
32
+
33
+ text_list = []
34
+
35
+ for i in range(start_page-1, end_page):
36
+ text = doc.load_page(i).get_text("text")
37
+ text = preprocess(text)
38
+ text_list.append(text)
39
+
40
+ doc.close()
41
+ return text_list
42
+
43
+
44
+ def text_to_chunks(texts, word_length=150, start_page=1):
45
+ text_toks = [t.split(' ') for t in texts]
46
+ page_nums = []
47
+ chunks = []
48
+
49
+ for idx, words in enumerate(text_toks):
50
+ for i in range(0, len(words), word_length):
51
+ chunk = words[i:i+word_length]
52
+ if (i+word_length) > len(words) and (len(chunk) < word_length) and (
53
+ len(text_toks) != (idx+1)):
54
+ text_toks[idx+1] = chunk + text_toks[idx+1]
55
+ continue
56
+ chunk = ' '.join(chunk).strip()
57
+ chunk = f'[{idx+start_page}]' + ' ' + '"' + chunk + '"'
58
+ chunks.append(chunk)
59
+ return chunks
60
+
61
+
62
+ class SemanticSearch:
63
+
64
+ def __init__(self):
65
+ self.use = hub.load('https://tfhub.dev/google/universal-sentence-encoder/4')
66
+ self.fitted = False
67
+
68
+
69
+ def fit(self, data, batch=1000, n_neighbors=5):
70
+ self.data = data
71
+ self.embeddings = self.get_text_embedding(data, batch=batch)
72
+ n_neighbors = min(n_neighbors, len(self.embeddings))
73
+ self.nn = NearestNeighbors(n_neighbors=n_neighbors)
74
+ self.nn.fit(self.embeddings)
75
+ self.fitted = True
76
+
77
+
78
+ def __call__(self, text, return_data=True):
79
+ inp_emb = self.use([text])
80
+ neighbors = self.nn.kneighbors(inp_emb, return_distance=False)[0]
81
+
82
+ if return_data:
83
+ return [self.data[i] for i in neighbors]
84
+ else:
85
+ return neighbors
86
+
87
+
88
+ def get_text_embedding(self, texts, batch=1000):
89
+ embeddings = []
90
+ for i in range(0, len(texts), batch):
91
+ text_batch = texts[i:(i+batch)]
92
+ emb_batch = self.use(text_batch)
93
+ embeddings.append(emb_batch)
94
+ embeddings = np.vstack(embeddings)
95
+ return embeddings
96
+
97
+
98
+
99
+ def load_recommender(path, start_page=1):
100
+ global recommender
101
+ texts = pdf_to_text(path, start_page=start_page)
102
+ chunks = text_to_chunks(texts, start_page=start_page)
103
+ recommender.fit(chunks)
104
+ return 'Corpus Loaded.'
105
+
106
+ def generate_text(openAI_key,prompt, engine="text-davinci-003"):
107
+ openai.api_key = openAI_key
108
+ completions = openai.Completion.create(
109
+ engine=engine,
110
+ prompt=prompt,
111
+ max_tokens=512,
112
+ n=1,
113
+ stop=None,
114
+ temperature=0.7,
115
+ )
116
+ message = completions.choices[0].text
117
+ return message
118
+
119
+ def generate_answer(question,openAI_key):
120
+ topn_chunks = recommender(question)
121
+ prompt = ""
122
+ prompt += 'search results:\n\n'
123
+ for c in topn_chunks:
124
+ prompt += c + '\n\n'
125
+
126
+ prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
127
+ "Cite each reference using [ Page Number] notation (every result has this number at the beginning). "\
128
+ "Citation should be done at the end of each sentence. If the search results mention multiple subjects "\
129
+ "with the same name, create separate answers for each. Only include information found in the results and "\
130
+ "don't add any additional information. Make sure the answer is correct and don't output false content. "\
131
+ "If the text does not relate to the query, simply state 'Text Not Found in PDF'. Ignore outlier "\
132
+ "search results which has nothing to do with the question. Only answer what is asked. The "\
133
+ "answer should be short and concise. Answer step-by-step. \n\nQuery: {question}\nAnswer: "
134
+
135
+ prompt += f"Query: {question}\nAnswer:"
136
+ answer = generate_text(openAI_key, prompt,"text-davinci-003")
137
+ return answer
138
+
139
+
140
+ def question_answer(url, file, question,openAI_key):
141
+ if openAI_key.strip()=='':
142
+ return '[ERROR]: Please enter you Open AI Key. Get your key here : https://platform.openai.com/account/api-keys'
143
+ if url.strip() == '' and file == None:
144
+ return '[ERROR]: Both URL and PDF is empty. Provide atleast one.'
145
+
146
+ if url.strip() != '' and file != None:
147
+ return '[ERROR]: Both URL and PDF is provided. Please provide only one (eiter URL or PDF).'
148
+
149
+ if url.strip() != '':
150
+ glob_url = url
151
+ download_pdf(glob_url, 'corpus.pdf')
152
+ load_recommender('corpus.pdf')
153
+
154
+ else:
155
+ old_file_name = file.name
156
+ file_name = file.name
157
+ file_name = file_name[:-12] + file_name[-4:]
158
+ os.rename(old_file_name, file_name)
159
+ load_recommender(file_name)
160
+
161
+ if question.strip() == '':
162
+ return '[ERROR]: Question field is empty'
163
+
164
+ return generate_answer(question,openAI_key)
165
+
166
+
167
+ recommender = SemanticSearch()
168
+
169
+ title = 'PDF GPT'
170
+ 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."""
171
+
172
+ with gr.Blocks() as demo:
173
+
174
+ gr.Markdown(f'<center><h1>{title}</h1></center>')
175
+ gr.Markdown(description)
176
+
177
+ with gr.Row():
178
+
179
+ with gr.Group():
180
+ 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>')
181
+ openAI_key=gr.Textbox(label='Enter your OpenAI API key here')
182
+ url = gr.Textbox(label='Enter PDF URL here')
183
+ gr.Markdown("<center><h4>OR<h4></center>")
184
+ file = gr.File(label='Upload your PDF/ Research Paper / Book here', file_types=['.pdf'])
185
+ question = gr.Textbox(label='Enter your question here')
186
+ btn = gr.Button(value='Submit')
187
+ btn.style(full_width=True)
188
+
189
+ with gr.Group():
190
+ answer = gr.Textbox(label='The answer to your question is :')
191
+
192
+ btn.click(question_answer, inputs=[url, file, question,openAI_key], outputs=[answer])
193
+ #openai.api_key = os.getenv('Your_Key_Here')
194
+ demo.launch()