Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -22,7 +22,29 @@ import tqdm
|
|
22 |
import accelerate
|
23 |
import re
|
24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
# default_persist_directory = './chroma_HF/'
|
28 |
list_llm = ["mistralai/Mistral-7B-Instruct-v0.3", "mistralai/Mixtral-8x7B-Instruct-v0.1", "mistralai/Mistral-7B-Instruct-v0.1", \
|
@@ -36,21 +58,14 @@ list_llm_simple = [os.path.basename(llm) for llm in list_llm]
|
|
36 |
|
37 |
# Load PDF document and create doc splits
|
38 |
def load_doc(list_file_path, chunk_size, chunk_overlap):
|
39 |
-
# Processing for one document only
|
40 |
-
# loader = PyPDFLoader(file_path)
|
41 |
-
# pages = loader.load()
|
42 |
loaders = [PyPDFLoader(x) for x in list_file_path]
|
43 |
pages = []
|
44 |
for loader in loaders:
|
45 |
pages.extend(loader.load())
|
46 |
-
|
47 |
-
text_splitter = RecursiveCharacterTextSplitter(
|
48 |
-
chunk_size = chunk_size,
|
49 |
-
chunk_overlap = chunk_overlap)
|
50 |
doc_splits = text_splitter.split_documents(pages)
|
51 |
return doc_splits
|
52 |
|
53 |
-
|
54 |
# Create vector database
|
55 |
def create_db(splits, collection_name):
|
56 |
embedding = HuggingFaceEmbeddings()
|
@@ -60,52 +75,25 @@ def create_db(splits, collection_name):
|
|
60 |
embedding=embedding,
|
61 |
client=new_client,
|
62 |
collection_name=collection_name,
|
63 |
-
# persist_directory=default_persist_directory
|
64 |
)
|
65 |
return vectordb
|
66 |
|
67 |
-
|
68 |
# Load vector database
|
69 |
def load_db():
|
70 |
embedding = HuggingFaceEmbeddings()
|
71 |
vectordb = Chroma(
|
72 |
-
# persist_directory=default_persist_directory,
|
73 |
embedding_function=embedding)
|
74 |
return vectordb
|
75 |
|
76 |
-
|
77 |
# Initialize langchain LLM chain
|
78 |
def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
79 |
progress(0.1, desc="Initializing HF tokenizer...")
|
80 |
-
# HuggingFacePipeline uses local model
|
81 |
-
# Note: it will download model locally...
|
82 |
-
# tokenizer=AutoTokenizer.from_pretrained(llm_model)
|
83 |
-
# progress(0.5, desc="Initializing HF pipeline...")
|
84 |
-
# pipeline=transformers.pipeline(
|
85 |
-
# "text-generation",
|
86 |
-
# model=llm_model,
|
87 |
-
# tokenizer=tokenizer,
|
88 |
-
# torch_dtype=torch.bfloat16,
|
89 |
-
# trust_remote_code=True,
|
90 |
-
# device_map="auto",
|
91 |
-
# # max_length=1024,
|
92 |
-
# max_new_tokens=max_tokens,
|
93 |
-
# do_sample=True,
|
94 |
-
# top_k=top_k,
|
95 |
-
# num_return_sequences=1,
|
96 |
-
# eos_token_id=tokenizer.eos_token_id
|
97 |
-
# )
|
98 |
-
# llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature': temperature})
|
99 |
|
100 |
-
# HuggingFaceHub uses HF inference endpoints
|
101 |
progress(0.5, desc="Initializing HF Hub...")
|
102 |
-
|
103 |
-
# Warning: langchain issue
|
104 |
-
# URL: https://github.com/langchain-ai/langchain/issues/6080
|
105 |
if llm_model == "mistralai/Mixtral-8x7B-Instruct-v0.3":
|
106 |
llm = HuggingFaceEndpoint(
|
107 |
repo_id=llm_model,
|
108 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "load_in_8bit": True}
|
109 |
temperature = temperature,
|
110 |
max_new_tokens = max_tokens,
|
111 |
top_k = top_k,
|
@@ -120,10 +108,8 @@ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, pr
|
|
120 |
top_k = top_k,
|
121 |
)
|
122 |
elif llm_model == "microsoft/phi-2":
|
123 |
-
# raise gr.Error("phi-2 model requires 'trust_remote_code=True', currently not supported by langchain HuggingFaceHub...")
|
124 |
llm = HuggingFaceEndpoint(
|
125 |
repo_id=llm_model,
|
126 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
|
127 |
temperature = temperature,
|
128 |
max_new_tokens = max_tokens,
|
129 |
top_k = top_k,
|
@@ -133,7 +119,6 @@ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, pr
|
|
133 |
elif llm_model == "TinyLlama/TinyLlama-1.1B-Chat-v1.0":
|
134 |
llm = HuggingFaceEndpoint(
|
135 |
repo_id=llm_model,
|
136 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": 250, "top_k": top_k}
|
137 |
temperature = temperature,
|
138 |
max_new_tokens = 250,
|
139 |
top_k = top_k,
|
@@ -142,7 +127,6 @@ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, pr
|
|
142 |
raise gr.Error("Llama-2-7b-chat-hf model requires a Pro subscription...")
|
143 |
llm = HuggingFaceEndpoint(
|
144 |
repo_id=llm_model,
|
145 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
|
146 |
temperature = temperature,
|
147 |
max_new_tokens = max_tokens,
|
148 |
top_k = top_k,
|
@@ -150,8 +134,6 @@ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, pr
|
|
150 |
else:
|
151 |
llm = HuggingFaceEndpoint(
|
152 |
repo_id=llm_model,
|
153 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
|
154 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
|
155 |
temperature = temperature,
|
156 |
max_new_tokens = max_tokens,
|
157 |
top_k = top_k,
|
@@ -163,7 +145,6 @@ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, pr
|
|
163 |
output_key='answer',
|
164 |
return_messages=True
|
165 |
)
|
166 |
-
# retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})
|
167 |
retriever=vector_db.as_retriever()
|
168 |
progress(0.8, desc="Defining retrieval chain...")
|
169 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
@@ -171,34 +152,21 @@ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, pr
|
|
171 |
retriever=retriever,
|
172 |
chain_type="stuff",
|
173 |
memory=memory,
|
174 |
-
# combine_docs_chain_kwargs={"prompt": your_prompt})
|
175 |
return_source_documents=True,
|
176 |
-
#return_generated_question=False,
|
177 |
verbose=False,
|
178 |
)
|
179 |
progress(0.9, desc="Done!")
|
180 |
return qa_chain
|
181 |
|
182 |
-
|
183 |
# Generate collection name for vector database
|
184 |
-
# - Use filepath as input, ensuring unicode text
|
185 |
def create_collection_name(filepath):
|
186 |
-
# Extract filename without extension
|
187 |
collection_name = Path(filepath).stem
|
188 |
-
# Fix potential issues from naming convention
|
189 |
-
## Remove space
|
190 |
collection_name = collection_name.replace(" ","-")
|
191 |
-
## ASCII transliterations of Unicode text
|
192 |
collection_name = unidecode(collection_name)
|
193 |
-
## Remove special characters
|
194 |
-
#collection_name = re.findall("[\dA-Za-z]*", collection_name)[0]
|
195 |
collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
|
196 |
-
## Limit length to 50 characters
|
197 |
collection_name = collection_name[:50]
|
198 |
-
## Minimum length of 3 characters
|
199 |
if len(collection_name) < 3:
|
200 |
collection_name = collection_name + 'xyz'
|
201 |
-
## Enforce start and end as alphanumeric character
|
202 |
if not collection_name[0].isalnum():
|
203 |
collection_name = 'A' + collection_name[1:]
|
204 |
if not collection_name[-1].isalnum():
|
@@ -207,46 +175,34 @@ def create_collection_name(filepath):
|
|
207 |
print('Collection name: ', collection_name)
|
208 |
return collection_name
|
209 |
|
210 |
-
|
211 |
# Initialize database
|
212 |
def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
|
213 |
-
# Create list of documents (when valid)
|
214 |
list_file_path = [x.name for x in list_file_obj if x is not None]
|
215 |
-
# Create collection_name for vector database
|
216 |
progress(0.1, desc="Creating collection name...")
|
217 |
collection_name = create_collection_name(list_file_path[0])
|
218 |
progress(0.25, desc="Loading document...")
|
219 |
-
# Load document and create splits
|
220 |
doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
|
221 |
-
# Create or load vector database
|
222 |
progress(0.5, desc="Generating vector database...")
|
223 |
-
# global vector_db
|
224 |
vector_db = create_db(doc_splits, collection_name)
|
225 |
progress(0.9, desc="Done!")
|
226 |
return vector_db, collection_name, "Complete!"
|
227 |
|
228 |
-
|
229 |
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
230 |
-
# print("llm_option",llm_option)
|
231 |
llm_name = list_llm[llm_option]
|
232 |
print("llm_name: ",llm_name)
|
233 |
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
|
234 |
return qa_chain, "Complete!"
|
235 |
|
236 |
-
|
237 |
def format_chat_history(message, chat_history):
|
238 |
formatted_chat_history = []
|
239 |
for user_message, bot_message in chat_history:
|
240 |
formatted_chat_history.append(f"User: {user_message}")
|
241 |
formatted_chat_history.append(f"Assistant: {bot_message}")
|
242 |
return formatted_chat_history
|
243 |
-
|
244 |
|
245 |
def conversation(qa_chain, message, history):
|
246 |
formatted_chat_history = format_chat_history(message, history)
|
247 |
-
#print("formatted_chat_history",formatted_chat_history)
|
248 |
|
249 |
-
# Generate response using QA chain
|
250 |
response = qa_chain({"question": message, "chat_history": formatted_chat_history})
|
251 |
response_answer = response["answer"]
|
252 |
if response_answer.find("Helpful Answer:") != -1:
|
@@ -255,34 +211,40 @@ def conversation(qa_chain, message, history):
|
|
255 |
response_source1 = response_sources[0].page_content.strip()
|
256 |
response_source2 = response_sources[1].page_content.strip()
|
257 |
response_source3 = response_sources[2].page_content.strip()
|
258 |
-
# Langchain sources are zero-based
|
259 |
response_source1_page = response_sources[0].metadata["page"] + 1
|
260 |
response_source2_page = response_sources[1].metadata["page"] + 1
|
261 |
response_source3_page = response_sources[2].metadata["page"] + 1
|
262 |
-
# print ('chat response: ', response_answer)
|
263 |
-
# print('DB source', response_sources)
|
264 |
|
265 |
-
# Append user message and response to chat history
|
266 |
new_history = history + [(message, response_answer)]
|
267 |
-
# return gr.update(value=""), new_history, response_sources[0], response_sources[1]
|
268 |
return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
|
269 |
-
|
270 |
|
271 |
def upload_file(file_obj):
|
272 |
list_file_path = []
|
273 |
for idx, file in enumerate(file_obj):
|
274 |
file_path = file_obj.name
|
275 |
list_file_path.append(file_path)
|
276 |
-
# print(file_path)
|
277 |
-
# initialize_database(file_path, progress)
|
278 |
return list_file_path
|
279 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
280 |
|
281 |
def demo():
|
282 |
with gr.Blocks(theme="base") as demo:
|
283 |
vector_db = gr.State()
|
284 |
qa_chain = gr.State()
|
285 |
collection_name = gr.State()
|
|
|
286 |
|
287 |
gr.Markdown(
|
288 |
"""<center><h2>PDF-based chatbot</center></h2>
|
@@ -295,7 +257,6 @@ def demo():
|
|
295 |
with gr.Tab("Step 1 - Upload PDF"):
|
296 |
with gr.Row():
|
297 |
document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
|
298 |
-
# upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)
|
299 |
|
300 |
with gr.Tab("Step 2 - Process document"):
|
301 |
with gr.Row():
|
@@ -309,7 +270,7 @@ def demo():
|
|
309 |
db_progress = gr.Textbox(label="Vector database initialization", value="None")
|
310 |
with gr.Row():
|
311 |
db_btn = gr.Button("Generate vector database")
|
312 |
-
|
313 |
with gr.Tab("Step 3 - Initialize QA chain"):
|
314 |
with gr.Row():
|
315 |
llm_btn = gr.Radio(list_llm_simple, \
|
@@ -326,7 +287,13 @@ def demo():
|
|
326 |
with gr.Row():
|
327 |
qachain_btn = gr.Button("Initialize Question Answering chain")
|
328 |
|
329 |
-
with gr.Tab("Step 4 -
|
|
|
|
|
|
|
|
|
|
|
|
|
330 |
chatbot = gr.Chatbot(height=300)
|
331 |
with gr.Accordion("Advanced - Document references", open=False):
|
332 |
with gr.Row():
|
@@ -345,7 +312,6 @@ def demo():
|
|
345 |
clear_btn = gr.ClearButton([msg, chatbot], value="Clear conversation")
|
346 |
|
347 |
# Preprocessing events
|
348 |
-
#upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])
|
349 |
db_btn.click(initialize_database, \
|
350 |
inputs=[document, slider_chunk_size, slider_chunk_overlap], \
|
351 |
outputs=[vector_db, collection_name, db_progress])
|
@@ -355,6 +321,9 @@ def demo():
|
|
355 |
inputs=None, \
|
356 |
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
|
357 |
queue=False)
|
|
|
|
|
|
|
358 |
|
359 |
# Chatbot events
|
360 |
msg.submit(conversation, \
|
|
|
22 |
import accelerate
|
23 |
import re
|
24 |
|
25 |
+
# LlamaParse import
|
26 |
+
from llama_parse import LlamaParse
|
27 |
+
import asyncio
|
28 |
+
from llama_index.core.async_utils import DEFAULT_NUM_WORKERS, run_jobs
|
29 |
+
from llama_index.core.base.response.schema import PydanticResponse
|
30 |
+
from llama_index.core.bridge.pydantic import BaseModel, Field, ValidationError
|
31 |
+
from llama_index.core.callbacks.base import CallbackManager
|
32 |
+
from llama_index.core.llms.llm import LLM
|
33 |
+
from llama_index.core.node_parser.interface import NodeParser
|
34 |
+
from llama_index.core.schema import BaseNode, Document, IndexNode, TextNode
|
35 |
+
from llama_index.core.utils import get_tqdm_iterable
|
36 |
|
37 |
+
from io import StringIO
|
38 |
+
from typing import Any, Callable, List, Optional
|
39 |
+
|
40 |
+
import pandas as pd
|
41 |
+
from llama_index.core.node_parser.relational.base_element import (
|
42 |
+
# BaseElementNodeParser,
|
43 |
+
Element,
|
44 |
+
)
|
45 |
+
from llama_index.core.schema import BaseNode, TextNode
|
46 |
+
|
47 |
+
# Implementations
|
48 |
|
49 |
# default_persist_directory = './chroma_HF/'
|
50 |
list_llm = ["mistralai/Mistral-7B-Instruct-v0.3", "mistralai/Mixtral-8x7B-Instruct-v0.1", "mistralai/Mistral-7B-Instruct-v0.1", \
|
|
|
58 |
|
59 |
# Load PDF document and create doc splits
|
60 |
def load_doc(list_file_path, chunk_size, chunk_overlap):
|
|
|
|
|
|
|
61 |
loaders = [PyPDFLoader(x) for x in list_file_path]
|
62 |
pages = []
|
63 |
for loader in loaders:
|
64 |
pages.extend(loader.load())
|
65 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size = chunk_size, chunk_overlap = chunk_overlap)
|
|
|
|
|
|
|
66 |
doc_splits = text_splitter.split_documents(pages)
|
67 |
return doc_splits
|
68 |
|
|
|
69 |
# Create vector database
|
70 |
def create_db(splits, collection_name):
|
71 |
embedding = HuggingFaceEmbeddings()
|
|
|
75 |
embedding=embedding,
|
76 |
client=new_client,
|
77 |
collection_name=collection_name,
|
|
|
78 |
)
|
79 |
return vectordb
|
80 |
|
|
|
81 |
# Load vector database
|
82 |
def load_db():
|
83 |
embedding = HuggingFaceEmbeddings()
|
84 |
vectordb = Chroma(
|
|
|
85 |
embedding_function=embedding)
|
86 |
return vectordb
|
87 |
|
|
|
88 |
# Initialize langchain LLM chain
|
89 |
def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
90 |
progress(0.1, desc="Initializing HF tokenizer...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
|
|
|
92 |
progress(0.5, desc="Initializing HF Hub...")
|
93 |
+
|
|
|
|
|
94 |
if llm_model == "mistralai/Mixtral-8x7B-Instruct-v0.3":
|
95 |
llm = HuggingFaceEndpoint(
|
96 |
repo_id=llm_model,
|
|
|
97 |
temperature = temperature,
|
98 |
max_new_tokens = max_tokens,
|
99 |
top_k = top_k,
|
|
|
108 |
top_k = top_k,
|
109 |
)
|
110 |
elif llm_model == "microsoft/phi-2":
|
|
|
111 |
llm = HuggingFaceEndpoint(
|
112 |
repo_id=llm_model,
|
|
|
113 |
temperature = temperature,
|
114 |
max_new_tokens = max_tokens,
|
115 |
top_k = top_k,
|
|
|
119 |
elif llm_model == "TinyLlama/TinyLlama-1.1B-Chat-v1.0":
|
120 |
llm = HuggingFaceEndpoint(
|
121 |
repo_id=llm_model,
|
|
|
122 |
temperature = temperature,
|
123 |
max_new_tokens = 250,
|
124 |
top_k = top_k,
|
|
|
127 |
raise gr.Error("Llama-2-7b-chat-hf model requires a Pro subscription...")
|
128 |
llm = HuggingFaceEndpoint(
|
129 |
repo_id=llm_model,
|
|
|
130 |
temperature = temperature,
|
131 |
max_new_tokens = max_tokens,
|
132 |
top_k = top_k,
|
|
|
134 |
else:
|
135 |
llm = HuggingFaceEndpoint(
|
136 |
repo_id=llm_model,
|
|
|
|
|
137 |
temperature = temperature,
|
138 |
max_new_tokens = max_tokens,
|
139 |
top_k = top_k,
|
|
|
145 |
output_key='answer',
|
146 |
return_messages=True
|
147 |
)
|
|
|
148 |
retriever=vector_db.as_retriever()
|
149 |
progress(0.8, desc="Defining retrieval chain...")
|
150 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
|
|
152 |
retriever=retriever,
|
153 |
chain_type="stuff",
|
154 |
memory=memory,
|
|
|
155 |
return_source_documents=True,
|
|
|
156 |
verbose=False,
|
157 |
)
|
158 |
progress(0.9, desc="Done!")
|
159 |
return qa_chain
|
160 |
|
|
|
161 |
# Generate collection name for vector database
|
|
|
162 |
def create_collection_name(filepath):
|
|
|
163 |
collection_name = Path(filepath).stem
|
|
|
|
|
164 |
collection_name = collection_name.replace(" ","-")
|
|
|
165 |
collection_name = unidecode(collection_name)
|
|
|
|
|
166 |
collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
|
|
|
167 |
collection_name = collection_name[:50]
|
|
|
168 |
if len(collection_name) < 3:
|
169 |
collection_name = collection_name + 'xyz'
|
|
|
170 |
if not collection_name[0].isalnum():
|
171 |
collection_name = 'A' + collection_name[1:]
|
172 |
if not collection_name[-1].isalnum():
|
|
|
175 |
print('Collection name: ', collection_name)
|
176 |
return collection_name
|
177 |
|
|
|
178 |
# Initialize database
|
179 |
def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
|
|
|
180 |
list_file_path = [x.name for x in list_file_obj if x is not None]
|
|
|
181 |
progress(0.1, desc="Creating collection name...")
|
182 |
collection_name = create_collection_name(list_file_path[0])
|
183 |
progress(0.25, desc="Loading document...")
|
|
|
184 |
doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
|
|
|
185 |
progress(0.5, desc="Generating vector database...")
|
|
|
186 |
vector_db = create_db(doc_splits, collection_name)
|
187 |
progress(0.9, desc="Done!")
|
188 |
return vector_db, collection_name, "Complete!"
|
189 |
|
|
|
190 |
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
|
|
191 |
llm_name = list_llm[llm_option]
|
192 |
print("llm_name: ",llm_name)
|
193 |
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
|
194 |
return qa_chain, "Complete!"
|
195 |
|
|
|
196 |
def format_chat_history(message, chat_history):
|
197 |
formatted_chat_history = []
|
198 |
for user_message, bot_message in chat_history:
|
199 |
formatted_chat_history.append(f"User: {user_message}")
|
200 |
formatted_chat_history.append(f"Assistant: {bot_message}")
|
201 |
return formatted_chat_history
|
|
|
202 |
|
203 |
def conversation(qa_chain, message, history):
|
204 |
formatted_chat_history = format_chat_history(message, history)
|
|
|
205 |
|
|
|
206 |
response = qa_chain({"question": message, "chat_history": formatted_chat_history})
|
207 |
response_answer = response["answer"]
|
208 |
if response_answer.find("Helpful Answer:") != -1:
|
|
|
211 |
response_source1 = response_sources[0].page_content.strip()
|
212 |
response_source2 = response_sources[1].page_content.strip()
|
213 |
response_source3 = response_sources[2].page_content.strip()
|
|
|
214 |
response_source1_page = response_sources[0].metadata["page"] + 1
|
215 |
response_source2_page = response_sources[1].metadata["page"] + 1
|
216 |
response_source3_page = response_sources[2].metadata["page"] + 1
|
|
|
|
|
217 |
|
|
|
218 |
new_history = history + [(message, response_answer)]
|
|
|
219 |
return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
|
|
|
220 |
|
221 |
def upload_file(file_obj):
|
222 |
list_file_path = []
|
223 |
for idx, file in enumerate(file_obj):
|
224 |
file_path = file_obj.name
|
225 |
list_file_path.append(file_path)
|
|
|
|
|
226 |
return list_file_path
|
227 |
|
228 |
+
# Initialize LlamaIndex parsing
|
229 |
+
def initialize_llama_index(file_obj):
|
230 |
+
documents = LlamaParse(result_type="markdown",api_key=secret_value_0).load_data(file_obj.name)
|
231 |
+
node_parser = MarkdownElementNodeParser(llm = None, num_workers=8)
|
232 |
+
nodes = node_parser.get_nodes_from_documents(documents)
|
233 |
+
base_nodes, objects = node_parser.get_nodes_and_objects(nodes)
|
234 |
+
index_with_obj = VectorStoreIndex(nodes=base_nodes+objects)
|
235 |
+
index_ret = index_with_obj.as_retriever(top_k=15)
|
236 |
+
recursive_query_engine = RetrieverQueryEngine.from_args(index_ret, node_postprocessors=[FlagEmbeddingReranker(
|
237 |
+
top_n=5,
|
238 |
+
model="BAAI/bge-reranker-large",
|
239 |
+
)], verbose=False)
|
240 |
+
return recursive_query_engine, "LlamaIndex parsing complete"
|
241 |
|
242 |
def demo():
|
243 |
with gr.Blocks(theme="base") as demo:
|
244 |
vector_db = gr.State()
|
245 |
qa_chain = gr.State()
|
246 |
collection_name = gr.State()
|
247 |
+
llama_index_engine = gr.State()
|
248 |
|
249 |
gr.Markdown(
|
250 |
"""<center><h2>PDF-based chatbot</center></h2>
|
|
|
257 |
with gr.Tab("Step 1 - Upload PDF"):
|
258 |
with gr.Row():
|
259 |
document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
|
|
|
260 |
|
261 |
with gr.Tab("Step 2 - Process document"):
|
262 |
with gr.Row():
|
|
|
270 |
db_progress = gr.Textbox(label="Vector database initialization", value="None")
|
271 |
with gr.Row():
|
272 |
db_btn = gr.Button("Generate vector database")
|
273 |
+
|
274 |
with gr.Tab("Step 3 - Initialize QA chain"):
|
275 |
with gr.Row():
|
276 |
llm_btn = gr.Radio(list_llm_simple, \
|
|
|
287 |
with gr.Row():
|
288 |
qachain_btn = gr.Button("Initialize Question Answering chain")
|
289 |
|
290 |
+
with gr.Tab("Step 4 - LlamaIndex parsing"):
|
291 |
+
with gr.Row():
|
292 |
+
llama_index_btn = gr.Button("Parse with LlamaIndex")
|
293 |
+
with gr.Row():
|
294 |
+
llama_index_progress = gr.Textbox(label="LlamaIndex parsing status", value="None")
|
295 |
+
|
296 |
+
with gr.Tab("Step 5 - Chatbot"):
|
297 |
chatbot = gr.Chatbot(height=300)
|
298 |
with gr.Accordion("Advanced - Document references", open=False):
|
299 |
with gr.Row():
|
|
|
312 |
clear_btn = gr.ClearButton([msg, chatbot], value="Clear conversation")
|
313 |
|
314 |
# Preprocessing events
|
|
|
315 |
db_btn.click(initialize_database, \
|
316 |
inputs=[document, slider_chunk_size, slider_chunk_overlap], \
|
317 |
outputs=[vector_db, collection_name, db_progress])
|
|
|
321 |
inputs=None, \
|
322 |
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
|
323 |
queue=False)
|
324 |
+
llama_index_btn.click(initialize_llama_index, \
|
325 |
+
inputs=[document], \
|
326 |
+
outputs=[llama_index_engine, llama_index_progress])
|
327 |
|
328 |
# Chatbot events
|
329 |
msg.submit(conversation, \
|