ELEVEN-001 commited on
Commit
8cf0eef
·
1 Parent(s): 8eb03a6

Upload 4 files

Browse files
Files changed (3) hide show
  1. README.md +6 -5
  2. app.py +197 -0
  3. requirements.txt +6 -0
README.md CHANGED
@@ -1,12 +1,13 @@
1
  ---
2
- title: ChatToFiles
3
- emoji: 🏆
4
- colorFrom: purple
5
- colorTo: red
6
  sdk: gradio
7
- sdk_version: 3.28.2
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: PdfChatter
3
+ emoji: 🏢
4
+ colorFrom: indigo
5
+ colorTo: green
6
  sdk: gradio
7
+ sdk_version: 3.20.1
8
  app_file: app.py
9
  pinned: false
10
+ license: afl-3.0
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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):
16
+ text = text.replace('\n', ' ')
17
+ text = re.sub('\s+', ' ', text)
18
+ return text
19
+
20
+
21
+ def pdf_to_text(path, start_page=1, end_page=None):
22
+ doc = fitz.open(path)
23
+ total_pages = doc.page_count
24
+
25
+ if end_page is None:
26
+ end_page = total_pages
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)
34
+
35
+ doc.close()
36
+ return text_list
37
+
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
+
58
+ def __init__(self):
59
+ self.use = hub.load('https://tfhub.dev/google/universal-sentence-encoder/4')
60
+ self.fitted = False
61
+
62
+
63
+ def fit(self, data, batch=1000, n_neighbors=5):
64
+ self.data = data
65
+ self.embeddings = self.get_text_embedding(data, batch=batch)
66
+ n_neighbors = min(n_neighbors, len(self.embeddings))
67
+ self.nn = NearestNeighbors(n_neighbors=n_neighbors)
68
+ self.nn.fit(self.embeddings)
69
+ self.fitted = True
70
+
71
+
72
+ def __call__(self, text, return_data=True):
73
+ inp_emb = self.use([text])
74
+ neighbors = self.nn.kneighbors(inp_emb, return_distance=False)[0]
75
+
76
+ if return_data:
77
+ return [self.data[i] for i in neighbors]
78
+ else:
79
+ return neighbors
80
+
81
+
82
+ def get_text_embedding(self, texts, batch=1000):
83
+ embeddings = []
84
+ for i in range(0, len(texts), batch):
85
+ text_batch = texts[i:(i+batch)]
86
+ emb_batch = self.use(text_batch)
87
+ embeddings.append(emb_batch)
88
+ embeddings = np.vstack(embeddings)
89
+ return embeddings
90
+
91
+
92
+
93
+ def load_recommender(path, start_page=1):
94
+ global recommender
95
+ texts = pdf_to_text(path, start_page=start_page)
96
+ chunks = text_to_chunks(texts, start_page=start_page)
97
+ recommender.fit(chunks)
98
+ return 'Corpus Loaded.'
99
+
100
+ def generate_text(openAI_key,prompt, engine="text-davinci-003"):
101
+ openai.api_key = openAI_key
102
+ completions = openai.Completion.create(
103
+ engine=engine,
104
+ prompt=prompt,
105
+ max_tokens=512,
106
+ n=1,
107
+ stop=None,
108
+ temperature=0.7,
109
+ )
110
+ message = completions.choices[0].text
111
+ return message
112
+
113
+ def generate_answer(question,openAI_key):
114
+ topn_chunks = recommender(question)
115
+ prompt = ""
116
+ prompt += 'search results:\n\n'
117
+ for c in topn_chunks:
118
+ prompt += c + '\n\n'
119
+
120
+ prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
121
+ "Cite each reference using [ Page Number] notation (every result has this number at the beginning). "\
122
+ "Citation should be done at the end of each sentence. If the search results mention multiple subjects "\
123
+ "with the same name, create separate answers for each. Only include information found in the results and "\
124
+ "don't add any additional information. Make sure the answer is correct and don't output false content. "\
125
+ "If the text does not relate to the query, simply state 'Text Not Found in PDF'. Ignore outlier "\
126
+ "search results which has nothing to do with the question. Only answer what is asked. The "\
127
+ "answer should be short and concise. Answer step-by-step. \n\nQuery: {question}\nAnswer: "\
128
+ "if you are asked to make questions from the pdf that you are provided with, kindly make it according to the question"
129
+
130
+ prompt += f"Query: {question}\nAnswer:"
131
+ answer = generate_text(openAI_key, prompt,"text-davinci-003")
132
+ return answer
133
+
134
+
135
+ def question_answer(url, file, question,openAI_key):
136
+ if openAI_key.strip()=='':
137
+ return '[ERROR]: Please enter you Open AI Key. Get your key here : https://platform.openai.com/account/api-keys'
138
+ if url.strip() == '' and file == None:
139
+ return '[ERROR]: Both URL and PDF is empty. Provide atleast one.'
140
+
141
+ if url.strip() != '' and file != None:
142
+ return '[ERROR]: Both URL and PDF is provided. Please provide only one (eiter URL or PDF).'
143
+
144
+ if url.strip() != '':
145
+ glob_url = url
146
+ download_pdf(glob_url, 'corpus.pdf')
147
+ load_recommender('corpus.pdf')
148
+
149
+ else:
150
+ old_file_name = file.name
151
+ file_name = file.name
152
+ file_name = file_name[:-12] + file_name[-4:]
153
+
154
+ # Rename the file
155
+ os.rename(old_file_name, file_name)
156
+ load_recommender(file_name)
157
+
158
+ # Delete the existing file if it exists
159
+ if os.path.exists(file_name):
160
+ os.remove(file_name)
161
+
162
+
163
+ if question.strip() == '':
164
+ return '[ERROR]: Question field is empty'
165
+
166
+ return generate_answer(question,openAI_key)
167
+
168
+
169
+ recommender = SemanticSearch()
170
+
171
+ title = 'PDF GPT'
172
+ 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."""
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='Enter your OpenAI API key here')
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()
197
+ #demo.launch(share=True)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ PyMuPDF
2
+ numpy==1.19.5
3
+ scikit-learn
4
+ tensorflow>=2.0.0
5
+ tensorflow-hub
6
+ openai==0.10.2