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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
from langchain_community.vectorstores import FAISS
|
| 4 |
+
from langchain_community.document_loaders import PyPDFLoader
|
| 5 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 6 |
+
from langchain_community.vectorstores import Chroma
|
| 7 |
+
from langchain.chains import ConversationalRetrievalChain
|
| 8 |
+
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 torch
|
| 14 |
+
|
| 15 |
+
api_token = os.getenv("HF_TOKEN")
|
| 16 |
+
|
| 17 |
+
list_llm = ["microsoft/Phi-3-mini-4k-instruct", "mistralai/Mistral-7B-Instruct-v0.3"]
|
| 18 |
+
list_llm_simple = [os.path.basename(llm) for llm in list_llm]
|
| 19 |
+
|
| 20 |
+
# Load and split PDF document
|
| 21 |
+
def load_doc(list_file_path, chunk_size, chunk_overlap):
|
| 22 |
+
loaders = [PyPDFLoader(x) for x in list_file_path]
|
| 23 |
+
pages = []
|
| 24 |
+
for loader in loaders:
|
| 25 |
+
pages.extend(loader.load())
|
| 26 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 27 |
+
chunk_size=chunk_size,
|
| 28 |
+
chunk_overlap=chunk_overlap
|
| 29 |
+
)
|
| 30 |
+
doc_splits = text_splitter.split_documents(pages)
|
| 31 |
+
return doc_splits
|
| 32 |
+
|
| 33 |
+
# Create vector database
|
| 34 |
+
def create_db(splits):
|
| 35 |
+
embeddings = HuggingFaceEmbeddings()
|
| 36 |
+
vectordb = FAISS.from_documents(splits, embeddings)
|
| 37 |
+
return vectordb
|
| 38 |
+
|
| 39 |
+
# Initialize langchain LLM chain
|
| 40 |
+
def initialize_llmchain(llm_model, vector_db, progress=gr.Progress()):
|
| 41 |
+
llm = HuggingFaceEndpoint(
|
| 42 |
+
huggingfacehub_api_token=api_token,
|
| 43 |
+
repo_id=llm_model,
|
| 44 |
+
temperature=0.1,
|
| 45 |
+
max_new_tokens=2000,
|
| 46 |
+
top_k=3,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
memory = ConversationBufferMemory(
|
| 50 |
+
memory_key="chat_history",
|
| 51 |
+
output_key='answer',
|
| 52 |
+
return_messages=True
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
retriever = vector_db.as_retriever()
|
| 56 |
+
qa_chain = ConversationalRetrievalChain.from_llm(
|
| 57 |
+
llm,
|
| 58 |
+
retriever=retriever,
|
| 59 |
+
chain_type="stuff",
|
| 60 |
+
memory=memory,
|
| 61 |
+
return_source_documents=True,
|
| 62 |
+
verbose=False,
|
| 63 |
+
)
|
| 64 |
+
return qa_chain
|
| 65 |
+
|
| 66 |
+
# Initialize database
|
| 67 |
+
def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
|
| 68 |
+
list_file_path = [x.name for x in list_file_obj if x is not None]
|
| 69 |
+
doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
|
| 70 |
+
vector_db = create_db(doc_splits)
|
| 71 |
+
if vector_db is None:
|
| 72 |
+
print("Vector database creation failed")
|
| 73 |
+
else:
|
| 74 |
+
print("Embedding database created successfully")
|
| 75 |
+
return vector_db, "Embedding database created!"
|
| 76 |
+
|
| 77 |
+
# Initialize LLM
|
| 78 |
+
def initialize_LLM(llm_option, vector_db, progress=gr.Progress()):
|
| 79 |
+
if vector_db is None:
|
| 80 |
+
print("Vector database is None")
|
| 81 |
+
return None, "Failed to initialize RAG System: Vector database is None"
|
| 82 |
+
|
| 83 |
+
llm_name = list_llm[llm_option]
|
| 84 |
+
qa_chain = initialize_llmchain(llm_name, vector_db, progress)
|
| 85 |
+
return qa_chain, "RAG System initialized!"
|
| 86 |
+
|
| 87 |
+
def format_chat_history(message, chat_history):
|
| 88 |
+
formatted_chat_history = []
|
| 89 |
+
for user_message, bot_message in chat_history:
|
| 90 |
+
formatted_chat_history.append(f"User: {user_message}")
|
| 91 |
+
formatted_chat_history.append(f"Assistant: {bot_message}")
|
| 92 |
+
return formatted_chat_history
|
| 93 |
+
|
| 94 |
+
def conversation(qa_chain, message, history):
|
| 95 |
+
formatted_chat_history = format_chat_history(message, history)
|
| 96 |
+
response = qa_chain.invoke({"question": message, "chat_history": formatted_chat_history})
|
| 97 |
+
response_answer = response["answer"]
|
| 98 |
+
if response_answer.find("Helpful Answer:") != -1:
|
| 99 |
+
response_answer = response_answer.split("Helpful Answer:")[-1]
|
| 100 |
+
response_sources = response["source_documents"]
|
| 101 |
+
response_source1 = response_sources[0].page_content.strip()
|
| 102 |
+
response_source2 = response_sources[1].page_content.strip()
|
| 103 |
+
response_source3 = response_sources[2].page_content.strip()
|
| 104 |
+
response_source1_page = response_sources[0].metadata["page"] + 1
|
| 105 |
+
response_source2_page = response_sources[1].metadata["page"] + 1
|
| 106 |
+
response_source3_page = response_sources[2].metadata["page"] + 1
|
| 107 |
+
new_history = history + [(message, response_answer)]
|
| 108 |
+
return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
|
| 109 |
+
|
| 110 |
+
def upload_file(file_obj):
|
| 111 |
+
list_file_path = []
|
| 112 |
+
for idx, file in enumerate(file_obj):
|
| 113 |
+
file_path = file_obj.name
|
| 114 |
+
list_file_path.append(file_path)
|
| 115 |
+
return list_file_path
|
| 116 |
+
|
| 117 |
+
def demo():
|
| 118 |
+
with gr.Blocks(theme=gr.themes.Default(primary_hue="green")) as demo:
|
| 119 |
+
vector_db = gr.State()
|
| 120 |
+
qa_chain = gr.State()
|
| 121 |
+
gr.HTML("<center><h1>RAG System</h1><center>")
|
| 122 |
+
gr.Markdown("""This App is designed to perform retrieval augmented generation (RAG) on PDF documents. \
|
| 123 |
+
<b>Please do not upload confidential documents.</b>
|
| 124 |
+
""")
|
| 125 |
+
with gr.Row():
|
| 126 |
+
with gr.Column(scale=86):
|
| 127 |
+
gr.Markdown("<b>Step 1 - Upload PDF documents and Initialize the RAG system</b>")
|
| 128 |
+
with gr.Row():
|
| 129 |
+
document = gr.Files(height=300, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload PDF documents")
|
| 130 |
+
with gr.Row():
|
| 131 |
+
slider_chunk_size = gr.Slider(minimum=10, maximum=1000, value=200, step=5, label="Chunk Size")
|
| 132 |
+
slider_chunk_overlap = gr.Slider(minimum=0, maximum=512, value=20, step=5, label="Chunk Overlap")
|
| 133 |
+
with gr.Row():
|
| 134 |
+
db_btn = gr.Button("Create Embeddings")
|
| 135 |
+
with gr.Row():
|
| 136 |
+
db_progress = gr.Textbox(value="Not initialized", show_label=False)
|
| 137 |
+
gr.Markdown("<style>body { font-size: 16px; }</style><b>Select Large Language Model (LLM)</b>")
|
| 138 |
+
with gr.Row():
|
| 139 |
+
llm_btn = gr.Radio(list_llm_simple, label="Available LLMs", value=list_llm_simple[0], type="index")
|
| 140 |
+
with gr.Row():
|
| 141 |
+
qachain_btn = gr.Button("Initialize RAG system")
|
| 142 |
+
with gr.Row():
|
| 143 |
+
llm_progress = gr.Textbox(value="Not initialized", show_label=False)
|
| 144 |
+
|
| 145 |
+
with gr.Column(scale=200):
|
| 146 |
+
gr.Markdown("<b>Step 2 - Chat with your Document</b>")
|
| 147 |
+
chatbot = gr.Chatbot(height=505)
|
| 148 |
+
with gr.Accordion("Similar context from the source document", open=False):
|
| 149 |
+
with gr.Row():
|
| 150 |
+
doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
|
| 151 |
+
source1_page = gr.Number(label="Page", scale=1)
|
| 152 |
+
with gr.Row():
|
| 153 |
+
doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
|
| 154 |
+
source2_page = gr.Number(label="Page", scale=1)
|
| 155 |
+
with gr.Row():
|
| 156 |
+
doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
|
| 157 |
+
source3_page = gr.Number(label="Page", scale=1)
|
| 158 |
+
with gr.Row():
|
| 159 |
+
msg = gr.Textbox(placeholder="Ask a question", container=True)
|
| 160 |
+
with gr.Row():
|
| 161 |
+
submit_btn = gr.Button("Submit")
|
| 162 |
+
clear_btn = gr.ClearButton([msg, chatbot], value="Clear")
|
| 163 |
+
|
| 164 |
+
# Preprocessing events
|
| 165 |
+
db_btn.click(initialize_database,
|
| 166 |
+
inputs=[document, slider_chunk_size, slider_chunk_overlap],
|
| 167 |
+
outputs=[vector_db, db_progress])
|
| 168 |
+
qachain_btn.click(initialize_LLM,
|
| 169 |
+
inputs=[llm_btn, vector_db],
|
| 170 |
+
outputs=[qa_chain, llm_progress]).then(lambda:[None, "", 0, "", 0, "", 0],
|
| 171 |
+
inputs=None,
|
| 172 |
+
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
| 173 |
+
queue=False)
|
| 174 |
+
|
| 175 |
+
# Chatbot events
|
| 176 |
+
msg.submit(conversation,
|
| 177 |
+
inputs=[qa_chain, msg, chatbot],
|
| 178 |
+
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
| 179 |
+
queue=False)
|
| 180 |
+
submit_btn.click(conversation,
|
| 181 |
+
inputs=[qa_chain, msg, chatbot],
|
| 182 |
+
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
| 183 |
+
queue=False)
|
| 184 |
+
clear_btn.click(lambda: [None, "", 0, "", 0, "", 0],
|
| 185 |
+
inputs=None,
|
| 186 |
+
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
| 187 |
+
queue=False)
|
| 188 |
+
demo.queue().launch(debug=True)
|
| 189 |
+
|
| 190 |
+
if __name__ == "__main__":
|
| 191 |
+
demo()
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers
|
| 3 |
+
sentence-transformers
|
| 4 |
+
langchain
|
| 5 |
+
langchain-community
|
| 6 |
+
tqdm
|
| 7 |
+
accelerate
|
| 8 |
+
pypdf
|
| 9 |
+
faiss-gpu
|