u393845 commited on
Commit
5ab686f
1 Parent(s): cb52478
Files changed (3) hide show
  1. app.py +114 -193
  2. app_old_1.py +366 -0
  3. requirements.txt +2 -2
app.py CHANGED
@@ -1,32 +1,15 @@
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
- #from pathlib import Path
11
- #from dotenv import load_dotenv
12
-
13
- # dotenv_path = Path('azure_key.env')
14
- # load_dotenv(dotenv_path=dotenv_path)
15
-
16
- openai.api_type = "azure"
17
- openai.api_version = "azure"
18
- openai.api_base = "azure" # Your Azure OpenAI resource's endpoint value.
19
- openai.api_key = "azure"
20
-
21
- print(openai.api_key)
22
-
23
-
24
 
25
  def download_pdf(url, output_path):
26
- try:
27
- urllib.request.urlretrieve(url, output_path)
28
- except:
29
- print('error in download file')
30
 
31
 
32
  def preprocess(text):
@@ -44,7 +27,7 @@ def pdf_to_text(path, start_page=1, end_page=None):
44
 
45
  text_list = []
46
 
47
- for i in range(start_page - 1, end_page):
48
  text = doc.load_page(i).get_text("text")
49
  text = preprocess(text)
50
  text_list.append(text)
@@ -57,29 +40,27 @@ def text_to_chunks(texts, word_length=150, start_page=1):
57
  text_toks = [t.split(' ') for t in texts]
58
  page_nums = []
59
  chunks = []
60
-
61
  for idx, words in enumerate(text_toks):
62
  for i in range(0, len(words), word_length):
63
- chunk = words[i:i + word_length]
64
- if (i + word_length) > len(words) and (len(chunk) < word_length) and (
65
- len(text_toks) != (idx + 1)):
66
- text_toks[idx + 1] = chunk + text_toks[idx + 1]
67
  continue
68
  chunk = ' '.join(chunk).strip()
69
- chunk = f'[Page no. {idx + start_page}]' + ' ' + '"' + chunk + '"'
70
  chunks.append(chunk)
71
  return chunks
72
 
73
 
74
  class SemanticSearch:
75
-
76
  def __init__(self):
77
- #self.use = hub.load('https://tfhub.dev/google/universal-sentence-encoder/4')
78
- #self.use = hub.load(r'C:\Users\u393845\wns\GenAI\universal-sentence-encoder_4')
79
- #self.use = hub.load('/home/wnsuser/ESG/Django/Dev/Resources/USE')
80
- self.use = None
81
  self.fitted = False
82
-
 
83
  def fit(self, data, batch=1000, n_neighbors=5):
84
  self.data = data
85
  self.embeddings = self.get_text_embedding(data, batch=batch)
@@ -87,26 +68,29 @@ class SemanticSearch:
87
  self.nn = NearestNeighbors(n_neighbors=n_neighbors)
88
  self.nn.fit(self.embeddings)
89
  self.fitted = True
90
-
 
91
  def __call__(self, text, return_data=True):
92
  inp_emb = self.use([text])
93
  neighbors = self.nn.kneighbors(inp_emb, return_distance=False)[0]
94
-
95
  if return_data:
96
  return [self.data[i] for i in neighbors]
97
  else:
98
  return neighbors
99
-
 
100
  def get_text_embedding(self, texts, batch=1000):
101
  embeddings = []
102
  for i in range(0, len(texts), batch):
103
- text_batch = texts[i:(i + batch)]
104
  emb_batch = self.use(text_batch)
105
  embeddings.append(emb_batch)
106
  embeddings = np.vstack(embeddings)
107
  return embeddings
108
 
109
 
 
110
  def load_recommender(path, start_page=1):
111
  global recommender
112
  texts = pdf_to_text(path, start_page=start_page)
@@ -114,14 +98,13 @@ def load_recommender(path, start_page=1):
114
  recommender.fit(chunks)
115
  return 'Corpus Loaded.'
116
 
117
-
118
  def generate_text(openAI_key, prompt, model="gpt-3.5-turbo"):
119
  openai.api_key = openAI_key
120
- temperature = 0.7
121
- max_tokens = 256
122
- top_p = 1
123
- frequency_penalty = 0
124
- presence_penalty = 0
125
 
126
  if model == "text-davinci-003":
127
  completions = openai.Completion.create(
@@ -149,59 +132,46 @@ def generate_text(openAI_key, prompt, model="gpt-3.5-turbo"):
149
  ).choices[0].message['content']
150
  return message
151
 
152
-
153
  def generate_answer(question, openAI_key, model):
154
  topn_chunks = recommender(question)
155
  prompt = 'search results:\n\n'
156
  for c in topn_chunks:
157
  prompt += c + '\n\n'
158
-
159
- prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. " \
160
- "Cite each reference using [ Page Number] notation. " \
161
  "Only answer what is asked. The answer should be short and concise. \n\nQuery: "
162
-
163
  prompt += f"{question}\nAnswer:"
164
  answer = generate_text(openAI_key, prompt, model)
165
  return answer
166
 
167
 
168
- def question_answer(chat_history, url, file, question, model):
169
- openAI_key = openai.api_key
170
-
171
- qna_dic = {"What is the total scope 1 GHG emission?":"The total scope 1 GHG emission in FY 2022-23 is 2,942 tons of CO2e [Page no. 116].",
172
- "What is the total scope 2 GHG emission?":"The total scope 2 GHG emission in FY 2022-23 is 19,586 tons of CO2e [Page no. 116].",
173
- "What is the total scope 3 GHG emission?":"WNS measures and tracks its direct (Scope 1) and indirect (Scope 2) GHG emissions in context with its energy consumption. The methodology used for calculating GHG emissions is aligned with the globally accepted GHG protocol standards developed by the World Resources Institute. Additionally, WNS has joined the “Race to Zero” campaign backed by the United Nations and committed to attaining science-based net-zero targets. WNS is leveraging a high-quality technical tool to monitor and measure data across multiple locations and gather insights for tracking and improving its performance. The total Scope 3 GHG emission is not reported, however, WNS may evaluate this disclosure requirement in the near future. [Page no. 116, 129]",
174
- "What are the main results of the study?":"The main results of the study include the formulation of a policy to ensure a working environment free of discrimination or harassment and where all employees are treated with dignity and respect [Page no. 69], an extensive internal review of ESG topics previously identified in a detailed ESG materiality survey conducted by ESG advisors from Nasdaq Corporate Solutions [Page no. 16], a 12-week-long fellowship program that focuses on youth leadership [Page no. 21], and a focus on improving the diverse representation of the workforce, linking a portion of executive compensation to diversity targets, and recognizing and reinforcing inclusive behavior in the organization [Page no. 33].",
175
- "What are the main contributions of this study?":"This study focuses on improving the diverse representation of the workforce, linking a portion of executive compensation to diversity targets, recognizing and reinforcing inclusive behavior in the organization, creating several different categories of awards, and focusing on gender advancement, enhancing inclusivity and mental wellness. [Page no. 33] It also works toward improving gender representation in the organization across levels, runs multiple recruitment initiatives, and focuses on encouraging reading among schoolchildren through the management of 17 community libraries and 176 school libraries in India and one school library in China. [Page no. 19] Additionally, WNS has signed a letter of commitment with the Science Based Targets initiative in December 2022, switched to green power in 14 offices in India and Costa Rica, and spent $1,603,967 on community outreach. [Page no. 7]"}
176
-
177
-
178
  try:
179
- if openAI_key.strip() == '':
180
  return '[ERROR]: Please enter your Open AI Key. Get your key here : https://platform.openai.com/account/api-keys'
181
  if url.strip() == '' and file is None:
182
  return '[ERROR]: Both URL and PDF is empty. Provide at least one.'
183
  if url.strip() != '' and file is not None:
184
  return '[ERROR]: Both URL and PDF is provided. Please provide only one (either URL or PDF).'
185
- if model is None or model == '':
186
  return '[ERROR]: You have not selected any model. Please choose an LLM model.'
187
  if url.strip() != '':
188
  glob_url = url
189
  download_pdf(glob_url, 'corpus.pdf')
190
  load_recommender('corpus.pdf')
191
  else:
192
- pass
193
- # old_file_name = file.name
194
- # file_name = file.name
195
- # file_name = file_name[:-12] + file_name[-4:]
196
- # os.rename(old_file_name, file_name)
197
- # load_recommender(file_name)
198
- #load_recommender(file)
199
  if question.strip() == '':
200
  return '[ERROR]: Question field is empty'
201
  if model == "text-davinci-003" or model == "gpt-4" or model == "gpt-4-32k":
202
-
203
- answer = qna_dic[question]
204
- #answer = generate_answer_text_davinci_003(question, openAI_key)
205
  else:
206
  answer = generate_answer(question, openAI_key, model)
207
  chat_history.append([question, answer])
@@ -210,157 +180,108 @@ def question_answer(chat_history, url, file, question, model):
210
  return f'[ERROR]: Either you do not have access to GPT4 or you have exhausted your quota!'
211
 
212
 
213
- def generate_text_text_davinci_003(openAI_key, prompt, engine="text-davinci-003"):
 
214
  openai.api_key = openAI_key
215
  completions = openai.Completion.create(
216
- # engine=engine,
217
- # prompt=prompt,
218
- # max_tokens=512,
219
- # n=1,
220
- # stop=None,
221
- # temperature=0.7,
222
-
223
- engine="davinci003",
224
  prompt=prompt,
225
- temperature=0.1,
226
- max_tokens=400,
227
- top_p=1,
228
- frequency_penalty=0,
229
- presence_penalty=0,
230
- stop=None
231
  )
232
  message = completions.choices[0].text
233
  return message
234
 
235
 
236
- def generate_answer_text_davinci_003(question, openAI_key):
237
  topn_chunks = recommender(question)
238
  prompt = ""
239
  prompt += 'search results:\n\n'
240
  for c in topn_chunks:
241
  prompt += c + '\n\n'
242
-
243
- prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. " \
244
- "Cite each reference using [ Page Number] notation (every result has this number at the beginning). " \
245
- "Citation should be done at the end of each sentence. If the search results mention multiple subjects " \
246
- "with the same name, create separate answers for each. Only include information found in the results and " \
247
- "don't add any additional information. Make sure the answer is correct and don't output false content. " \
248
- "If the text does not relate to the query, simply state 'Found Nothing'. Ignore outlier " \
249
- "search results which has nothing to do with the question. Only answer what is asked. The " \
250
  "answer should be short and concise. \n\nQuery: {question}\nAnswer: "
251
-
252
  prompt += f"Query: {question}\nAnswer:"
253
- answer = generate_text_text_davinci_003(openAI_key, prompt, "text-davinci-003")
254
  return answer
255
 
256
-
257
  # pre-defined questions
258
  questions = [
259
- "What is the total scope 1 GHG emission?",
260
- "What is the total scope 2 GHG emission?",
261
- "What is the total scope 3 GHG emission?",
262
- "What are the main results of the study?",
263
- "What are the main contributions of this study?",
 
 
 
 
 
 
 
264
  ]
265
 
266
- recommender = SemanticSearch()
267
 
268
- # title = 'PDF GPT Turbo'
269
- # description = """ PDF GPT Turbo allows you to chat with your PDF files. It uses Google's Universal Sentence Encoder with Deep averaging network (DAN) to give hallucination free response by improving the embedding quality of OpenAI. It cites the page number in square brackets([Page No.]) and shows where the information is located, adding credibility to the responses."""
270
- #
271
- # with gr.Blocks(css="""#chatbot { font-size: 14px; min-height: 1200; }""") as demo:
272
- # gr.Markdown(f'<center><h3>{title}</h3></center>')
273
- # gr.Markdown(description)
274
- #
275
- # try:
276
- # with gr.Row():
277
- # with gr.Group():
278
- # #gr.Markdown(
279
- # # f'<p style="text-align:center">Get your Open AI API key <a href="https://platform.openai.com/account/api-keys">here</a></p>')
280
- # with gr.Accordion(""):
281
- # #openAI_key = gr.Textbox(label='Enter your OpenAI API key here', password=True)
282
- # url = gr.Textbox(label='Enter PDF URL here (Example: https://arxiv.org/pdf/1706.03762.pdf )')
283
- # gr.Markdown("<center><h4>OR<h4></center>")
284
- # file = gr.File(label='Upload your PDF/ Research Paper / Book here', file_types=['.pdf'])
285
- # question = gr.Textbox(label='Enter your question here')
286
- # gr.Examples(
287
- # [[q] for q in questions],
288
- # inputs=[question],
289
- # label="PRE-DEFINED QUESTIONS: Click on a question to auto-fill the input box, then press Enter!",
290
- # )
291
- # model = gr.Radio([
292
- # 'gpt-3.5-turbo',
293
- # 'gpt-3.5-turbo-16k',
294
- # 'gpt-3.5-turbo-0613',
295
- # 'gpt-3.5-turbo-16k-0613',
296
- # 'text-davinci-003',
297
- # 'gpt-4',
298
- # 'gpt-4-32k'
299
- # ], label='Select Model', default='gpt-3.5-turbo')
300
- # btn = gr.Button(value='Submit')
301
- #
302
- # btn.style(full_width=True)
303
- #
304
- # with gr.Group():
305
- # chatbot = gr.Chatbot(placeholder="Chat History", label="Chat History", lines=50, elem_id="chatbot")
306
- # except:
307
- # print("error in gradio")
308
- # #
309
- # # Bind the click event of the button to the question_answer function
310
- #
311
- # try:
312
- # btn.click(
313
- # question_answer,
314
- # inputs=[chatbot, url, file, question, model],
315
- # outputs=[chatbot],
316
- # )
317
- # except:
318
- # print("error in btn.click")
319
- #
320
- # #demo.launch(server_name="10.31.8.38")
321
- # demo.launch(share=True)
322
 
323
  title = 'PDF GPT Turbo'
324
  description = """ PDF GPT Turbo allows you to chat with your PDF files. It uses Google's Universal Sentence Encoder with Deep averaging network (DAN) to give hallucination free response by improving the embedding quality of OpenAI. It cites the page number in square brackets([Page No.]) and shows where the information is located, adding credibility to the responses."""
325
 
326
  with gr.Blocks(css="""#chatbot { font-size: 14px; min-height: 1200; }""") as demo:
 
327
  gr.Markdown(f'<center><h3>{title}</h3></center>')
328
  gr.Markdown(description)
329
 
330
- try:
331
- with gr.Row():
332
- with gr.Group():
333
- with gr.Accordion(""):
334
- url = gr.Textbox(label='Enter PDF URL here (Example: https://arxiv.org/pdf/1706.03762.pdf )')
335
- gr.Markdown("<center><h4>OR<h4></center>")
336
- file = gr.File(label='Upload your PDF/ Research Paper / Book here', file_types=['.pdf'])
337
- question = gr.Textbox(label='Enter your question here')
338
- gr.Examples(
339
- [[q] for q in questions],
340
- inputs=[question],
341
- label="PRE-DEFINED QUESTIONS: Click on a question to auto-fill the input box, then press Enter!",
342
- )
343
- model = gr.Radio([
344
- 'gpt-3.5-turbo',
345
- 'gpt-3.5-turbo-16k',
346
- 'gpt-3.5-turbo-0613',
347
- 'gpt-3.5-turbo-16k-0613',
348
- 'text-davinci-003',
349
- 'gpt-4',
350
- 'gpt-4-32k'
351
- ], label='Select Model', default='gpt-3.5-turbo')
352
-
353
- with gr.Group():
354
- btn = gr.Button(value='Submit')
355
- btn.style(full_width=True)
356
- chatbot = gr.Chatbot(placeholder="Chat History", label="Chat History", lines=50, elem_id="chatbot")
357
- btn.click(
358
- question_answer,
359
- inputs=[chatbot, url, file, question, model],
360
- outputs=[chatbot],
361
- )
362
- except:
363
- print("error in gradio")
364
-
365
- demo.launch(share=True)
 
 
 
 
 
 
366
 
 
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):
 
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)
 
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'[Page no. {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)
 
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)
 
98
  recommender.fit(chunks)
99
  return 'Corpus Loaded.'
100
 
 
101
  def generate_text(openAI_key, prompt, model="gpt-3.5-turbo"):
102
  openai.api_key = openAI_key
103
+ temperature=0.7
104
+ max_tokens=256
105
+ top_p=1
106
+ frequency_penalty=0
107
+ presence_penalty=0
108
 
109
  if model == "text-davinci-003":
110
  completions = openai.Completion.create(
 
132
  ).choices[0].message['content']
133
  return message
134
 
135
+
136
  def generate_answer(question, openAI_key, model):
137
  topn_chunks = recommender(question)
138
  prompt = 'search results:\n\n'
139
  for c in topn_chunks:
140
  prompt += c + '\n\n'
141
+
142
+ prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
143
+ "Cite each reference using [ Page Number] notation. "\
144
  "Only answer what is asked. The answer should be short and concise. \n\nQuery: "
145
+
146
  prompt += f"{question}\nAnswer:"
147
  answer = generate_text(openAI_key, prompt, model)
148
  return answer
149
 
150
 
151
+ def question_answer(chat_history, url, file, question, openAI_key, model):
 
 
 
 
 
 
 
 
 
152
  try:
153
+ if openAI_key.strip()=='':
154
  return '[ERROR]: Please enter your Open AI Key. Get your key here : https://platform.openai.com/account/api-keys'
155
  if url.strip() == '' and file is None:
156
  return '[ERROR]: Both URL and PDF is empty. Provide at least one.'
157
  if url.strip() != '' and file is not None:
158
  return '[ERROR]: Both URL and PDF is provided. Please provide only one (either URL or PDF).'
159
+ if model is None or model =='':
160
  return '[ERROR]: You have not selected any model. Please choose an LLM model.'
161
  if url.strip() != '':
162
  glob_url = url
163
  download_pdf(glob_url, 'corpus.pdf')
164
  load_recommender('corpus.pdf')
165
  else:
166
+ old_file_name = file.name
167
+ file_name = file.name
168
+ file_name = file_name[:-12] + file_name[-4:]
169
+ os.rename(old_file_name, file_name)
170
+ load_recommender(file_name)
 
 
171
  if question.strip() == '':
172
  return '[ERROR]: Question field is empty'
173
  if model == "text-davinci-003" or model == "gpt-4" or model == "gpt-4-32k":
174
+ answer = generate_answer_text_davinci_003(question, openAI_key)
 
 
175
  else:
176
  answer = generate_answer(question, openAI_key, model)
177
  chat_history.append([question, answer])
 
180
  return f'[ERROR]: Either you do not have access to GPT4 or you have exhausted your quota!'
181
 
182
 
183
+
184
+ def generate_text_text_davinci_003(openAI_key,prompt, engine="text-davinci-003"):
185
  openai.api_key = openAI_key
186
  completions = openai.Completion.create(
187
+ engine=engine,
 
 
 
 
 
 
 
188
  prompt=prompt,
189
+ max_tokens=512,
190
+ n=1,
191
+ stop=None,
192
+ temperature=0.7,
 
 
193
  )
194
  message = completions.choices[0].text
195
  return message
196
 
197
 
198
+ def generate_answer_text_davinci_003(question,openAI_key):
199
  topn_chunks = recommender(question)
200
  prompt = ""
201
  prompt += 'search results:\n\n'
202
  for c in topn_chunks:
203
  prompt += c + '\n\n'
204
+
205
+ prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
206
+ "Cite each reference using [ Page Number] notation (every result has this number at the beginning). "\
207
+ "Citation should be done at the end of each sentence. If the search results mention multiple subjects "\
208
+ "with the same name, create separate answers for each. Only include information found in the results and "\
209
+ "don't add any additional information. Make sure the answer is correct and don't output false content. "\
210
+ "If the text does not relate to the query, simply state 'Found Nothing'. Ignore outlier "\
211
+ "search results which has nothing to do with the question. Only answer what is asked. The "\
212
  "answer should be short and concise. \n\nQuery: {question}\nAnswer: "
213
+
214
  prompt += f"Query: {question}\nAnswer:"
215
+ answer = generate_text_text_davinci_003(openAI_key, prompt,"text-davinci-003")
216
  return answer
217
 
 
218
  # pre-defined questions
219
  questions = [
220
+ "What did the study investigate?",
221
+ "Can you provide a summary of this paper?",
222
+ "what are the methodologies used in this study?",
223
+ "what are the data intervals used in this study? Give me the start dates and end dates?",
224
+ "what are the main limitations of this study?",
225
+ "what are the main shortcomings of this study?",
226
+ "what are the main findings of the study?",
227
+ "what are the main results of the study?",
228
+ "what are the main contributions of this study?",
229
+ "what is the conclusion of this paper?",
230
+ "what are the input features used in this study?",
231
+ "what is the dependent variable in this study?",
232
  ]
233
 
 
234
 
235
+ recommender = SemanticSearch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
  title = 'PDF GPT Turbo'
238
  description = """ PDF GPT Turbo allows you to chat with your PDF files. It uses Google's Universal Sentence Encoder with Deep averaging network (DAN) to give hallucination free response by improving the embedding quality of OpenAI. It cites the page number in square brackets([Page No.]) and shows where the information is located, adding credibility to the responses."""
239
 
240
  with gr.Blocks(css="""#chatbot { font-size: 14px; min-height: 1200; }""") as demo:
241
+
242
  gr.Markdown(f'<center><h3>{title}</h3></center>')
243
  gr.Markdown(description)
244
 
245
+ with gr.Row():
246
+
247
+ with gr.Group():
248
+ 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>')
249
+ with gr.Accordion("API Key"):
250
+ openAI_key = gr.Textbox(label='Enter your OpenAI API key here', password=True)
251
+ url = gr.Textbox(label='Enter PDF URL here (Example: https://arxiv.org/pdf/1706.03762.pdf )')
252
+ gr.Markdown("<center><h4>OR<h4></center>")
253
+ file = gr.File(label='Upload your PDF/ Research Paper / Book here', file_types=['.pdf'])
254
+ question = gr.Textbox(label='Enter your question here')
255
+ gr.Examples(
256
+ [[q] for q in questions],
257
+ inputs=[question],
258
+ label="PRE-DEFINED QUESTIONS: Click on a question to auto-fill the input box, then press Enter!",
259
+ )
260
+ model = gr.Radio([
261
+ 'gpt-3.5-turbo',
262
+ 'gpt-3.5-turbo-16k',
263
+ 'gpt-3.5-turbo-0613',
264
+ 'gpt-3.5-turbo-16k-0613',
265
+ 'text-davinci-003',
266
+ 'gpt-4',
267
+ 'gpt-4-32k'
268
+ ], label='Select Model', default='gpt-3.5-turbo')
269
+ btn = gr.Button(value='Submit')
270
+
271
+ btn.style(full_width=True)
272
+
273
+ with gr.Group():
274
+ chatbot = gr.Chatbot(placeholder="Chat History", label="Chat History", lines=50, elem_id="chatbot")
275
+
276
+
277
+ #
278
+ # Bind the click event of the button to the question_answer function
279
+ btn.click(
280
+ question_answer,
281
+ inputs=[chatbot, url, file, question, openAI_key, model],
282
+ outputs=[chatbot],
283
+ )
284
+
285
+ demo.launch()
286
+
287
 
app_old_1.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #from pathlib import Path
11
+ #from dotenv import load_dotenv
12
+
13
+ # dotenv_path = Path('azure_key.env')
14
+ # load_dotenv(dotenv_path=dotenv_path)
15
+
16
+ openai.api_type = "azure"
17
+ openai.api_version = "azure"
18
+ openai.api_base = "azure" # Your Azure OpenAI resource's endpoint value.
19
+ openai.api_key = "azure"
20
+
21
+ print(openai.api_key)
22
+
23
+
24
+
25
+ def download_pdf(url, output_path):
26
+ try:
27
+ urllib.request.urlretrieve(url, output_path)
28
+ except:
29
+ print('error in download file')
30
+
31
+
32
+ def preprocess(text):
33
+ text = text.replace('\n', ' ')
34
+ text = re.sub('\s+', ' ', text)
35
+ return text
36
+
37
+
38
+ def pdf_to_text(path, start_page=1, end_page=None):
39
+ doc = fitz.open(path)
40
+ total_pages = doc.page_count
41
+
42
+ if end_page is None:
43
+ end_page = total_pages
44
+
45
+ text_list = []
46
+
47
+ for i in range(start_page - 1, end_page):
48
+ text = doc.load_page(i).get_text("text")
49
+ text = preprocess(text)
50
+ text_list.append(text)
51
+
52
+ doc.close()
53
+ return text_list
54
+
55
+
56
+ def text_to_chunks(texts, word_length=150, start_page=1):
57
+ text_toks = [t.split(' ') for t in texts]
58
+ page_nums = []
59
+ chunks = []
60
+
61
+ for idx, words in enumerate(text_toks):
62
+ for i in range(0, len(words), word_length):
63
+ chunk = words[i:i + word_length]
64
+ if (i + word_length) > len(words) and (len(chunk) < word_length) and (
65
+ len(text_toks) != (idx + 1)):
66
+ text_toks[idx + 1] = chunk + text_toks[idx + 1]
67
+ continue
68
+ chunk = ' '.join(chunk).strip()
69
+ chunk = f'[Page no. {idx + start_page}]' + ' ' + '"' + chunk + '"'
70
+ chunks.append(chunk)
71
+ return chunks
72
+
73
+
74
+ class SemanticSearch:
75
+
76
+ def __init__(self):
77
+ #self.use = hub.load('https://tfhub.dev/google/universal-sentence-encoder/4')
78
+ #self.use = hub.load(r'C:\Users\u393845\wns\GenAI\universal-sentence-encoder_4')
79
+ #self.use = hub.load('/home/wnsuser/ESG/Django/Dev/Resources/USE')
80
+ self.use = None
81
+ self.fitted = False
82
+
83
+ def fit(self, data, batch=1000, n_neighbors=5):
84
+ self.data = data
85
+ self.embeddings = self.get_text_embedding(data, batch=batch)
86
+ n_neighbors = min(n_neighbors, len(self.embeddings))
87
+ self.nn = NearestNeighbors(n_neighbors=n_neighbors)
88
+ self.nn.fit(self.embeddings)
89
+ self.fitted = True
90
+
91
+ def __call__(self, text, return_data=True):
92
+ inp_emb = self.use([text])
93
+ neighbors = self.nn.kneighbors(inp_emb, return_distance=False)[0]
94
+
95
+ if return_data:
96
+ return [self.data[i] for i in neighbors]
97
+ else:
98
+ return neighbors
99
+
100
+ def get_text_embedding(self, texts, batch=1000):
101
+ embeddings = []
102
+ for i in range(0, len(texts), batch):
103
+ text_batch = texts[i:(i + batch)]
104
+ emb_batch = self.use(text_batch)
105
+ embeddings.append(emb_batch)
106
+ embeddings = np.vstack(embeddings)
107
+ return embeddings
108
+
109
+
110
+ def load_recommender(path, start_page=1):
111
+ global recommender
112
+ texts = pdf_to_text(path, start_page=start_page)
113
+ chunks = text_to_chunks(texts, start_page=start_page)
114
+ recommender.fit(chunks)
115
+ return 'Corpus Loaded.'
116
+
117
+
118
+ def generate_text(openAI_key, prompt, model="gpt-3.5-turbo"):
119
+ openai.api_key = openAI_key
120
+ temperature = 0.7
121
+ max_tokens = 256
122
+ top_p = 1
123
+ frequency_penalty = 0
124
+ presence_penalty = 0
125
+
126
+ if model == "text-davinci-003":
127
+ completions = openai.Completion.create(
128
+ engine=model,
129
+ prompt=prompt,
130
+ max_tokens=max_tokens,
131
+ n=1,
132
+ stop=None,
133
+ temperature=temperature,
134
+ )
135
+ message = completions.choices[0].text
136
+ else:
137
+ message = openai.ChatCompletion.create(
138
+ model=model,
139
+ messages=[
140
+ {"role": "system", "content": "You are a helpful assistant."},
141
+ {"role": "assistant", "content": "Here is some initial assistant message."},
142
+ {"role": "user", "content": prompt}
143
+ ],
144
+ temperature=.3,
145
+ max_tokens=max_tokens,
146
+ top_p=top_p,
147
+ frequency_penalty=frequency_penalty,
148
+ presence_penalty=presence_penalty,
149
+ ).choices[0].message['content']
150
+ return message
151
+
152
+
153
+ def generate_answer(question, openAI_key, model):
154
+ topn_chunks = recommender(question)
155
+ prompt = 'search results:\n\n'
156
+ for c in topn_chunks:
157
+ prompt += c + '\n\n'
158
+
159
+ prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. " \
160
+ "Cite each reference using [ Page Number] notation. " \
161
+ "Only answer what is asked. The answer should be short and concise. \n\nQuery: "
162
+
163
+ prompt += f"{question}\nAnswer:"
164
+ answer = generate_text(openAI_key, prompt, model)
165
+ return answer
166
+
167
+
168
+ def question_answer(chat_history, url, file, question, model):
169
+ openAI_key = openai.api_key
170
+
171
+ qna_dic = {"What is the total scope 1 GHG emission?":"The total scope 1 GHG emission in FY 2022-23 is 2,942 tons of CO2e [Page no. 116].",
172
+ "What is the total scope 2 GHG emission?":"The total scope 2 GHG emission in FY 2022-23 is 19,586 tons of CO2e [Page no. 116].",
173
+ "What is the total scope 3 GHG emission?":"WNS measures and tracks its direct (Scope 1) and indirect (Scope 2) GHG emissions in context with its energy consumption. The methodology used for calculating GHG emissions is aligned with the globally accepted GHG protocol standards developed by the World Resources Institute. Additionally, WNS has joined the “Race to Zero” campaign backed by the United Nations and committed to attaining science-based net-zero targets. WNS is leveraging a high-quality technical tool to monitor and measure data across multiple locations and gather insights for tracking and improving its performance. The total Scope 3 GHG emission is not reported, however, WNS may evaluate this disclosure requirement in the near future. [Page no. 116, 129]",
174
+ "What are the main results of the study?":"The main results of the study include the formulation of a policy to ensure a working environment free of discrimination or harassment and where all employees are treated with dignity and respect [Page no. 69], an extensive internal review of ESG topics previously identified in a detailed ESG materiality survey conducted by ESG advisors from Nasdaq Corporate Solutions [Page no. 16], a 12-week-long fellowship program that focuses on youth leadership [Page no. 21], and a focus on improving the diverse representation of the workforce, linking a portion of executive compensation to diversity targets, and recognizing and reinforcing inclusive behavior in the organization [Page no. 33].",
175
+ "What are the main contributions of this study?":"This study focuses on improving the diverse representation of the workforce, linking a portion of executive compensation to diversity targets, recognizing and reinforcing inclusive behavior in the organization, creating several different categories of awards, and focusing on gender advancement, enhancing inclusivity and mental wellness. [Page no. 33] It also works toward improving gender representation in the organization across levels, runs multiple recruitment initiatives, and focuses on encouraging reading among schoolchildren through the management of 17 community libraries and 176 school libraries in India and one school library in China. [Page no. 19] Additionally, WNS has signed a letter of commitment with the Science Based Targets initiative in December 2022, switched to green power in 14 offices in India and Costa Rica, and spent $1,603,967 on community outreach. [Page no. 7]"}
176
+
177
+
178
+ try:
179
+ if openAI_key.strip() == '':
180
+ return '[ERROR]: Please enter your Open AI Key. Get your key here : https://platform.openai.com/account/api-keys'
181
+ if url.strip() == '' and file is None:
182
+ return '[ERROR]: Both URL and PDF is empty. Provide at least one.'
183
+ if url.strip() != '' and file is not None:
184
+ return '[ERROR]: Both URL and PDF is provided. Please provide only one (either URL or PDF).'
185
+ if model is None or model == '':
186
+ return '[ERROR]: You have not selected any model. Please choose an LLM model.'
187
+ if url.strip() != '':
188
+ glob_url = url
189
+ download_pdf(glob_url, 'corpus.pdf')
190
+ load_recommender('corpus.pdf')
191
+ else:
192
+ pass
193
+ # old_file_name = file.name
194
+ # file_name = file.name
195
+ # file_name = file_name[:-12] + file_name[-4:]
196
+ # os.rename(old_file_name, file_name)
197
+ # load_recommender(file_name)
198
+ #load_recommender(file)
199
+ if question.strip() == '':
200
+ return '[ERROR]: Question field is empty'
201
+ if model == "text-davinci-003" or model == "gpt-4" or model == "gpt-4-32k":
202
+
203
+ answer = qna_dic[question]
204
+ #answer = generate_answer_text_davinci_003(question, openAI_key)
205
+ else:
206
+ answer = generate_answer(question, openAI_key, model)
207
+ chat_history.append([question, answer])
208
+ return chat_history
209
+ except openai.error.InvalidRequestError as e:
210
+ return f'[ERROR]: Either you do not have access to GPT4 or you have exhausted your quota!'
211
+
212
+
213
+ def generate_text_text_davinci_003(openAI_key, prompt, engine="text-davinci-003"):
214
+ openai.api_key = openAI_key
215
+ completions = openai.Completion.create(
216
+ # engine=engine,
217
+ # prompt=prompt,
218
+ # max_tokens=512,
219
+ # n=1,
220
+ # stop=None,
221
+ # temperature=0.7,
222
+
223
+ engine="davinci003",
224
+ prompt=prompt,
225
+ temperature=0.1,
226
+ max_tokens=400,
227
+ top_p=1,
228
+ frequency_penalty=0,
229
+ presence_penalty=0,
230
+ stop=None
231
+ )
232
+ message = completions.choices[0].text
233
+ return message
234
+
235
+
236
+ def generate_answer_text_davinci_003(question, openAI_key):
237
+ topn_chunks = recommender(question)
238
+ prompt = ""
239
+ prompt += 'search results:\n\n'
240
+ for c in topn_chunks:
241
+ prompt += c + '\n\n'
242
+
243
+ prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. " \
244
+ "Cite each reference using [ Page Number] notation (every result has this number at the beginning). " \
245
+ "Citation should be done at the end of each sentence. If the search results mention multiple subjects " \
246
+ "with the same name, create separate answers for each. Only include information found in the results and " \
247
+ "don't add any additional information. Make sure the answer is correct and don't output false content. " \
248
+ "If the text does not relate to the query, simply state 'Found Nothing'. Ignore outlier " \
249
+ "search results which has nothing to do with the question. Only answer what is asked. The " \
250
+ "answer should be short and concise. \n\nQuery: {question}\nAnswer: "
251
+
252
+ prompt += f"Query: {question}\nAnswer:"
253
+ answer = generate_text_text_davinci_003(openAI_key, prompt, "text-davinci-003")
254
+ return answer
255
+
256
+
257
+ # pre-defined questions
258
+ questions = [
259
+ "What is the total scope 1 GHG emission?",
260
+ "What is the total scope 2 GHG emission?",
261
+ "What is the total scope 3 GHG emission?",
262
+ "What are the main results of the study?",
263
+ "What are the main contributions of this study?",
264
+ ]
265
+
266
+ recommender = SemanticSearch()
267
+
268
+ # title = 'PDF GPT Turbo'
269
+ # description = """ PDF GPT Turbo allows you to chat with your PDF files. It uses Google's Universal Sentence Encoder with Deep averaging network (DAN) to give hallucination free response by improving the embedding quality of OpenAI. It cites the page number in square brackets([Page No.]) and shows where the information is located, adding credibility to the responses."""
270
+ #
271
+ # with gr.Blocks(css="""#chatbot { font-size: 14px; min-height: 1200; }""") as demo:
272
+ # gr.Markdown(f'<center><h3>{title}</h3></center>')
273
+ # gr.Markdown(description)
274
+ #
275
+ # try:
276
+ # with gr.Row():
277
+ # with gr.Group():
278
+ # #gr.Markdown(
279
+ # # f'<p style="text-align:center">Get your Open AI API key <a href="https://platform.openai.com/account/api-keys">here</a></p>')
280
+ # with gr.Accordion(""):
281
+ # #openAI_key = gr.Textbox(label='Enter your OpenAI API key here', password=True)
282
+ # url = gr.Textbox(label='Enter PDF URL here (Example: https://arxiv.org/pdf/1706.03762.pdf )')
283
+ # gr.Markdown("<center><h4>OR<h4></center>")
284
+ # file = gr.File(label='Upload your PDF/ Research Paper / Book here', file_types=['.pdf'])
285
+ # question = gr.Textbox(label='Enter your question here')
286
+ # gr.Examples(
287
+ # [[q] for q in questions],
288
+ # inputs=[question],
289
+ # label="PRE-DEFINED QUESTIONS: Click on a question to auto-fill the input box, then press Enter!",
290
+ # )
291
+ # model = gr.Radio([
292
+ # 'gpt-3.5-turbo',
293
+ # 'gpt-3.5-turbo-16k',
294
+ # 'gpt-3.5-turbo-0613',
295
+ # 'gpt-3.5-turbo-16k-0613',
296
+ # 'text-davinci-003',
297
+ # 'gpt-4',
298
+ # 'gpt-4-32k'
299
+ # ], label='Select Model', default='gpt-3.5-turbo')
300
+ # btn = gr.Button(value='Submit')
301
+ #
302
+ # btn.style(full_width=True)
303
+ #
304
+ # with gr.Group():
305
+ # chatbot = gr.Chatbot(placeholder="Chat History", label="Chat History", lines=50, elem_id="chatbot")
306
+ # except:
307
+ # print("error in gradio")
308
+ # #
309
+ # # Bind the click event of the button to the question_answer function
310
+ #
311
+ # try:
312
+ # btn.click(
313
+ # question_answer,
314
+ # inputs=[chatbot, url, file, question, model],
315
+ # outputs=[chatbot],
316
+ # )
317
+ # except:
318
+ # print("error in btn.click")
319
+ #
320
+ # #demo.launch(server_name="10.31.8.38")
321
+ # demo.launch(share=True)
322
+
323
+ title = 'PDF GPT Turbo'
324
+ description = """ PDF GPT Turbo allows you to chat with your PDF files. It uses Google's Universal Sentence Encoder with Deep averaging network (DAN) to give hallucination free response by improving the embedding quality of OpenAI. It cites the page number in square brackets([Page No.]) and shows where the information is located, adding credibility to the responses."""
325
+
326
+ with gr.Blocks(css="""#chatbot { font-size: 14px; min-height: 1200; }""") as demo:
327
+ gr.Markdown(f'<center><h3>{title}</h3></center>')
328
+ gr.Markdown(description)
329
+
330
+ try:
331
+ with gr.Row():
332
+ with gr.Group():
333
+ with gr.Accordion(""):
334
+ url = gr.Textbox(label='Enter PDF URL here (Example: https://arxiv.org/pdf/1706.03762.pdf )')
335
+ gr.Markdown("<center><h4>OR<h4></center>")
336
+ file = gr.File(label='Upload your PDF/ Research Paper / Book here', file_types=['.pdf'])
337
+ question = gr.Textbox(label='Enter your question here')
338
+ gr.Examples(
339
+ [[q] for q in questions],
340
+ inputs=[question],
341
+ label="PRE-DEFINED QUESTIONS: Click on a question to auto-fill the input box, then press Enter!",
342
+ )
343
+ model = gr.Radio([
344
+ 'gpt-3.5-turbo',
345
+ 'gpt-3.5-turbo-16k',
346
+ 'gpt-3.5-turbo-0613',
347
+ 'gpt-3.5-turbo-16k-0613',
348
+ 'text-davinci-003',
349
+ 'gpt-4',
350
+ 'gpt-4-32k'
351
+ ], label='Select Model', default='gpt-3.5-turbo')
352
+
353
+ with gr.Group():
354
+ btn = gr.Button(value='Submit')
355
+ btn.style(full_width=True)
356
+ chatbot = gr.Chatbot(placeholder="Chat History", label="Chat History", lines=50, elem_id="chatbot")
357
+ btn.click(
358
+ question_answer,
359
+ inputs=[chatbot, url, file, question, model],
360
+ outputs=[chatbot],
361
+ )
362
+ except:
363
+ print("error in gradio")
364
+
365
+ demo.launch(share=True)
366
+
requirements.txt CHANGED
@@ -1,5 +1,5 @@
1
- gradio==3.20.0
2
- PyMuPDF==1.22.5
3
  numpy
4
  scikit-learn
5
  tensorflow
 
1
+ gradio
2
+ PyMuPDF
3
  numpy
4
  scikit-learn
5
  tensorflow