JohnTan38 commited on
Commit
c0922b2
1 Parent(s): a7893b8

Upload 5 files

Browse files
Files changed (5) hide show
  1. Dockerfile +17 -0
  2. api.py +177 -0
  3. app.py +94 -0
  4. docker-compose.yaml +15 -0
  5. requirements.txt +8 -0
Dockerfile ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.8-slim-buster as langchain-serve-img
2
+
3
+ RUN pip3 install langchain-serve
4
+ RUN pip3 install api
5
+
6
+ CMD [ "lc-serve", "deploy", "local", "api" ]
7
+
8
+ FROM python:3.8-slim-buster as pdf-gpt-img
9
+
10
+ WORKDIR /app
11
+
12
+ COPY requirements.txt requirements.txt
13
+ RUN pip3 install -r requirements.txt
14
+
15
+ COPY . .
16
+
17
+ CMD [ "python3", "app.py" ]
api.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import shutil
4
+ import urllib.request
5
+ from pathlib import Path
6
+ from tempfile import NamedTemporaryFile
7
+
8
+ import fitz
9
+ import numpy as np
10
+ import openai
11
+ import tensorflow_hub as hub
12
+ from fastapi import UploadFile
13
+ from lcserve import serving
14
+ from sklearn.neighbors import NearestNeighbors
15
+
16
+
17
+ recommender = None
18
+
19
+
20
+ def download_pdf(url, output_path):
21
+ urllib.request.urlretrieve(url, output_path)
22
+
23
+
24
+ def preprocess(text):
25
+ text = text.replace('\n', ' ')
26
+ text = re.sub('\s+', ' ', text)
27
+ return text
28
+
29
+
30
+ def pdf_to_text(path, start_page=1, end_page=None):
31
+ doc = fitz.open(path)
32
+ total_pages = doc.page_count
33
+
34
+ if end_page is None:
35
+ end_page = total_pages
36
+
37
+ text_list = []
38
+
39
+ for i in range(start_page - 1, end_page):
40
+ text = doc.load_page(i).get_text("text")
41
+ text = preprocess(text)
42
+ text_list.append(text)
43
+
44
+ doc.close()
45
+ return text_list
46
+
47
+
48
+ def text_to_chunks(texts, word_length=150, start_page=1):
49
+ text_toks = [t.split(' ') for t in texts]
50
+ chunks = []
51
+
52
+ for idx, words in enumerate(text_toks):
53
+ for i in range(0, len(words), word_length):
54
+ chunk = words[i : i + word_length]
55
+ if (
56
+ (i + word_length) > len(words)
57
+ and (len(chunk) < word_length)
58
+ and (len(text_toks) != (idx + 1))
59
+ ):
60
+ text_toks[idx + 1] = chunk + text_toks[idx + 1]
61
+ continue
62
+ chunk = ' '.join(chunk).strip()
63
+ chunk = f'[Page no. {idx+start_page}]' + ' ' + '"' + chunk + '"'
64
+ chunks.append(chunk)
65
+ return chunks
66
+
67
+
68
+ class SemanticSearch:
69
+ def __init__(self):
70
+ self.use = hub.load('https://tfhub.dev/google/universal-sentence-encoder/4')
71
+ self.fitted = False
72
+
73
+ def fit(self, data, batch=1000, n_neighbors=5):
74
+ self.data = data
75
+ self.embeddings = self.get_text_embedding(data, batch=batch)
76
+ n_neighbors = min(n_neighbors, len(self.embeddings))
77
+ self.nn = NearestNeighbors(n_neighbors=n_neighbors)
78
+ self.nn.fit(self.embeddings)
79
+ self.fitted = True
80
+
81
+ def __call__(self, text, return_data=True):
82
+ inp_emb = self.use([text])
83
+ neighbors = self.nn.kneighbors(inp_emb, return_distance=False)[0]
84
+
85
+ if return_data:
86
+ return [self.data[i] for i in neighbors]
87
+ else:
88
+ return neighbors
89
+
90
+ def get_text_embedding(self, texts, batch=1000):
91
+ embeddings = []
92
+ for i in range(0, len(texts), batch):
93
+ text_batch = texts[i : (i + batch)]
94
+ emb_batch = self.use(text_batch)
95
+ embeddings.append(emb_batch)
96
+ embeddings = np.vstack(embeddings)
97
+ return embeddings
98
+
99
+
100
+ def load_recommender(path, start_page=1):
101
+ global recommender
102
+ if recommender is None:
103
+ recommender = SemanticSearch()
104
+
105
+ texts = pdf_to_text(path, start_page=start_page)
106
+ chunks = text_to_chunks(texts, start_page=start_page)
107
+ recommender.fit(chunks)
108
+ return 'Corpus Loaded.'
109
+
110
+
111
+ def generate_text(openAI_key, prompt, engine="text-davinci-003"):
112
+ openai.api_key = openAI_key
113
+ try:
114
+ completions = openai.Completion.create(
115
+ engine=engine,
116
+ prompt=prompt,
117
+ max_tokens=512,
118
+ n=1,
119
+ stop=None,
120
+ temperature=0.7,
121
+ )
122
+ message = completions.choices[0].text
123
+ except Exception as e:
124
+ message = f'API Error: {str(e)}'
125
+ return message
126
+
127
+
128
+ def generate_answer(question, openAI_key):
129
+ topn_chunks = recommender(question)
130
+ prompt = ""
131
+ prompt += 'search results:\n\n'
132
+ for c in topn_chunks:
133
+ prompt += c + '\n\n'
134
+
135
+ prompt += (
136
+ "Instructions: Compose a comprehensive reply to the query using the search results given. "
137
+ "Cite each reference using [ Page Number] notation (every result has this number at the beginning). "
138
+ "Citation should be done at the end of each sentence. If the search results mention multiple subjects "
139
+ "with the same name, create separate answers for each. Only include information found in the results and "
140
+ "don't add any additional information. Make sure the answer is correct and don't output false content. "
141
+ "If the text does not relate to the query, simply state 'Text Not Found in PDF'. Ignore outlier "
142
+ "search results which has nothing to do with the question. Only answer what is asked. The "
143
+ "answer should be short and concise. Answer step-by-step. \n\nQuery: {question}\nAnswer: "
144
+ )
145
+
146
+ prompt += f"Query: {question}\nAnswer:"
147
+ answer = generate_text(openAI_key, prompt, "text-davinci-003")
148
+ return answer
149
+
150
+
151
+ def load_openai_key() -> str:
152
+ key = os.environ.get("OPENAI_API_KEY")
153
+ if key is None:
154
+ raise ValueError(
155
+ "[ERROR]: Please pass your OPENAI_API_KEY. Get your key here : https://platform.openai.com/account/api-keys"
156
+ )
157
+ return key
158
+
159
+
160
+ @serving
161
+ def ask_url(url: str, question: str):
162
+ download_pdf(url, 'corpus.pdf')
163
+ load_recommender('corpus.pdf')
164
+ openAI_key = load_openai_key()
165
+ return generate_answer(question, openAI_key)
166
+
167
+
168
+ @serving
169
+ async def ask_file(file: UploadFile, question: str) -> str:
170
+ suffix = Path(file.filename).suffix
171
+ with NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
172
+ shutil.copyfileobj(file.file, tmp)
173
+ tmp_path = Path(tmp.name)
174
+
175
+ load_recommender(str(tmp_path))
176
+ openAI_key = load_openai_key()
177
+ return generate_answer(question, openAI_key)
app.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from tempfile import _TemporaryFileWrapper
3
+
4
+ import gradio as gr
5
+ import requests
6
+
7
+
8
+ def ask_api(
9
+ lcserve_host: str,
10
+ url: str,
11
+ file: _TemporaryFileWrapper,
12
+ question: str,
13
+ openAI_key: str,
14
+ ) -> str:
15
+ if not lcserve_host.startswith('http'):
16
+ return '[ERROR]: Invalid API Host'
17
+
18
+ if url.strip() == '' and file == None:
19
+ return '[ERROR]: Both URL and PDF is empty. Provide at least one.'
20
+
21
+ if url.strip() != '' and file != None:
22
+ return '[ERROR]: Both URL and PDF is provided. Please provide only one (either URL or PDF).'
23
+
24
+ if question.strip() == '':
25
+ return '[ERROR]: Question field is empty'
26
+
27
+ _data = {
28
+ 'question': question,
29
+ 'envs': {
30
+ 'OPENAI_API_KEY': openAI_key,
31
+ },
32
+ }
33
+
34
+ if url.strip() != '':
35
+ r = requests.post(
36
+ f'{lcserve_host}/ask_url',
37
+ json={'url': url, **_data},
38
+ )
39
+
40
+ else:
41
+ with open(file.name, 'rb') as f:
42
+ r = requests.post(
43
+ f'{lcserve_host}/ask_file',
44
+ params={'input_data': json.dumps(_data)},
45
+ files={'file': f},
46
+ )
47
+
48
+ if r.status_code != 200:
49
+ raise ValueError(f'[ERROR]: {r.text}')
50
+
51
+ return r.json()['result']
52
+
53
+
54
+ title = 'PDF GPT'
55
+ 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."""
56
+
57
+ with gr.Blocks() as demo:
58
+ gr.Markdown(f'<center><h1>{title}</h1></center>')
59
+ gr.Markdown(description)
60
+
61
+ with gr.Row():
62
+ with gr.Group():
63
+ lcserve_host = gr.Textbox(
64
+ label='Enter your API Host here',
65
+ value='http://localhost:8080',
66
+ placeholder='http://localhost:8080',
67
+ )
68
+ gr.Markdown(
69
+ '<p style="text-align:center">Get your Open AI API key <a href="https://platform.openai.com/account/api-keys">here</a></p>'
70
+ )
71
+ openAI_key = gr.Textbox(
72
+ label='Enter your OpenAI API key here', type='password'
73
+ )
74
+ pdf_url = gr.Textbox(label='Enter PDF URL here')
75
+ gr.Markdown("<center><h4>OR<h4></center>")
76
+ file = gr.File(
77
+ label='Upload your PDF/ Research Paper / Book here', file_types=['.pdf']
78
+ )
79
+ question = gr.Textbox(label='Enter your question here')
80
+ btn = gr.Button(value='Submit')
81
+ btn.style(full_width=True)
82
+
83
+ with gr.Group():
84
+ answer = gr.Textbox(label='The answer to your question is :')
85
+
86
+ btn.click(
87
+ ask_api,
88
+ inputs=[lcserve_host, pdf_url, file, question, openAI_key],
89
+ outputs=[answer],
90
+ )
91
+
92
+ demo.app.server.timeout = 60000 # Set the maximum return time for the results of accessing the upstream server
93
+
94
+ demo.launch(server_port=7860, enable_queue=True) # `enable_queue=True` to ensure the validity of multi-user requests
docker-compose.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3'
2
+
3
+ services:
4
+ langchain-serve:
5
+ build:
6
+ context: .
7
+ target: langchain-serve-img
8
+ ports:
9
+ - '8080:8080'
10
+ pdf-gpt:
11
+ build:
12
+ context: .
13
+ target: pdf-gpt-img
14
+ ports:
15
+ - '7860:7860'
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ PyMuPDF==1.22.1
2
+ numpy==1.23.5
3
+ scikit-learn==1.2.2
4
+ tensorflow>=2.0.0
5
+ tensorflow_hub==0.13.0
6
+ openai==0.27.4
7
+ gradio==3.34.0
8
+ langchain-serve>=0.0.19