bhaskartripathi commited on
Commit
e6a7a6e
1 Parent(s): 1e4f764

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -69
app.py CHANGED
@@ -2,6 +2,7 @@ import urllib.request
2
  import fitz
3
  import re
4
  import numpy as np
 
5
  import openai
6
  import gradio as gr
7
  import os
@@ -10,11 +11,13 @@ from sklearn.neighbors import NearestNeighbors
10
  def download_pdf(url, output_path):
11
  urllib.request.urlretrieve(url, output_path)
12
 
 
13
  def preprocess(text):
14
  text = text.replace('\n', ' ')
15
  text = re.sub('\s+', ' ', text)
16
  return text
17
 
 
18
  def pdf_to_text(path, start_page=1, end_page=None):
19
  doc = fitz.open(path)
20
  total_pages = doc.page_count
@@ -32,11 +35,12 @@ def pdf_to_text(path, start_page=1, end_page=None):
32
  doc.close()
33
  return text_list
34
 
 
35
  def text_to_chunks(texts, word_length=150, start_page=1):
36
  text_toks = [t.split(' ') for t in texts]
37
  page_nums = []
38
  chunks = []
39
-
40
  for idx, words in enumerate(text_toks):
41
  for i in range(0, len(words), word_length):
42
  chunk = words[i:i+word_length]
@@ -49,70 +53,57 @@ def text_to_chunks(texts, word_length=150, start_page=1):
49
  chunks.append(chunk)
50
  return chunks
51
 
52
- class SemanticSearch:
53
 
54
- def __init__(self, openAI_key):
55
- self.openAI_key = openAI_key
 
 
56
  self.fitted = False
57
-
58
- def fit(self, data, n_neighbors=5):
 
59
  self.data = data
60
- self.embeddings = self.get_text_embedding(data)
61
  n_neighbors = min(n_neighbors, len(self.embeddings))
62
  self.nn = NearestNeighbors(n_neighbors=n_neighbors)
63
  self.nn.fit(self.embeddings)
64
  self.fitted = True
65
-
 
66
  def __call__(self, text, return_data=True):
67
- inp_emb = self.get_text_embedding([text])
68
  neighbors = self.nn.kneighbors(inp_emb, return_distance=False)[0]
69
-
70
  if return_data:
71
  return [self.data[i] for i in neighbors]
72
  else:
73
  return neighbors
74
-
75
- def get_text_embedding(self, texts):
76
- prompt = "Embed the following texts:"
77
- for text in texts:
78
- prompt += f"\n\n{text}"
79
-
80
- openai.api_key = self.openAI_key
81
- completions = openai.Completion.create(
82
- engine="text-davinci-003",
83
- prompt=prompt,
84
- max_tokens=len(texts) * 128,
85
- n=1,
86
- stop=None,
87
- temperature=0.5,
88
- )
89
-
90
- message = completions.choices[0].text
91
  embeddings = []
92
- for emb_str in message.split("\n"):
93
- emb_str = emb_str.strip()
94
- if emb_str:
95
- emb = np.array([float(x) for x in emb_str.split()])
96
- embeddings.append(emb)
97
- embeddings = np.array(embeddings)
98
  return embeddings
99
 
100
- def load_recommender(path, openAI_key, start_page=1):
 
 
101
  global recommender
102
  texts = pdf_to_text(path, start_page=start_page)
103
  chunks = text_to_chunks(texts, start_page=start_page)
104
- recommender = SemanticSearch(openAI_key) # add the openAI_key parameter here
105
  recommender.fit(chunks)
106
  return 'Corpus Loaded.'
107
 
108
-
109
-
110
- def generate_text(openAI_key, prompt, engine="text-davinci-003"):
111
  openai.api_key = openAI_key
112
  completions = openai.Completion.create(
113
  engine=engine,
114
  prompt=prompt,
115
- max_tokens=4096,
116
  n=1,
117
  stop=None,
118
  temperature=0.7,
@@ -120,57 +111,60 @@ def generate_text(openAI_key, prompt, engine="text-davinci-003"):
120
  message = completions.choices[0].text
121
  return message
122
 
123
- def generate_answer(question, openAI_key):
124
  topn_chunks = recommender(question)
125
  prompt = ""
126
  prompt += 'search results:\n\n'
127
  for c in topn_chunks:
128
  prompt += c + '\n\n'
 
 
 
 
 
 
 
 
 
129
 
130
- prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. Cite each reference "\
131
- "using [Page Number] notation (every result has this number at the beginning). Citation should be done at the "\
132
- "end of each sentence. If the search results mention multiple subjects with the same name, create separate "\
133
- "answers for each. Only include information found in the results and don't add any additional information. "\
134
- "Make sure the answer is correct and don't output false content. If the text does not relate to the query, "\
135
- "simply state 'Text Not Found in PDF'. Ignore outlier search results which has nothing to do with the question. "\
136
- "Only answer what is asked. The answer should be short and concise. Answer step-by-step.\n\nQuery: {question}"\
137
- "\nAnswer: "
138
-
139
  prompt += f"Query: {question}\nAnswer:"
140
- answer = generate_text(openAI_key, prompt, "text-davinci-003")
141
  return answer
142
 
143
- def question_answer(url, file, question, openAI_key):
144
- if openAI_key.strip() == '':
 
145
  return '[ERROR]: Please enter you Open AI Key. Get your key here : https://platform.openai.com/account/api-keys'
146
  if url.strip() == '' and file == None:
147
- return '[ERROR]: Both URL and PDF is empty. Provide at least one.'
148
-
149
  if url.strip() != '' and file != None:
150
- return '[ERROR]: Both URL and PDF is provided. Please provide only one (either URL or PDF).'
151
 
152
  if url.strip() != '':
153
  glob_url = url
154
  download_pdf(glob_url, 'corpus.pdf')
155
- load_recommender('corpus.pdf', openAI_key)
156
 
157
  else:
158
  old_file_name = file.name
159
  file_name = file.name
160
  file_name = file_name[:-12] + file_name[-4:]
161
  os.rename(old_file_name, file_name)
162
- load_recommender(file_name, openAI_key)
163
 
164
  if question.strip() == '':
165
  return '[ERROR]: Question field is empty'
166
 
167
- return generate_answer(question, openAI_key)
 
168
 
169
- recommender = None
170
 
171
- # Add your Gradio UI code here
172
  title = 'PDF GPT'
173
- description = """With PDF GPT, you can chat with your PDF files/books and get precise answers."""
 
 
174
 
175
  with gr.Blocks() as demo:
176
 
@@ -178,7 +172,7 @@ with gr.Blocks() as demo:
178
  gr.Markdown(description)
179
 
180
  with gr.Row():
181
-
182
  with gr.Group():
183
  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>')
184
  openAI_key=gr.Textbox(label='Enter your OpenAI API key here')
@@ -192,12 +186,7 @@ with gr.Blocks() as demo:
192
  with gr.Group():
193
  answer = gr.Textbox(label='The answer to your question is :')
194
 
195
- btn.click(question_answer, inputs=[url, file, question, openAI_key], outputs=[answer])
196
-
197
  demo.launch()
198
 
199
- # remove this line
200
- recommender = SemanticSearch(openAI_key)
201
-
202
- # call load_recommender instead to initialize recommender
203
- load_recommender('corpus.pdf', openAI_key)
 
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
 
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
 
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]
 
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
 
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
+ def generate_text(openAI_key,prompt, engine="text-davinci-003"):
 
 
102
  openai.api_key = openAI_key
103
  completions = openai.Completion.create(
104
  engine=engine,
105
  prompt=prompt,
106
+ max_tokens=512,
107
  n=1,
108
  stop=None,
109
  temperature=0.7,
 
111
  message = completions.choices[0].text
112
  return message
113
 
114
+ def generate_answer(question,openAI_key):
115
  topn_chunks = recommender(question)
116
  prompt = ""
117
  prompt += 'search results:\n\n'
118
  for c in topn_chunks:
119
  prompt += c + '\n\n'
120
+
121
+ prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
122
+ "Cite each reference using [ Page Number] notation (every result has this number at the beginning). "\
123
+ "Citation should be done at the end of each sentence. If the search results mention multiple subjects "\
124
+ "with the same name, create separate answers for each. Only include information found in the results and "\
125
+ "don't add any additional information. Make sure the answer is correct and don't output false content. "\
126
+ "If the text does not relate to the query, simply state 'Text Not Found in PDF'. Ignore outlier "\
127
+ "search results which has nothing to do with the question. Only answer what is asked. The "\
128
+ "answer should be short and concise. Answer step-by-step. \n\nQuery: {question}\nAnswer: "
129
 
 
 
 
 
 
 
 
 
 
130
  prompt += f"Query: {question}\nAnswer:"
131
+ answer = generate_text(openAI_key, prompt,"text-davinci-003")
132
  return answer
133
 
134
+
135
+ def question_answer(url, file, question,openAI_key):
136
+ if openAI_key.strip()=='':
137
  return '[ERROR]: Please enter you Open AI Key. Get your key here : https://platform.openai.com/account/api-keys'
138
  if url.strip() == '' and file == None:
139
+ return '[ERROR]: Both URL and PDF is empty. Provide atleast one.'
140
+
141
  if url.strip() != '' and file != None:
142
+ return '[ERROR]: Both URL and PDF is provided. Please provide only one (eiter URL or PDF).'
143
 
144
  if url.strip() != '':
145
  glob_url = url
146
  download_pdf(glob_url, 'corpus.pdf')
147
+ load_recommender('corpus.pdf')
148
 
149
  else:
150
  old_file_name = file.name
151
  file_name = file.name
152
  file_name = file_name[:-12] + file_name[-4:]
153
  os.rename(old_file_name, file_name)
154
+ load_recommender(file_name)
155
 
156
  if question.strip() == '':
157
  return '[ERROR]: Question field is empty'
158
 
159
+ return generate_answer(question,openAI_key)
160
+
161
 
162
+ recommender = SemanticSearch()
163
 
 
164
  title = 'PDF GPT'
165
+ description = """ What is PDF GPT ?
166
+ 1. The problem is that Open AI has a 4K token limit and cannot take an entire PDF file as input. Additionally, it sometimes returns irrelevant responses due to poor embeddings. ChatGPT cannot directly talk to external data. The solution is PDF GPT, which allows you to chat with an uploaded PDF file using GPT functionalities. The application breaks the document into smaller chunks and generates embeddings using a powerful Deep Averaging Network Encoder. A semantic search is performed on your query, and the top relevant chunks are used to generate a response.
167
+ 2. 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. The Responses are much better than the naive responses by Open AI."""
168
 
169
  with gr.Blocks() as demo:
170
 
 
172
  gr.Markdown(description)
173
 
174
  with gr.Row():
175
+
176
  with gr.Group():
177
  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>')
178
  openAI_key=gr.Textbox(label='Enter your OpenAI API key here')
 
186
  with gr.Group():
187
  answer = gr.Textbox(label='The answer to your question is :')
188
 
189
+ btn.click(question_answer, inputs=[url, file, question,openAI_key], outputs=[answer])
190
+ #openai.api_key = os.getenv('Your_Key_Here')
191
  demo.launch()
192