Tj commited on
Commit
a9d9170
·
1 Parent(s): c6a2b84

Update app.py

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