ELEVEN-001 commited on
Commit
06fd46f
·
1 Parent(s): 69bdd2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -35
app.py CHANGED
@@ -8,6 +8,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
 
@@ -40,12 +41,12 @@ 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()
@@ -53,13 +54,14 @@ def text_to_chunks(texts, word_length=150, start_page=1):
53
  chunks.append(chunk)
54
  return chunks
55
 
 
56
  class SemanticSearch:
57
-
58
  def __init__(self):
59
- self.use = hub.load('https://tfhub.dev/google/universal-sentence-encoder/4')
 
60
  self.fitted = False
61
-
62
-
63
  def fit(self, data, batch=1000, n_neighbors=5):
64
  self.data = data
65
  self.embeddings = self.get_text_embedding(data, batch=batch)
@@ -67,18 +69,16 @@ class SemanticSearch:
67
  self.nn = NearestNeighbors(n_neighbors=n_neighbors)
68
  self.nn.fit(self.embeddings)
69
  self.fitted = True
70
-
71
-
72
  def __call__(self, text, return_data=True):
73
  inp_emb = self.use([text])
74
  neighbors = self.nn.kneighbors(inp_emb, return_distance=False)[0]
75
-
76
  if return_data:
77
  return [self.data[i] for i in neighbors]
78
  else:
79
  return neighbors
80
-
81
-
82
  def get_text_embedding(self, texts, batch=1000):
83
  embeddings = []
84
  for i in range(0, len(texts), batch):
@@ -89,7 +89,6 @@ class SemanticSearch:
89
  return embeddings
90
 
91
 
92
-
93
  def load_recommender(path, start_page=1):
94
  global recommender
95
  texts = pdf_to_text(path, start_page=start_page)
@@ -97,7 +96,8 @@ def load_recommender(path, start_page=1):
97
  recommender.fit(chunks)
98
  return 'Corpus Loaded.'
99
 
100
- def generate_text(openAI_key,prompt, engine="text-davinci-003"):
 
101
  openai.api_key = openAI_key
102
  completions = openai.Completion.create(
103
  engine=engine,
@@ -110,13 +110,14 @@ def generate_text(openAI_key,prompt, engine="text-davinci-003"):
110
  message = completions.choices[0].text
111
  return message
112
 
113
- def generate_answer(question,openAI_key):
 
114
  topn_chunks = recommender(question)
115
  prompt = ""
116
  prompt += 'search results:\n\n'
117
  for c in topn_chunks:
118
  prompt += c + '\n\n'
119
-
120
  prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
121
  "Cite each reference using [ Page Number] notation (every result has this number at the beginning). "\
122
  "Citation should be done at the end of each sentence. If the search results mention multiple subjects "\
@@ -126,18 +127,18 @@ def generate_answer(question,openAI_key):
126
  "search results which has nothing to do with the question. Only answer what is asked. The "\
127
  "answer should be short and concise. Answer step-by-step. \n\nQuery: {question}\nAnswer: "\
128
  "if you are asked to make questions from the pdf that you are provided with, kindly make it according to the question"
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
 
@@ -150,7 +151,7 @@ def question_answer(url, file, question,openAI_key):
150
  old_file_name = file.name
151
  file_name = file.name
152
  file_name = file_name[:-12] + file_name[-4:]
153
-
154
  # Rename the file
155
  os.rename(old_file_name, file_name)
156
  load_recommender(file_name)
@@ -159,17 +160,16 @@ def question_answer(url, file, question,openAI_key):
159
  if os.path.exists(file_name):
160
  os.remove(file_name)
161
 
162
-
163
  if question.strip() == '':
164
  return '[ERROR]: Question field is empty'
165
 
166
- return generate_answer(question,openAI_key)
167
 
168
 
169
  recommender = SemanticSearch()
170
 
171
  title = 'ChatToFiles'
172
- description = """ PDF GPT is a cutting-edge tool that facilitates conversation with PDF files utilizing Universal Sentence Encoder and Open AI technology. This tool is particularly advantageous as it delivers more reliable responses than other comparable tools, thanks to its superior embeddings, which eliminate hallucination errors. Additionally, when providing answers, PDF GPT can cite the exact page number where the relevant information is located within the PDF file, which enhances the credibility of the responses and expedites the process of finding pertinent information."""
173
 
174
  with gr.Blocks() as iface:
175
 
@@ -177,20 +177,24 @@ with gr.Blocks() as iface:
177
  gr.Markdown(description)
178
 
179
  with gr.Row():
180
-
181
  with gr.Group():
182
- openAI_key=gr.Textbox(label='Enter your OpenAI API key here')
183
- url = gr.Textbox(label='Enter PDF URL here')
184
- gr.Markdown("<center><h4>OR<h4></center>")
 
185
  file = gr.File(label='Drop PDF here', file_types=['.pdf'])
186
- question = gr.Textbox(label='Enter your question here')
 
187
  btn = gr.Button(value='Submit')
188
  btn.style(full_width=True)
189
 
190
  with gr.Group():
191
- answer = gr.Textbox(label='The answer to your question is :', lines=5, placeholder='Type your answer here...')
192
-
193
- btn.click(question_answer, inputs=[url, file, question,openAI_key], outputs=[answer])
194
- #openai.api_key = os.getenv('Your_Key_Here')
195
- #iface.launch()
196
- iface.launch()
 
 
 
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
 
 
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()
 
54
  chunks.append(chunk)
55
  return chunks
56
 
57
+
58
  class SemanticSearch:
59
+
60
  def __init__(self):
61
+ self.use = hub.load(
62
+ 'https://tfhub.dev/google/universal-sentence-encoder/4')
63
  self.fitted = False
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)
 
69
  self.nn = NearestNeighbors(n_neighbors=n_neighbors)
70
  self.nn.fit(self.embeddings)
71
  self.fitted = True
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
  def get_text_embedding(self, texts, batch=1000):
83
  embeddings = []
84
  for i in range(0, len(texts), batch):
 
89
  return embeddings
90
 
91
 
 
92
  def load_recommender(path, start_page=1):
93
  global recommender
94
  texts = pdf_to_text(path, start_page=start_page)
 
96
  recommender.fit(chunks)
97
  return 'Corpus Loaded.'
98
 
99
+
100
+ def generate_text(openAI_key, prompt, engine="text-davinci-003"):
101
  openai.api_key = openAI_key
102
  completions = openai.Completion.create(
103
  engine=engine,
 
110
  message = completions.choices[0].text
111
  return message
112
 
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 "\
 
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
  "if you are asked to make questions from the pdf that you are provided with, kindly make it according to the question"
130
+
131
  prompt += f"Query: {question}\nAnswer:"
132
+ answer = generate_text(openAI_key, prompt, "text-davinci-003")
133
  return answer
134
 
135
 
136
+ def question_answer(url, file, question, openAI_key):
137
+ if openAI_key.strip() == '':
138
  return '[ERROR]: Please enter you Open AI Key. Get your key here : https://platform.openai.com/account/api-keys'
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
 
 
151
  old_file_name = file.name
152
  file_name = file.name
153
  file_name = file_name[:-12] + file_name[-4:]
154
+
155
  # Rename the file
156
  os.rename(old_file_name, file_name)
157
  load_recommender(file_name)
 
160
  if os.path.exists(file_name):
161
  os.remove(file_name)
162
 
 
163
  if question.strip() == '':
164
  return '[ERROR]: Question field is empty'
165
 
166
+ return generate_answer(question, openAI_key)
167
 
168
 
169
  recommender = SemanticSearch()
170
 
171
  title = 'ChatToFiles'
172
+ description = """ ChatToFiles is a cutting-edge tool that facilitates conversation with PDF files utilizing Universal Sentence Encoder and Open AI technology. This tool is particularly advantageous as it delivers more reliable responses than other comparable tools, thanks to its superior embeddings, which eliminate hallucination errors. Additionally, when providing answers, PDF GPT can cite the exact page number where the relevant information is located within the PDF file, which enhances the credibility of the responses and expedites the process of finding pertinent information."""
173
 
174
  with gr.Blocks() as iface:
175
 
 
177
  gr.Markdown(description)
178
 
179
  with gr.Row():
180
+
181
  with gr.Group():
182
+ openAI_key = gr.Textbox(label='Enter your OpenAI API key here', placeholder='sk-')
183
+ url = gr.Textbox(label='Enter PDF URL here', placeholder='https://docs.pdf')
184
+ gr.Markdown(
185
+ "<center><h4>----------------------------------------------------------------------------------------------------------------------------------------------------<h4></center>")
186
  file = gr.File(label='Drop PDF here', file_types=['.pdf'])
187
+ question = gr.Textbox(
188
+ label='Enter your question here', placeholder='Type your question here')
189
  btn = gr.Button(value='Submit')
190
  btn.style(full_width=True)
191
 
192
  with gr.Group():
193
+ answer = gr.Textbox(label='The answer to your question is :',
194
+ lines=5, placeholder='Your answer here...')
195
+
196
+ btn.click(question_answer, inputs=[
197
+ url, file, question, openAI_key], outputs=[answer])
198
+ # openai.api_key = os.getenv('Your_Key_Here')
199
+ iface.launch()
200
+ # iface.launch(share=True)