bhaskartripathi commited on
Commit
d7831dc
β€’
1 Parent(s): 4b3e66b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +168 -0
app.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import urllib.request
2
+ import fitz
3
+ import re
4
+ import numpy as np
5
+ import tensorflow_hub as hub
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer
7
+ import gradio as gr
8
+ import os
9
+ from sklearn.neighbors import NearestNeighbors
10
+
11
+ tokenizer = AutoTokenizer.from_pretrained("tiiuae/falcon-40b-instruct")
12
+ model = AutoModelForCausalLM.from_pretrained("tiiuae/falcon-40b-instruct")
13
+
14
+ def download_pdf(url, output_path):
15
+ urllib.request.urlretrieve(url, output_path)
16
+
17
+ def preprocess(text):
18
+ text = text.replace('\n', ' ')
19
+ text = re.sub('\s+', ' ', text)
20
+ return text
21
+
22
+ def pdf_to_text(path, start_page=1, end_page=None):
23
+ doc = fitz.open(path)
24
+ total_pages = doc.page_count
25
+
26
+ if end_page is None:
27
+ end_page = total_pages
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)
35
+
36
+ doc.close()
37
+ return text_list
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]
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
+ class SemanticSearch:
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)
64
+ n_neighbors = min(n_neighbors, len(self.embeddings))
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)
85
+ return embeddings
86
+
87
+ def load_recommender(path, start_page=1):
88
+ global recommender
89
+ texts = pdf_to_text(path, start_page=start_page)
90
+ chunks = text_to_chunks(texts, start_page=start_page)
91
+ recommender.fit(chunks)
92
+ return 'Corpus Loaded.'
93
+
94
+ def generate_text(prompt, max_length=512):
95
+ inputs = tokenizer(prompt, return_tensors="pt")
96
+ outputs = model.generate(**inputs, max_length=max_length)
97
+ message = tokenizer.decode(outputs[0])
98
+ return message
99
+
100
+ def generate_answer(question):
101
+ topn_chunks = recommender(question)
102
+ prompt = ""
103
+ prompt += 'search results:\n\n'
104
+ for c in topn_chunks:
105
+ prompt += c + '\n\n'
106
+
107
+ prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
108
+ "Cite each reference using [ Page Number] notation (every result has this number at the beginning). "\
109
+ "Citation should be done at the end of each sentence. If the search results mention multiple subjects "\
110
+ "with the same name, create separate answers for each. Only include information found in the results and "\
111
+ "don't add any additional information. Make sure the answer is correct and don't output false content. "\
112
+ "If the text does not relate to the query, simply state 'Found Nothing'. Ignore outlier "\
113
+ "search results which has nothing to do with the question. Only answer what is asked. The "\
114
+ "answer should be short and concise. \n\nQuery: {question}\nAnswer: "
115
+
116
+ prompt += f"Query: {question}\nAnswer:"
117
+ answer = generate_text(prompt)
118
+ return answer
119
+
120
+ def question_answer(url, file, question):
121
+ if url.strip() == '' and file == None:
122
+ return '[ERROR]: Both URL and PDF is empty. Provide at least one.'
123
+
124
+ if url.strip() != '' and file != None:
125
+ return '[ERROR]: Both URL and PDF is provided. Please provide only one (either URL or PDF).'
126
+
127
+ if url.strip() != '':
128
+ glob_url = url
129
+ download_pdf(glob_url, 'corpus.pdf')
130
+ load_recommender('corpus.pdf')
131
+
132
+ else:
133
+ old_file_name = file.name
134
+ file_name = file.name
135
+ file_name = file_name[:-12] + file_name[-4:]
136
+ os.rename(old_file_name, file_name)
137
+ load_recommender(file_name)
138
+
139
+ if question.strip() == '':
140
+ return '[ERROR]: Question field is empty'
141
+
142
+ return generate_answer(question)
143
+
144
+ recommender = SemanticSearch()
145
+
146
+ title = 'PDF GPT'
147
+ description = """ PDF GPT allows you to chat with your PDF file using Universal Sentence Encoder and Falcon. 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."""
148
+
149
+ with gr.Blocks() as demo:
150
+
151
+ gr.Markdown(f'<center><h1>{title}</h1></center>')
152
+ gr.Markdown(description)
153
+
154
+ with gr.Row():
155
+
156
+ with gr.Group():
157
+ url = gr.Textbox(label='Enter PDF URL here')
158
+ gr.Markdown("<center><h4>OR<h4></center>")
159
+ file = gr.File(label='Upload your PDF/ Research Paper / Book here', file_types=['.pdf'])
160
+ question = gr.Textbox(label='Enter your question here')
161
+ btn = gr.Button(value='Submit')
162
+ btn.style(full_width=True)
163
+
164
+ with gr.Group():
165
+ answer = gr.Textbox(label='The answer to your question is :')
166
+
167
+ btn.click(question_answer, inputs=[url, file, question], outputs=[answer])
168
+ demo.launch()