Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,6 +1,5 @@
|
|
1 |
import gradio as gr
|
2 |
import os
|
3 |
-
|
4 |
from langchain_community.document_loaders import PyPDFLoader
|
5 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
6 |
from langchain_community.vectorstores import Chroma
|
@@ -9,154 +8,77 @@ from langchain_community.embeddings import HuggingFaceEmbeddings
|
|
9 |
from langchain_community.llms import HuggingFacePipeline
|
10 |
from langchain.chains import ConversationChain
|
11 |
from langchain.memory import ConversationBufferMemory
|
12 |
-
from langchain_community.llms import HuggingFaceEndpoint
|
13 |
import spaces
|
14 |
from pathlib import Path
|
15 |
import chromadb
|
16 |
from unidecode import unidecode
|
17 |
|
18 |
-
from transformers import AutoTokenizer
|
19 |
import transformers
|
20 |
import torch
|
21 |
-
import tqdm
|
22 |
-
import accelerate
|
23 |
import re
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
"
|
30 |
-
"
|
31 |
-
|
32 |
-
"TinyLlama/TinyLlama-1.1B-Chat-v1.0", "mosaicml/mpt-7b-instruct", "tiiuae/falcon-7b-instruct", \
|
33 |
-
"google/flan-t5-xxl"
|
34 |
]
|
35 |
list_llm_simple = [os.path.basename(llm) for llm in list_llm]
|
36 |
|
37 |
@spaces.GPU
|
38 |
-
# Load PDF document and create doc splits
|
39 |
def load_doc(list_file_path, chunk_size, chunk_overlap):
|
40 |
-
# Processing for one document only
|
41 |
-
# loader = PyPDFLoader(file_path)
|
42 |
-
# pages = loader.load()
|
43 |
loaders = [PyPDFLoader(x) for x in list_file_path]
|
44 |
pages = []
|
45 |
for loader in loaders:
|
46 |
pages.extend(loader.load())
|
47 |
-
# text_splitter = RecursiveCharacterTextSplitter(chunk_size = 600, chunk_overlap = 50)
|
48 |
text_splitter = RecursiveCharacterTextSplitter(
|
49 |
-
chunk_size
|
50 |
-
chunk_overlap
|
|
|
51 |
doc_splits = text_splitter.split_documents(pages)
|
52 |
return doc_splits
|
53 |
|
54 |
-
|
55 |
-
# Create vector database
|
56 |
def create_db(splits, collection_name):
|
57 |
-
embedding = HuggingFaceEmbeddings()
|
58 |
new_client = chromadb.EphemeralClient()
|
59 |
vectordb = Chroma.from_documents(
|
60 |
documents=splits,
|
61 |
embedding=embedding,
|
62 |
client=new_client,
|
63 |
-
collection_name=collection_name
|
64 |
-
# persist_directory=default_persist_directory
|
65 |
)
|
66 |
return vectordb
|
67 |
|
68 |
-
|
69 |
-
# Load vector database
|
70 |
-
def load_db():
|
71 |
-
embedding = HuggingFaceEmbeddings()
|
72 |
-
vectordb = Chroma(
|
73 |
-
# persist_directory=default_persist_directory,
|
74 |
-
embedding_function=embedding)
|
75 |
-
return vectordb
|
76 |
-
|
77 |
-
|
78 |
-
# Initialize langchain LLM chain
|
79 |
def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
80 |
progress(0.1, desc="Initializing HF tokenizer...")
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
# device_map="auto",
|
92 |
-
# # max_length=1024,
|
93 |
-
# max_new_tokens=max_tokens,
|
94 |
-
# do_sample=True,
|
95 |
-
# top_k=top_k,
|
96 |
-
# num_return_sequences=1,
|
97 |
-
# eos_token_id=tokenizer.eos_token_id
|
98 |
-
# )
|
99 |
-
# llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature': temperature})
|
100 |
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
elif llm_model in ["HuggingFaceH4/zephyr-7b-gemma-v0.1","mosaicml/mpt-7b-instruct"]:
|
116 |
-
raise gr.Error("LLM model is too large to be loaded automatically on free inference endpoint")
|
117 |
-
llm = HuggingFaceEndpoint(
|
118 |
-
repo_id=llm_model,
|
119 |
-
temperature = temperature,
|
120 |
-
max_new_tokens = max_tokens,
|
121 |
-
top_k = top_k,
|
122 |
-
)
|
123 |
-
elif llm_model == "microsoft/phi-2":
|
124 |
-
# raise gr.Error("phi-2 model requires 'trust_remote_code=True', currently not supported by langchain HuggingFaceHub...")
|
125 |
-
llm = HuggingFaceEndpoint(
|
126 |
-
repo_id=llm_model,
|
127 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
|
128 |
-
temperature = temperature,
|
129 |
-
max_new_tokens = max_tokens,
|
130 |
-
top_k = top_k,
|
131 |
-
trust_remote_code = True,
|
132 |
-
torch_dtype = "auto",
|
133 |
-
)
|
134 |
-
elif llm_model == "TinyLlama/TinyLlama-1.1B-Chat-v1.0":
|
135 |
-
llm = HuggingFaceEndpoint(
|
136 |
-
repo_id=llm_model,
|
137 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": 250, "top_k": top_k}
|
138 |
-
temperature = temperature,
|
139 |
-
max_new_tokens = 250,
|
140 |
-
top_k = top_k,
|
141 |
-
)
|
142 |
-
elif llm_model == "meta-llama/Llama-2-7b-chat-hf":
|
143 |
-
raise gr.Error("Llama-2-7b-chat-hf model requires a Pro subscription...")
|
144 |
-
llm = HuggingFaceEndpoint(
|
145 |
-
repo_id=llm_model,
|
146 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
|
147 |
-
temperature = temperature,
|
148 |
-
max_new_tokens = max_tokens,
|
149 |
-
top_k = top_k,
|
150 |
-
)
|
151 |
-
else:
|
152 |
-
llm = HuggingFaceEndpoint(
|
153 |
-
repo_id=llm_model,
|
154 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
|
155 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
|
156 |
-
temperature = temperature,
|
157 |
-
max_new_tokens = max_tokens,
|
158 |
-
top_k = top_k,
|
159 |
-
)
|
160 |
|
161 |
progress(0.75, desc="Defining buffer memory...")
|
162 |
memory = ConversationBufferMemory(
|
@@ -164,90 +86,58 @@ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, pr
|
|
164 |
output_key='answer',
|
165 |
return_messages=True
|
166 |
)
|
167 |
-
|
168 |
-
retriever=vector_db.as_retriever()
|
169 |
progress(0.8, desc="Defining retrieval chain...")
|
170 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
171 |
llm,
|
172 |
retriever=retriever,
|
173 |
chain_type="stuff",
|
174 |
memory=memory,
|
175 |
-
# combine_docs_chain_kwargs={"prompt": your_prompt})
|
176 |
return_source_documents=True,
|
177 |
-
#return_generated_question=False,
|
178 |
verbose=False,
|
179 |
)
|
180 |
progress(0.9, desc="Done!")
|
181 |
return qa_chain
|
182 |
|
183 |
-
|
184 |
-
# Generate collection name for vector database
|
185 |
-
# - Use filepath as input, ensuring unicode text
|
186 |
def create_collection_name(filepath):
|
187 |
-
# Extract filename without extension
|
188 |
collection_name = Path(filepath).stem
|
189 |
-
# Fix potential issues from naming convention
|
190 |
-
## Remove space
|
191 |
collection_name = collection_name.replace(" ","-")
|
192 |
-
## ASCII transliterations of Unicode text
|
193 |
collection_name = unidecode(collection_name)
|
194 |
-
## Remove special characters
|
195 |
-
#collection_name = re.findall("[\dA-Za-z]*", collection_name)[0]
|
196 |
collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
|
197 |
-
## Limit length to 50 characters
|
198 |
collection_name = collection_name[:50]
|
199 |
-
## Minimum length of 3 characters
|
200 |
if len(collection_name) < 3:
|
201 |
collection_name = collection_name + 'xyz'
|
202 |
-
## Enforce start and end as alphanumeric character
|
203 |
if not collection_name[0].isalnum():
|
204 |
collection_name = 'A' + collection_name[1:]
|
205 |
if not collection_name[-1].isalnum():
|
206 |
collection_name = collection_name[:-1] + 'Z'
|
207 |
-
print('Filepath: ', filepath)
|
208 |
-
print('Collection name: ', collection_name)
|
209 |
return collection_name
|
210 |
|
211 |
-
|
212 |
-
# Initialize database
|
213 |
def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
|
214 |
-
# Create list of documents (when valid)
|
215 |
list_file_path = [x.name for x in list_file_obj if x is not None]
|
216 |
-
# Create collection_name for vector database
|
217 |
progress(0.1, desc="Creating collection name...")
|
218 |
collection_name = create_collection_name(list_file_path[0])
|
219 |
progress(0.25, desc="Loading document...")
|
220 |
-
# Load document and create splits
|
221 |
doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
|
222 |
-
# Create or load vector database
|
223 |
progress(0.5, desc="Generating vector database...")
|
224 |
-
# global vector_db
|
225 |
vector_db = create_db(doc_splits, collection_name)
|
226 |
progress(0.9, desc="Done!")
|
227 |
return vector_db, collection_name, "Complete!"
|
228 |
|
229 |
-
|
230 |
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
231 |
-
# print("llm_option",llm_option)
|
232 |
llm_name = list_llm[llm_option]
|
233 |
-
print("llm_name: ",llm_name)
|
234 |
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
|
235 |
return qa_chain, "Complete!"
|
236 |
|
237 |
-
|
238 |
def format_chat_history(message, chat_history):
|
239 |
formatted_chat_history = []
|
240 |
for user_message, bot_message in chat_history:
|
241 |
formatted_chat_history.append(f"User: {user_message}")
|
242 |
formatted_chat_history.append(f"Assistant: {bot_message}")
|
243 |
return formatted_chat_history
|
244 |
-
|
245 |
|
246 |
def conversation(qa_chain, message, history):
|
247 |
formatted_chat_history = format_chat_history(message, history)
|
248 |
-
#print("formatted_chat_history",formatted_chat_history)
|
249 |
-
|
250 |
-
# Generate response using QA chain
|
251 |
response = qa_chain({"question": message, "chat_history": formatted_chat_history})
|
252 |
response_answer = response["answer"]
|
253 |
if response_answer.find("Helpful Answer:") != -1:
|
@@ -256,28 +146,12 @@ def conversation(qa_chain, message, history):
|
|
256 |
response_source1 = response_sources[0].page_content.strip()
|
257 |
response_source2 = response_sources[1].page_content.strip()
|
258 |
response_source3 = response_sources[2].page_content.strip()
|
259 |
-
# Langchain sources are zero-based
|
260 |
response_source1_page = response_sources[0].metadata["page"] + 1
|
261 |
response_source2_page = response_sources[1].metadata["page"] + 1
|
262 |
response_source3_page = response_sources[2].metadata["page"] + 1
|
263 |
-
# print ('chat response: ', response_answer)
|
264 |
-
# print('DB source', response_sources)
|
265 |
|
266 |
-
# Append user message and response to chat history
|
267 |
new_history = history + [(message, response_answer)]
|
268 |
-
# return gr.update(value=""), new_history, response_sources[0], response_sources[1]
|
269 |
return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
|
270 |
-
|
271 |
-
|
272 |
-
def upload_file(file_obj):
|
273 |
-
list_file_path = []
|
274 |
-
for idx, file in enumerate(file_obj):
|
275 |
-
file_path = file_obj.name
|
276 |
-
list_file_path.append(file_path)
|
277 |
-
# print(file_path)
|
278 |
-
# initialize_database(file_path, progress)
|
279 |
-
return list_file_path
|
280 |
-
|
281 |
|
282 |
def demo():
|
283 |
with gr.Blocks(theme="base") as demo:
|
@@ -286,94 +160,71 @@ def demo():
|
|
286 |
collection_name = gr.State()
|
287 |
|
288 |
gr.Markdown(
|
289 |
-
"""<center><h2>PDF-based
|
290 |
<h3>Ask any questions about your PDF documents</h3>""")
|
291 |
gr.Markdown(
|
292 |
-
"""<b>Note:</b> This AI assistant
|
293 |
-
|
294 |
-
|
295 |
-
<br><b>Warning:</b> This space uses the free CPU Basic hardware from Hugging Face. Some steps and LLM models used below (free inference endpoints) can take some time to generate a reply.
|
296 |
-
""")
|
297 |
|
298 |
with gr.Tab("Step 1 - Upload PDF"):
|
299 |
-
|
300 |
-
document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
|
301 |
-
# upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)
|
302 |
|
303 |
with gr.Tab("Step 2 - Process document"):
|
304 |
-
|
305 |
-
db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")
|
306 |
with gr.Accordion("Advanced options - Document text splitter", open=False):
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
with gr.Row():
|
312 |
-
db_progress = gr.Textbox(label="Vector database initialization", value="None")
|
313 |
-
with gr.Row():
|
314 |
-
db_btn = gr.Button("Generate vector database")
|
315 |
|
316 |
with gr.Tab("Step 3 - Initialize QA chain"):
|
317 |
-
|
318 |
-
llm_btn = gr.Radio(list_llm_simple, \
|
319 |
-
label="LLM models", value = list_llm_simple[0], type="index", info="Choose your LLM model")
|
320 |
with gr.Accordion("Advanced options - LLM model", open=False):
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
|
327 |
-
with gr.Row():
|
328 |
-
llm_progress = gr.Textbox(value="None",label="QA chain initialization")
|
329 |
-
with gr.Row():
|
330 |
-
qachain_btn = gr.Button("Initialize Question Answering chain")
|
331 |
|
332 |
with gr.Tab("Step 4 - Chatbot"):
|
333 |
chatbot = gr.Chatbot(height=300)
|
334 |
with gr.Accordion("Advanced - Document references", open=False):
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
with gr.Row():
|
345 |
-
msg = gr.Textbox(placeholder="Type message (e.g. 'What is this document about?')", container=True)
|
346 |
-
with gr.Row():
|
347 |
-
submit_btn = gr.Button("Submit message")
|
348 |
-
clear_btn = gr.ClearButton([msg, chatbot], value="Clear conversation")
|
349 |
|
350 |
# Preprocessing events
|
351 |
-
|
352 |
-
|
353 |
-
inputs=[document, slider_chunk_size, slider_chunk_overlap], \
|
354 |
outputs=[vector_db, collection_name, db_progress])
|
355 |
-
qachain_btn.click(initialize_LLM,
|
356 |
-
inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db],
|
357 |
-
outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0],
|
358 |
-
inputs=None,
|
359 |
-
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
360 |
queue=False)
|
361 |
|
362 |
# Chatbot events
|
363 |
-
msg.submit(conversation,
|
364 |
-
inputs=[qa_chain, msg, chatbot],
|
365 |
-
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
366 |
queue=False)
|
367 |
-
submit_btn.click(conversation,
|
368 |
-
inputs=[qa_chain, msg, chatbot],
|
369 |
-
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
370 |
queue=False)
|
371 |
-
clear_btn.click(lambda:[None,"",0,"",0,"",0],
|
372 |
-
inputs=None,
|
373 |
-
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
374 |
queue=False)
|
375 |
demo.queue().launch(debug=True)
|
376 |
|
377 |
-
|
378 |
if __name__ == "__main__":
|
379 |
-
demo()
|
|
|
1 |
import gradio as gr
|
2 |
import os
|
|
|
3 |
from langchain_community.document_loaders import PyPDFLoader
|
4 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
5 |
from langchain_community.vectorstores import Chroma
|
|
|
8 |
from langchain_community.llms import HuggingFacePipeline
|
9 |
from langchain.chains import ConversationChain
|
10 |
from langchain.memory import ConversationBufferMemory
|
|
|
11 |
import spaces
|
12 |
from pathlib import Path
|
13 |
import chromadb
|
14 |
from unidecode import unidecode
|
15 |
|
16 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
17 |
import transformers
|
18 |
import torch
|
|
|
|
|
19 |
import re
|
20 |
|
21 |
+
# List of models
|
22 |
+
list_llm = [
|
23 |
+
"mistralai/Mistral-7B-Instruct-v0.2",
|
24 |
+
"HuggingFaceH4/zephyr-7b-beta",
|
25 |
+
"microsoft/phi-2",
|
26 |
+
"TinyLlama/TinyLlama-1.1B-Chat-v1.0",
|
27 |
+
# Add more GPU-compatible models here
|
|
|
|
|
28 |
]
|
29 |
list_llm_simple = [os.path.basename(llm) for llm in list_llm]
|
30 |
|
31 |
@spaces.GPU
|
|
|
32 |
def load_doc(list_file_path, chunk_size, chunk_overlap):
|
|
|
|
|
|
|
33 |
loaders = [PyPDFLoader(x) for x in list_file_path]
|
34 |
pages = []
|
35 |
for loader in loaders:
|
36 |
pages.extend(loader.load())
|
|
|
37 |
text_splitter = RecursiveCharacterTextSplitter(
|
38 |
+
chunk_size=chunk_size,
|
39 |
+
chunk_overlap=chunk_overlap
|
40 |
+
)
|
41 |
doc_splits = text_splitter.split_documents(pages)
|
42 |
return doc_splits
|
43 |
|
|
|
|
|
44 |
def create_db(splits, collection_name):
|
45 |
+
embedding = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2", device="cuda")
|
46 |
new_client = chromadb.EphemeralClient()
|
47 |
vectordb = Chroma.from_documents(
|
48 |
documents=splits,
|
49 |
embedding=embedding,
|
50 |
client=new_client,
|
51 |
+
collection_name=collection_name
|
|
|
52 |
)
|
53 |
return vectordb
|
54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
56 |
progress(0.1, desc="Initializing HF tokenizer...")
|
57 |
+
tokenizer = AutoTokenizer.from_pretrained(llm_model)
|
58 |
+
|
59 |
+
progress(0.3, desc="Loading model...")
|
60 |
+
try:
|
61 |
+
model = AutoModelForCausalLM.from_pretrained(llm_model, torch_dtype=torch.float16, device_map="auto")
|
62 |
+
except RuntimeError as e:
|
63 |
+
if "CUDA out of memory" in str(e):
|
64 |
+
raise gr.Error("GPU memory exceeded. Try a smaller model or reduce batch size.")
|
65 |
+
else:
|
66 |
+
raise e
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
+
progress(0.5, desc="Initializing HF pipeline...")
|
69 |
+
pipeline = transformers.pipeline(
|
70 |
+
"text-generation",
|
71 |
+
model=model,
|
72 |
+
tokenizer=tokenizer,
|
73 |
+
torch_dtype=torch.float16,
|
74 |
+
device_map="auto",
|
75 |
+
max_new_tokens=max_tokens,
|
76 |
+
do_sample=True,
|
77 |
+
top_k=top_k,
|
78 |
+
num_return_sequences=1,
|
79 |
+
eos_token_id=tokenizer.eos_token_id
|
80 |
+
)
|
81 |
+
llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature': temperature})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
|
83 |
progress(0.75, desc="Defining buffer memory...")
|
84 |
memory = ConversationBufferMemory(
|
|
|
86 |
output_key='answer',
|
87 |
return_messages=True
|
88 |
)
|
89 |
+
retriever = vector_db.as_retriever()
|
|
|
90 |
progress(0.8, desc="Defining retrieval chain...")
|
91 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
92 |
llm,
|
93 |
retriever=retriever,
|
94 |
chain_type="stuff",
|
95 |
memory=memory,
|
|
|
96 |
return_source_documents=True,
|
|
|
97 |
verbose=False,
|
98 |
)
|
99 |
progress(0.9, desc="Done!")
|
100 |
return qa_chain
|
101 |
|
|
|
|
|
|
|
102 |
def create_collection_name(filepath):
|
|
|
103 |
collection_name = Path(filepath).stem
|
|
|
|
|
104 |
collection_name = collection_name.replace(" ","-")
|
|
|
105 |
collection_name = unidecode(collection_name)
|
|
|
|
|
106 |
collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
|
|
|
107 |
collection_name = collection_name[:50]
|
|
|
108 |
if len(collection_name) < 3:
|
109 |
collection_name = collection_name + 'xyz'
|
|
|
110 |
if not collection_name[0].isalnum():
|
111 |
collection_name = 'A' + collection_name[1:]
|
112 |
if not collection_name[-1].isalnum():
|
113 |
collection_name = collection_name[:-1] + 'Z'
|
|
|
|
|
114 |
return collection_name
|
115 |
|
|
|
|
|
116 |
def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
|
|
|
117 |
list_file_path = [x.name for x in list_file_obj if x is not None]
|
|
|
118 |
progress(0.1, desc="Creating collection name...")
|
119 |
collection_name = create_collection_name(list_file_path[0])
|
120 |
progress(0.25, desc="Loading document...")
|
|
|
121 |
doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
|
|
|
122 |
progress(0.5, desc="Generating vector database...")
|
|
|
123 |
vector_db = create_db(doc_splits, collection_name)
|
124 |
progress(0.9, desc="Done!")
|
125 |
return vector_db, collection_name, "Complete!"
|
126 |
|
|
|
127 |
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
|
|
128 |
llm_name = list_llm[llm_option]
|
|
|
129 |
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
|
130 |
return qa_chain, "Complete!"
|
131 |
|
|
|
132 |
def format_chat_history(message, chat_history):
|
133 |
formatted_chat_history = []
|
134 |
for user_message, bot_message in chat_history:
|
135 |
formatted_chat_history.append(f"User: {user_message}")
|
136 |
formatted_chat_history.append(f"Assistant: {bot_message}")
|
137 |
return formatted_chat_history
|
|
|
138 |
|
139 |
def conversation(qa_chain, message, history):
|
140 |
formatted_chat_history = format_chat_history(message, history)
|
|
|
|
|
|
|
141 |
response = qa_chain({"question": message, "chat_history": formatted_chat_history})
|
142 |
response_answer = response["answer"]
|
143 |
if response_answer.find("Helpful Answer:") != -1:
|
|
|
146 |
response_source1 = response_sources[0].page_content.strip()
|
147 |
response_source2 = response_sources[1].page_content.strip()
|
148 |
response_source3 = response_sources[2].page_content.strip()
|
|
|
149 |
response_source1_page = response_sources[0].metadata["page"] + 1
|
150 |
response_source2_page = response_sources[1].metadata["page"] + 1
|
151 |
response_source3_page = response_sources[2].metadata["page"] + 1
|
|
|
|
|
152 |
|
|
|
153 |
new_history = history + [(message, response_answer)]
|
|
|
154 |
return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
155 |
|
156 |
def demo():
|
157 |
with gr.Blocks(theme="base") as demo:
|
|
|
160 |
collection_name = gr.State()
|
161 |
|
162 |
gr.Markdown(
|
163 |
+
"""<center><h2>GPU-Accelerated PDF-based Chatbot</center></h2>
|
164 |
<h3>Ask any questions about your PDF documents</h3>""")
|
165 |
gr.Markdown(
|
166 |
+
"""<b>Note:</b> This AI assistant uses GPU acceleration for faster processing.
|
167 |
+
It performs retrieval-augmented generation (RAG) from your PDF documents using Langchain and open-source LLMs.
|
168 |
+
The chatbot takes past questions into account and includes document references.""")
|
|
|
|
|
169 |
|
170 |
with gr.Tab("Step 1 - Upload PDF"):
|
171 |
+
document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
|
|
|
|
|
172 |
|
173 |
with gr.Tab("Step 2 - Process document"):
|
174 |
+
db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")
|
|
|
175 |
with gr.Accordion("Advanced options - Document text splitter", open=False):
|
176 |
+
slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)
|
177 |
+
slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
|
178 |
+
db_progress = gr.Textbox(label="Vector database initialization", value="None")
|
179 |
+
db_btn = gr.Button("Generate vector database")
|
|
|
|
|
|
|
|
|
180 |
|
181 |
with gr.Tab("Step 3 - Initialize QA chain"):
|
182 |
+
llm_btn = gr.Radio(list_llm_simple, label="LLM models", value = list_llm_simple[0], type="index", info="Choose your LLM model")
|
|
|
|
|
183 |
with gr.Accordion("Advanced options - LLM model", open=False):
|
184 |
+
slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
|
185 |
+
slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
|
186 |
+
slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
|
187 |
+
llm_progress = gr.Textbox(value="None",label="QA chain initialization")
|
188 |
+
qachain_btn = gr.Button("Initialize Question Answering chain")
|
|
|
|
|
|
|
|
|
|
|
189 |
|
190 |
with gr.Tab("Step 4 - Chatbot"):
|
191 |
chatbot = gr.Chatbot(height=300)
|
192 |
with gr.Accordion("Advanced - Document references", open=False):
|
193 |
+
doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
|
194 |
+
source1_page = gr.Number(label="Page", scale=1)
|
195 |
+
doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
|
196 |
+
source2_page = gr.Number(label="Page", scale=1)
|
197 |
+
doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
|
198 |
+
source3_page = gr.Number(label="Page", scale=1)
|
199 |
+
msg = gr.Textbox(placeholder="Type message (e.g. 'What is this document about?')", container=True)
|
200 |
+
submit_btn = gr.Button("Submit message")
|
201 |
+
clear_btn = gr.ClearButton([msg, chatbot], value="Clear conversation")
|
|
|
|
|
|
|
|
|
|
|
202 |
|
203 |
# Preprocessing events
|
204 |
+
db_btn.click(initialize_database,
|
205 |
+
inputs=[document, slider_chunk_size, slider_chunk_overlap],
|
|
|
206 |
outputs=[vector_db, collection_name, db_progress])
|
207 |
+
qachain_btn.click(initialize_LLM,
|
208 |
+
inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db],
|
209 |
+
outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0],
|
210 |
+
inputs=None,
|
211 |
+
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
212 |
queue=False)
|
213 |
|
214 |
# Chatbot events
|
215 |
+
msg.submit(conversation,
|
216 |
+
inputs=[qa_chain, msg, chatbot],
|
217 |
+
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
218 |
queue=False)
|
219 |
+
submit_btn.click(conversation,
|
220 |
+
inputs=[qa_chain, msg, chatbot],
|
221 |
+
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
222 |
queue=False)
|
223 |
+
clear_btn.click(lambda:[None,"",0,"",0,"",0],
|
224 |
+
inputs=None,
|
225 |
+
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
226 |
queue=False)
|
227 |
demo.queue().launch(debug=True)
|
228 |
|
|
|
229 |
if __name__ == "__main__":
|
230 |
+
demo()
|