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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
from typing import List, Dict
|
4 |
+
from langchain.text_splitter import (
|
5 |
+
RecursiveCharacterTextSplitter,
|
6 |
+
CharacterTextSplitter,
|
7 |
+
TokenTextSplitter
|
8 |
+
)
|
9 |
+
from langchain_community.vectorstores import FAISS, Chroma, Qdrant
|
10 |
+
from langchain_community.document_loaders import PyPDFLoader
|
11 |
+
from langchain.chains import ConversationalRetrievalChain
|
12 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
13 |
+
from langchain_huggingface import HuggingFaceEndpoint
|
14 |
+
from langchain.memory import ConversationBufferMemory
|
15 |
+
|
16 |
+
list_llm = ["meta-llama/Meta-Llama-3-8B-Instruct", "mistralai/Mistral-7B-Instruct-v0.2"]
|
17 |
+
list_llm_simple = [os.path.basename(llm) for llm in list_llm]
|
18 |
+
api_token = os.getenv("HF_TOKEN")
|
19 |
+
|
20 |
+
CHUNK_SIZES = {
|
21 |
+
"small": {"recursive": 512, "fixed": 512, "token": 256},
|
22 |
+
"medium": {"recursive": 1024, "fixed": 1024, "token": 512}
|
23 |
+
}
|
24 |
+
|
25 |
+
def get_text_splitter(strategy: str, chunk_size: int = 1024, chunk_overlap: int = 64):
|
26 |
+
splitters = {
|
27 |
+
"recursive": RecursiveCharacterTextSplitter(
|
28 |
+
chunk_size=chunk_size,
|
29 |
+
chunk_overlap=chunk_overlap
|
30 |
+
),
|
31 |
+
"fixed": CharacterTextSplitter(
|
32 |
+
chunk_size=chunk_size,
|
33 |
+
chunk_overlap=chunk_overlap
|
34 |
+
),
|
35 |
+
"token": TokenTextSplitter(
|
36 |
+
chunk_size=chunk_size,
|
37 |
+
chunk_overlap=chunk_overlap
|
38 |
+
)
|
39 |
+
}
|
40 |
+
return splitters.get(strategy)
|
41 |
+
|
42 |
+
def load_doc(list_file_path: List[str], splitting_strategy: str, chunk_size: str):
|
43 |
+
chunk_size_value = CHUNK_SIZES[chunk_size][splitting_strategy]
|
44 |
+
loaders = [PyPDFLoader(x) for x in list_file_path]
|
45 |
+
pages = []
|
46 |
+
for loader in loaders:
|
47 |
+
pages.extend(loader.load())
|
48 |
+
|
49 |
+
text_splitter = get_text_splitter(splitting_strategy, chunk_size_value)
|
50 |
+
doc_splits = text_splitter.split_documents(pages)
|
51 |
+
return doc_splits
|
52 |
+
|
53 |
+
def create_db(splits, db_choice: str = "faiss"):
|
54 |
+
embeddings = HuggingFaceEmbeddings()
|
55 |
+
db_creators = {
|
56 |
+
"faiss": lambda: FAISS.from_documents(splits, embeddings),
|
57 |
+
"chroma": lambda: Chroma.from_documents(splits, embeddings),
|
58 |
+
"qdrant": lambda: Qdrant.from_documents(
|
59 |
+
splits,
|
60 |
+
embeddings,
|
61 |
+
location=":memory:",
|
62 |
+
collection_name="pdf_docs"
|
63 |
+
)
|
64 |
+
}
|
65 |
+
return db_creators[db_choice]()
|
66 |
+
|
67 |
+
def initialize_database(list_file_obj, splitting_strategy, chunk_size, db_choice, progress=gr.Progress()):
|
68 |
+
"""Initialize vector database with error handling"""
|
69 |
+
try:
|
70 |
+
if not list_file_obj:
|
71 |
+
return None, "No files uploaded. Please upload PDF documents first."
|
72 |
+
|
73 |
+
list_file_path = [x.name for x in list_file_obj if x is not None]
|
74 |
+
if not list_file_path:
|
75 |
+
return None, "No valid files found. Please upload PDF documents."
|
76 |
+
|
77 |
+
doc_splits = load_doc(list_file_path, splitting_strategy, chunk_size)
|
78 |
+
if not doc_splits:
|
79 |
+
return None, "No content extracted from documents."
|
80 |
+
|
81 |
+
vector_db = create_db(doc_splits, db_choice)
|
82 |
+
return vector_db, f"Database created successfully using {splitting_strategy} splitting and {db_choice} vector database!"
|
83 |
+
|
84 |
+
except Exception as e:
|
85 |
+
return None, f"Error creating database: {str(e)}"
|
86 |
+
|
87 |
+
def initialize_llmchain(llm_choice, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
88 |
+
"""Initialize LLM chain with error handling"""
|
89 |
+
try:
|
90 |
+
if vector_db is None:
|
91 |
+
return None, "Please create vector database first."
|
92 |
+
|
93 |
+
llm_model = list_llm[llm_choice]
|
94 |
+
|
95 |
+
llm = HuggingFaceEndpoint(
|
96 |
+
repo_id=llm_model,
|
97 |
+
huggingfacehub_api_token=api_token,
|
98 |
+
temperature=temperature,
|
99 |
+
max_new_tokens=max_tokens,
|
100 |
+
top_k=top_k
|
101 |
+
)
|
102 |
+
|
103 |
+
memory = ConversationBufferMemory(
|
104 |
+
memory_key="chat_history",
|
105 |
+
output_key='answer',
|
106 |
+
return_messages=True
|
107 |
+
)
|
108 |
+
|
109 |
+
retriever = vector_db.as_retriever()
|
110 |
+
qa_chain = ConversationalRetrievalChain.from_llm(
|
111 |
+
llm,
|
112 |
+
retriever=retriever,
|
113 |
+
memory=memory,
|
114 |
+
return_source_documents=True
|
115 |
+
)
|
116 |
+
return qa_chain, "LLM initialized successfully!"
|
117 |
+
|
118 |
+
except Exception as e:
|
119 |
+
return None, f"Error initializing LLM: {str(e)}"
|
120 |
+
|
121 |
+
def conversation(qa_chain, message, history):
|
122 |
+
"""Conversation function returning all required outputs"""
|
123 |
+
response = qa_chain.invoke({
|
124 |
+
"question": message,
|
125 |
+
"chat_history": [(hist[0], hist[1]) for hist in history]
|
126 |
+
})
|
127 |
+
|
128 |
+
response_answer = response["answer"]
|
129 |
+
if "Helpful Answer:" in response_answer:
|
130 |
+
response_answer = response_answer.split("Helpful Answer:")[-1]
|
131 |
+
|
132 |
+
sources = response["source_documents"][:3]
|
133 |
+
source_contents = []
|
134 |
+
source_pages = []
|
135 |
+
|
136 |
+
for source in sources:
|
137 |
+
source_contents.append(source.page_content.strip())
|
138 |
+
source_pages.append(source.metadata.get("page", 0) + 1)
|
139 |
+
|
140 |
+
while len(source_contents) < 3:
|
141 |
+
source_contents.append("")
|
142 |
+
source_pages.append(0)
|
143 |
+
|
144 |
+
return (
|
145 |
+
qa_chain,
|
146 |
+
gr.update(value=""),
|
147 |
+
history + [(message, response_answer)],
|
148 |
+
source_contents[0],
|
149 |
+
source_pages[0],
|
150 |
+
source_contents[1],
|
151 |
+
source_pages[1],
|
152 |
+
source_contents[2],
|
153 |
+
source_pages[2]
|
154 |
+
)
|
155 |
+
|
156 |
+
def demo():
|
157 |
+
with gr.Blocks(theme=gr.themes.Default(primary_hue="red", secondary_hue="pink", neutral_hue="sky")) as demo:
|
158 |
+
vector_db = gr.State()
|
159 |
+
qa_chain = gr.State()
|
160 |
+
|
161 |
+
gr.HTML("<center><h1>RAG PDF Chatbot</h1></center>")
|
162 |
+
|
163 |
+
with gr.Column(scale=86):
|
164 |
+
gr.Markdown("<b>Step 1 - Configure and Initialize RAG Pipeline</b>")
|
165 |
+
with gr.Row():
|
166 |
+
document = gr.Files(
|
167 |
+
height=300,
|
168 |
+
file_count="multiple",
|
169 |
+
file_types=["pdf"],
|
170 |
+
interactive=True,
|
171 |
+
label="Upload PDF documents"
|
172 |
+
)
|
173 |
+
|
174 |
+
with gr.Row():
|
175 |
+
splitting_strategy = gr.Radio(
|
176 |
+
["recursive", "fixed", "token"],
|
177 |
+
label="Text Splitting Strategy",
|
178 |
+
value="recursive"
|
179 |
+
)
|
180 |
+
db_choice = gr.Radio(
|
181 |
+
["faiss", "chroma", "qdrant"],
|
182 |
+
label="Vector Database",
|
183 |
+
value="faiss"
|
184 |
+
)
|
185 |
+
chunk_size = gr.Radio(
|
186 |
+
["small", "medium"],
|
187 |
+
label="Chunk Size",
|
188 |
+
value="medium"
|
189 |
+
)
|
190 |
+
|
191 |
+
with gr.Row():
|
192 |
+
db_btn = gr.Button("Create vector database")
|
193 |
+
db_progress = gr.Textbox(
|
194 |
+
value="Not initialized",
|
195 |
+
show_label=False
|
196 |
+
)
|
197 |
+
|
198 |
+
gr.Markdown("<b>Step 2 - Configure LLM</b>")
|
199 |
+
with gr.Row():
|
200 |
+
llm_choice = gr.Radio(
|
201 |
+
list_llm_simple,
|
202 |
+
label="Available LLMs",
|
203 |
+
value=list_llm_simple[0],
|
204 |
+
type="index"
|
205 |
+
)
|
206 |
+
|
207 |
+
with gr.Row():
|
208 |
+
with gr.Accordion("LLM Parameters", open=False):
|
209 |
+
temperature = gr.Slider(
|
210 |
+
minimum=0.01,
|
211 |
+
maximum=1.0,
|
212 |
+
value=0.5,
|
213 |
+
step=0.1,
|
214 |
+
label="Temperature"
|
215 |
+
)
|
216 |
+
max_tokens = gr.Slider(
|
217 |
+
minimum=128,
|
218 |
+
maximum=4096,
|
219 |
+
value=2048,
|
220 |
+
step=128,
|
221 |
+
label="Max Tokens"
|
222 |
+
)
|
223 |
+
top_k = gr.Slider(
|
224 |
+
minimum=1,
|
225 |
+
maximum=10,
|
226 |
+
value=3,
|
227 |
+
step=1,
|
228 |
+
label="Top K"
|
229 |
+
)
|
230 |
+
|
231 |
+
with gr.Row():
|
232 |
+
init_llm_btn = gr.Button("Initialize LLM")
|
233 |
+
llm_progress = gr.Textbox(
|
234 |
+
value="Not initialized",
|
235 |
+
show_label=False
|
236 |
+
)
|
237 |
+
|
238 |
+
with gr.Column(scale=200):
|
239 |
+
gr.Markdown("<b>Step 3 - Chat with Documents</b>")
|
240 |
+
chatbot = gr.Chatbot(height=505)
|
241 |
+
|
242 |
+
with gr.Accordion("Source References", open=False):
|
243 |
+
with gr.Row():
|
244 |
+
source1 = gr.Textbox(label="Source 1", lines=2)
|
245 |
+
page1 = gr.Number(label="Page")
|
246 |
+
with gr.Row():
|
247 |
+
source2 = gr.Textbox(label="Source 2", lines=2)
|
248 |
+
page2 = gr.Number(label="Page")
|
249 |
+
with gr.Row():
|
250 |
+
source3 = gr.Textbox(label="Source 3", lines=2)
|
251 |
+
page3 = gr.Number(label="Page")
|
252 |
+
|
253 |
+
with gr.Row():
|
254 |
+
msg = gr.Textbox(
|
255 |
+
placeholder="Ask a question",
|
256 |
+
show_label=False
|
257 |
+
)
|
258 |
+
with gr.Row():
|
259 |
+
submit_btn = gr.Button("Submit")
|
260 |
+
clear_btn = gr.ClearButton(
|
261 |
+
[msg, chatbot],
|
262 |
+
value="Clear Chat"
|
263 |
+
)
|
264 |
+
|
265 |
+
# Event handlers
|
266 |
+
db_btn.click(
|
267 |
+
initialize_database,
|
268 |
+
inputs=[document, splitting_strategy, chunk_size, db_choice],
|
269 |
+
outputs=[vector_db, db_progress]
|
270 |
+
).then(
|
271 |
+
lambda x: gr.update(interactive=True) if x[0] is not None else gr.update(interactive=False),
|
272 |
+
inputs=[vector_db],
|
273 |
+
outputs=[init_llm_btn]
|
274 |
+
)
|
275 |
+
|
276 |
+
init_llm_btn.click(
|
277 |
+
initialize_llmchain,
|
278 |
+
inputs=[llm_choice, temperature, max_tokens, top_k, vector_db],
|
279 |
+
outputs=[qa_chain, llm_progress]
|
280 |
+
).then(
|
281 |
+
lambda x: gr.update(interactive=True) if x[0] is not None else gr.update(interactive=False),
|
282 |
+
inputs=[qa_chain],
|
283 |
+
outputs=[msg]
|
284 |
+
)
|
285 |
+
|
286 |
+
msg.submit(
|
287 |
+
conversation,
|
288 |
+
inputs=[qa_chain, msg, chatbot],
|
289 |
+
outputs=[qa_chain, msg, chatbot, source1, page1, source2, page2, source3, page3]
|
290 |
+
)
|
291 |
+
|
292 |
+
submit_btn.click(
|
293 |
+
conversation,
|
294 |
+
inputs=[qa_chain, msg, chatbot],
|
295 |
+
outputs=[qa_chain, msg, chatbot, source1, page1, source2, page2, source3, page3]
|
296 |
+
)
|
297 |
+
|
298 |
+
clear_btn.click(
|
299 |
+
lambda: [None, "", 0, "", 0, "", 0],
|
300 |
+
outputs=[chatbot, source1, page1, source2, page2, source3, page3]
|
301 |
+
)
|
302 |
+
|
303 |
+
demo.queue().launch(debug=True)
|
304 |
+
|
305 |
+
if __name__ == "__main__":
|
306 |
+
demo()
|