maconphillips commited on
Commit
54c69b3
·
1 Parent(s): 9da5873

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -0
app.py CHANGED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def preprocess(text):
15
+ text = text.replace('\n', ' ')
16
+ text = re.sub('\s+', ' ', text)
17
+ return text
18
+
19
+ def pdf_to_text(path, start_page=1, end_page=None):
20
+ doc = fitz.open(path)
21
+ total_pages = doc.page_count
22
+
23
+ if end_page is None:
24
+ end_page = total_pages
25
+
26
+ text_list = []
27
+
28
+ for i in range(start_page-1, end_page):
29
+ text = doc.load_page(i).get_text("text")
30
+ text = preprocess(text)
31
+ text_list.append(text)
32
+
33
+ doc.close()
34
+ return text_list
35
+
36
+ def text_to_chunks(texts, word_length=150, start_page=1):
37
+ text_toks = [t.split(' ') for t in texts]
38
+ page_nums = []
39
+ chunks = []
40
+
41
+ for idx, words in enumerate(text_toks):
42
+ for i in range(0, len(words), word_length):
43
+ chunk = words[i:i+word_length]
44
+ if (i+word_length) > len(words) and (len(chunk) < word_length) and (
45
+ len(text_toks) != (idx+1)):
46
+ text_toks[idx+1] = chunk + text_toks[idx+1]
47
+ continue
48
+ chunk = ' '.join(chunk).strip()
49
+ chunk = f'[Page no. {idx+start_page}]' + ' ' + '"' + chunk + '"'
50
+ chunks.append(chunk)
51
+ return chunks
52
+
53
+ class SemanticSearch:
54
+
55
+ def __init__(self):
56
+ self.use = hub.load('https://tfhub.dev/google/universal-sentence-encoder/4')
57
+ self.fitted = False
58
+
59
+ def fit(self, data, batch=1000, n_neighbors=5):
60
+ self.data = data
61
+ self.embeddings = self.get_text_embedding(data, batch=batch)
62
+ n_neighbors = min(n_neighbors, len(self.embeddings))
63
+ self.nn = NearestNeighbors(n_neighbors=n_neighbors)
64
+ self.nn.fit(self.embeddings)
65
+ self.fitted = True
66
+
67
+ def __call__(self, text, return_data=True):
68
+ inp_emb = self.use([text])
69
+ neighbors = self.nn.kneighbors(inp_emb, return_distance=False)[0]
70
+
71
+ if return_data:
72
+ return [self.data[i] for i in neighbors]
73
+ else:
74
+ return neighbors
75
+
76
+ def get_text_embedding(self, texts, batch=1000):
77
+ embeddings = []
78
+ for i in range(0, len(texts), batch):
79
+ text_batch = texts[i:(i+batch)]
80
+ emb_batch = self.use(text_batch)
81
+ embeddings.append(emb_batch)
82
+ embeddings = np.vstack(embeddings)
83
+ return embeddings
84
+
85
+ def load_recommender(path, start_page=1):
86
+ global recommender
87
+ texts = pdf_to_text(path, start_page=start_page)
88
+ chunks = text_to_chunks(texts, start_page=start_page)
89
+ recommender.fit(chunks)
90
+ return 'Corpus Loaded.'
91
+
92
+ def generate_text(openAI_key,prompt, engine="text-davinci-003"):
93
+ openai.api_key = openAI_key
94
+ completions = openai.Completion.create(
95
+ engine=engine,
96
+ prompt=prompt,
97
+ max_tokens=512,
98
+ n=1,
99
+ stop=None,
100
+ temperature=0.7,
101
+ )
102
+ message = completions.choices[0].text
103
+ return message
104
+
105
+ def generate_answer(question,openAI_key):
106
+ topn_chunks = recommender(question)
107
+ prompt = ""
108
+ prompt += 'search results:\n\n'
109
+ for c in topn_chunks:
110
+ prompt += c + '\n\n'
111
+
112
+ prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
113
+ "Cite each reference using [ Page Number] notation (every result has this number at the beginning). "\
114
+ "Citation should be done at the end of each sentence. If the search results mention multiple subjects "\
115
+ "with the same name, create separate answers for each. Only include information found in the results and "\
116
+ "don't add any additional information. Make sure the answer is correct and don't output false content. "\
117
+ "If the text does not relate to the query, simply state 'Text Not Found in PDF'. Ignore outlier "\
118
+ "search results which has nothing to do with the question. Only answer what is asked. The "\
119
+ "answer should be short and concise. Answer step-by-step. \n\nQuery: {question}\nAnswer: "
120
+
121
+ prompt += f"Query: {question}\nAnswer:"
122
+ answer = generate_text(openAI_key, prompt,"text-davinci-003")
123
+ return answer
124
+
125
+ def question_answer(url, file, question,openAI_key):
126
+ if openAI_key.strip()=='':
127
+ return '[ERROR]: Please enter you Open AI Key. Get your key here : https://platform.openai.com/account/api-keys'
128
+ if url.strip() == '' and file == None:
129
+ return '[ERROR]: Both URL and PDF is empty. Provide atleast one.'
130
+
131
+ if url.strip() != '' and file != None:
132
+ return '[ERROR]: Both URL and PDF is provided. Please provide only one (eiter URL or PDF).'
133
+
134
+ if url.strip() != '':
135
+ glob_url = url
136
+ download_pdf(glob_url, 'corpus.pdf')
137
+ load_recommender('corpus.pdf')
138
+
139
+ else:
140
+ old_file_name = file.name
141
+ file_name = file.name
142
+ file_name = file_name[:-12] + file_name[-4:]
143
+ os.rename(old_file_name, file_name)
144
+ load_recommender(file_name)
145
+
146
+ if question.strip() == '':
147
+ return '[ERROR]: Question field is empty'
148
+
149
+ return generate_answer(question,openAI_key)
150
+
151
+ recommender = SemanticSearch()
152
+
153
+ title = 'PDF GPT'
154
+ 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. Thequote("def load_recommender(path, start_page=1):", "return generate_answer(question,openAI_key)")