bhaskartripathi commited on
Commit
9eb86ad
1 Parent(s): b9171ac

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +216 -0
app.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(path, start_page=1, end_page=None):
22
+ doc = fitz.open(path)
23
+ total_pages = doc.page_count
24
+
25
+ if end_page is None:
26
+ end_page = total_pages
27
+
28
+ text_list = []
29
+
30
+ for i in range(start_page-1, end_page):
31
+ text = doc.load_page(i).get_text("text")
32
+ text = preprocess(text)
33
+ text_list.append(text)
34
+
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]
47
+ if (i+word_length) > len(words) and (len(chunk) < word_length) and (
48
+ len(text_toks) != (idx+1)):
49
+ text_toks[idx+1] = chunk + text_toks[idx+1]
50
+ continue
51
+ chunk = ' '.join(chunk).strip()
52
+ chunk = f'[{idx+start_page}]' + ' ' + '"' + chunk + '"'
53
+ chunks.append(chunk)
54
+ return chunks
55
+
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
+ openai.api_key = os.getenv('Your_Key_Here')
92
+
93
+ recommender = SemanticSearch()
94
+
95
+
96
+ def load_recommender(path, start_page=1):
97
+ global recommender
98
+ texts = pdf_to_text(path, start_page=start_page)
99
+ chunks = text_to_chunks(texts, start_page=start_page)
100
+ recommender.fit(chunks)
101
+ return 'Corpus Loaded.'
102
+
103
+
104
+ def generate_text(prompt, engine="text-davinci-003"):
105
+ completions = openai.Completion.create(
106
+ engine=engine,
107
+ prompt=prompt,
108
+ max_tokens=512,
109
+ n=1,
110
+ stop=None,
111
+ temperature=0.7,
112
+ )
113
+ message = completions.choices[0].text
114
+ return message
115
+
116
+
117
+ def generate_answer(question):
118
+ topn_chunks = recommender(question)
119
+ prompt = ""
120
+ prompt += 'search results:\n\n'
121
+ for c in topn_chunks:
122
+ prompt += c + '\n\n'
123
+
124
+ prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
125
+ "Cite each reference using [number] notation (every result has this number at the beginning). "\
126
+ "Citation should be done at the end of each sentence. If the search results mention multiple subjects "\
127
+ "with the same name, create separate answers for each. Only include information found in the results and "\
128
+ "don't add any additional information. Make sure the answer is correct and don't output false content. "\
129
+ "If the text does not relate to the query, simply state 'Found Nothing'. Ignore outlier "\
130
+ "search results which has nothing to do with the question. Only answer what is asked. The "\
131
+ "answer should be short and concise.\n\nQuery: {question}\nAnswer: "
132
+
133
+ prompt += f"Query: {question}\nAnswer:"
134
+ answer = generate_text(prompt)
135
+ return answer
136
+
137
+
138
+ def question_answer(url, file, question):
139
+ if url.strip() == '' and file == None:
140
+ return '[ERROR]: Both URL and PDF is empty. Provide atleast one.'
141
+
142
+ if url.strip() != '' and file != None:
143
+ return '[ERROR]: Both URL and PDF is provided. Please provide only one (eiter URL or PDF).'
144
+
145
+ if url.strip() != '':
146
+ glob_url = url
147
+ download_pdf(glob_url, 'corpus.pdf')
148
+ load_recommender('corpus.pdf')
149
+
150
+ else:
151
+ old_file_name = file.name
152
+ file_name = file.name
153
+ file_name = file_name[:-12] + file_name[-4:]
154
+ os.rename(old_file_name, file_name)
155
+ load_recommender(file_name)
156
+
157
+ if question.strip() == '':
158
+ return '[ERROR]: Question field is empty'
159
+
160
+ return generate_answer(question)
161
+
162
+
163
+ title = 'PDF GPT'
164
+ description = """ What is PDF GPT ?
165
+ 1. PDF GPT allows you to chat with a PDF file using GPT functionalities.
166
+ 2. The application intelligently breaks the document into smaller chunks and employs a powerful Deep Averaging Network Encoder to generate embeddings.
167
+ 3. PDF GPT utilizes Open AI as its data layer to generate a summary for each chunk.
168
+ 4. PDF GPT uses a KNN algorithm to return the top-n embedding from each chunk and uses custom logic to generate a response. The application also leverages important document sections to generate precise responses, and can even provide the page number where the information is located, adding credibility to the responses and helping to locate pertinent information quickly."""
169
+
170
+ with gr.Blocks() as demo:
171
+
172
+ gr.Markdown(f'<center><h1>{title}</h1></center>')
173
+ gr.Markdown(description)
174
+
175
+ with gr.Row():
176
+
177
+ with gr.Group():
178
+ url = gr.Textbox(label='Enter PDF URL here')
179
+ gr.Markdown("<center><h4>OR<h4></center>")
180
+ file = gr.File(label='Upload your PDF/ Research Paper / Book here', file_types=['.pdf'])
181
+ question = gr.Textbox(label='Enter your question here')
182
+ btn = gr.Button(value='Submit')
183
+ btn.style(full_width=True)
184
+
185
+ with gr.Group():
186
+ answer = gr.Textbox(label='The answer to your question is :')
187
+
188
+ btn.click(question_answer, inputs=[url, file, question], outputs=[answer])
189
+
190
+ demo.launch()
191
+
192
+
193
+ # import streamlit as st
194
+
195
+ # #Define the app layout
196
+ # st.markdown(f'<center><h1>{title}</h1></center>', unsafe_allow_html=True)
197
+ # st.markdown(description)
198
+
199
+ # col1, col2 = st.columns(2)
200
+
201
+ # # Define the inputs in the first column
202
+ # with col1:
203
+ # url = st.text_input('URL')
204
+ # st.markdown("<center><h6>or<h6></center>", unsafe_allow_html=True)
205
+ # file = st.file_uploader('PDF', type='pdf')
206
+ # question = st.text_input('question')
207
+ # btn = st.button('Submit')
208
+
209
+ # # Define the output in the second column
210
+ # with col2:
211
+ # answer = st.text_input('answer')
212
+
213
+ # # Define the button action
214
+ # if btn:
215
+ # answer_value = question_answer(url, file, question)
216
+ # answer.value = answer_value