joshuadunlop commited on
Commit
0be4b49
·
1 Parent(s): 49fead2

Create app.py

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