ledetele commited on
Commit
b6b066a
·
0 Parent(s):

Duplicate from ledetele/krystalOTP

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