Halo commited on
Commit
6319910
1 Parent(s): 8883fca

Add application file

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