alphayomega commited on
Commit
d33adfc
·
1 Parent(s): b3c15a7

Create app.py

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