Amjadd pritish commited on
Commit
9d2b666
·
0 Parent(s):

Duplicate from pritish/BookGPT

Browse files

Co-authored-by: Pritish Mishra <pritish@users.noreply.huggingface.co>

Files changed (4) hide show
  1. .gitattributes +34 -0
  2. README.md +13 -0
  3. app.py +190 -0
  4. requirements.txt +5 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: BookGPT
3
+ emoji: 😻
4
+ colorFrom: indigo
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 3.16.2
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: pritish/BookGPT
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
12
+ def download_pdf(url, output_path):
13
+ urllib.request.urlretrieve(url, output_path)
14
+
15
+
16
+ def preprocess(text):
17
+ text = text.replace('\n', ' ')
18
+ text = re.sub('\s+', ' ', text)
19
+ return text
20
+
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
+
40
+ def text_to_chunks(texts, word_length=150, start_page=1):
41
+ text_toks = [t.split(' ') for t in texts]
42
+ page_nums = []
43
+ chunks = []
44
+
45
+ for idx, words in enumerate(text_toks):
46
+ for i in range(0, len(words), word_length):
47
+ chunk = words[i:i+word_length]
48
+ if (i+word_length) > len(words) and (len(chunk) < word_length) and (
49
+ len(text_toks) != (idx+1)):
50
+ text_toks[idx+1] = chunk + text_toks[idx+1]
51
+ continue
52
+ chunk = ' '.join(chunk).strip()
53
+ chunk = f'[{idx+start_page}]' + ' ' + '"' + chunk + '"'
54
+ chunks.append(chunk)
55
+ return chunks
56
+
57
+
58
+ class SemanticSearch:
59
+
60
+ def __init__(self):
61
+ self.use = hub.load('https://tfhub.dev/google/universal-sentence-encoder/4')
62
+ self.fitted = False
63
+
64
+
65
+ def fit(self, data, batch=1000, n_neighbors=5):
66
+ self.data = data
67
+ self.embeddings = self.get_text_embedding(data, batch=batch)
68
+ n_neighbors = min(n_neighbors, len(self.embeddings))
69
+ self.nn = NearestNeighbors(n_neighbors=n_neighbors)
70
+ self.nn.fit(self.embeddings)
71
+ self.fitted = True
72
+
73
+
74
+ def __call__(self, text, return_data=True):
75
+ inp_emb = self.use([text])
76
+ neighbors = self.nn.kneighbors(inp_emb, return_distance=False)[0]
77
+
78
+ if return_data:
79
+ return [self.data[i] for i in neighbors]
80
+ else:
81
+ return neighbors
82
+
83
+
84
+ def get_text_embedding(self, texts, batch=1000):
85
+ embeddings = []
86
+ for i in range(0, len(texts), batch):
87
+ text_batch = texts[i:(i+batch)]
88
+ emb_batch = self.use(text_batch)
89
+ embeddings.append(emb_batch)
90
+ embeddings = np.vstack(embeddings)
91
+ return embeddings
92
+
93
+
94
+ recommender = SemanticSearch()
95
+
96
+ def load_recommender(path, start_page=1):
97
+ global recommender
98
+ texts = pdf_to_text(path, start_page=start_page)
99
+ chunks = text_to_chunks(texts, start_page=start_page)
100
+ recommender.fit(chunks)
101
+ return 'Corpus Loaded.'
102
+
103
+
104
+ def generate_text(prompt, engine="text-davinci-003"):
105
+ completions = openai.Completion.create(
106
+ engine=engine,
107
+ prompt=prompt,
108
+ max_tokens=512,
109
+ n=1,
110
+ stop=None,
111
+ temperature=0.7,
112
+ )
113
+ message = completions.choices[0].text
114
+ return message
115
+
116
+
117
+ def generate_answer(question):
118
+ topn_chunks = recommender(question)
119
+ prompt = ""
120
+ prompt += 'search results:\n\n'
121
+ for c in topn_chunks:
122
+ prompt += c + '\n\n'
123
+
124
+ prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
125
+ "Cite each reference using [number] notation (every result has this number at the beginning). "\
126
+ "Citation should be done at the end of each sentence. If the search results mention multiple subjects "\
127
+ "with the same name, create separate answers for each. Only include information found in the results and "\
128
+ "don't add any additional information. Make sure the answer is correct and don't output false content. "\
129
+ "If the text does not relate to the query, simply state 'Found Nothing'. Ignore outlier "\
130
+ "search results which has nothing to do with the question. Only answer what is asked. The "\
131
+ "answer should be short and concise.\n\nQuery: {question}\nAnswer: "
132
+
133
+ prompt += f"Query: {question}\nAnswer:"
134
+ answer = generate_text(prompt)
135
+ return answer
136
+
137
+
138
+ def question_answer(url, file, question, api_key):
139
+ openai.api_key = api_key
140
+
141
+ if url.strip() == '' and file == None:
142
+ return '[ERROR]: Both URL and PDF is empty. Provide atleast one.'
143
+
144
+ if url.strip() != '' and file != None:
145
+ return '[ERROR]: Both URL and PDF is provided. Please provide only one (eiter URL or PDF).'
146
+
147
+ if url.strip() != '':
148
+ glob_url = url
149
+ download_pdf(glob_url, 'corpus.pdf')
150
+ load_recommender('corpus.pdf')
151
+
152
+ else:
153
+ old_file_name = file.name
154
+ file_name = file.name
155
+ file_name = file_name[:-12] + file_name[-4:]
156
+ os.rename(old_file_name, file_name)
157
+ load_recommender(file_name)
158
+
159
+ if question.strip() == '':
160
+ return '[ERROR]: Question field is empty'
161
+
162
+ return generate_answer(question)
163
+
164
+
165
+ title = 'BookGPT'
166
+ description = "BookGPT allows you to input an entire book and ask questions about its contents. This app uses GPT-3 to generate answers based on the book's information. BookGPT has ability to add reference to the specific page number from where the information was found. This adds credibility to the answers generated also helps you locate the relevant information in the book."
167
+
168
+ with gr.Blocks() as demo:
169
+
170
+ gr.Markdown(f'<center><h1>{title}</h1></center>')
171
+ gr.Markdown(description)
172
+ gr.Markdown("Thank you for all the support this space has received! Unfortunately, my OpenAI $18 grant has been exhausted, so you'll need to enter your own OpenAI API Key to use the app. Sorry for inconvenience :-(.")
173
+
174
+ with gr.Row():
175
+
176
+ with gr.Group():
177
+ url = gr.Textbox(label='URL')
178
+ gr.Markdown("<center><h6>or<h6></center>")
179
+ file = gr.File(label='PDF', file_types=['.pdf'])
180
+ question = gr.Textbox(label='question')
181
+ api_key = gr.Textbox(label='OpenAI API Key')
182
+ btn = gr.Button(value='Submit')
183
+ btn.style(full_width=True)
184
+
185
+ with gr.Group():
186
+ answer = gr.Textbox(label='answer')
187
+
188
+ btn.click(question_answer, inputs=[url, file, question, api_key], outputs=[answer])
189
+
190
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ PyMuPDF
2
+ openai
3
+ tensorflow==2.9.2
4
+ tensorflow-hub==0.12.0
5
+ scikit-learn==1.0.2