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ders import PyPDFLoader
|
5 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
6 |
+
from langchain.vectorstores import Chroma
|
7 |
+
from langchain.chains import ConversationalRetrievalChain
|
8 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
9 |
+
from langchain.llms import HuggingFacePipeline
|
10 |
+
from langchain.chains import ConversationChain
|
11 |
+
from langchain.memory import ConversationBufferMemory
|
12 |
+
from langchain.llms import HuggingFaceHub
|
13 |
+
|
14 |
+
|
15 |
+
default_persist_directory = './chroma_HF/'
|
16 |
+
MODEL_NAME = "mistralai/Mistral-7B-Instruct-v0.2"
|
17 |
+
|
18 |
+
# Load PDF document and create doc splits
|
19 |
+
def load_doc(list_file_path, chunk_size, chunk_overlap):
|
20 |
+
loaders = [PyPDFLoader(x) for x in list_file_path]
|
21 |
+
pages = []
|
22 |
+
for loader in loaders:
|
23 |
+
pages.extend(loader.load())
|
24 |
+
|
25 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
26 |
+
chunk_size = chunk_size,
|
27 |
+
chunk_overlap = chunk_overlap)
|
28 |
+
doc_splits = text_splitter.split_documents(pages)
|
29 |
+
return doc_splits
|
30 |
+
|
31 |
+
|
32 |
+
# Create vector database
|
33 |
+
def create_db(splits):
|
34 |
+
embedding = HuggingFaceEmbeddings()
|
35 |
+
vectordb = Chroma.from_documents(
|
36 |
+
documents=splits,
|
37 |
+
embedding=embedding,
|
38 |
+
)
|
39 |
+
return vectordb
|
40 |
+
|
41 |
+
|
42 |
+
# Load vector database
|
43 |
+
def load_db():
|
44 |
+
embedding = HuggingFaceEmbeddings()
|
45 |
+
vectordb = Chroma(
|
46 |
+
persist_directory=default_persist_directory,
|
47 |
+
embedding_function=embedding,
|
48 |
+
)
|
49 |
+
return vectordb
|
50 |
+
|
51 |
+
|
52 |
+
# Initialize langchain LLM chain
|
53 |
+
def initialize_llmchain(temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
54 |
+
progress(0.1, desc="Initializing HF tokenizer...")
|
55 |
+
|
56 |
+
# HuggingFaceHub uses HF inference endpoints
|
57 |
+
progress(0.5, desc="Initializing HF Hub...")
|
58 |
+
llm = HuggingFaceHub(
|
59 |
+
repo_id=MODEL_NAME,
|
60 |
+
model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k,\
|
61 |
+
"trust_remote_code": True, "torch_dtype": "auto"}
|
62 |
+
)
|
63 |
+
|
64 |
+
progress(0.75, desc="Defining buffer memory...")
|
65 |
+
memory = ConversationBufferMemory(
|
66 |
+
memory_key="chat_history",
|
67 |
+
output_key='answer',
|
68 |
+
return_messages=True
|
69 |
+
)
|
70 |
+
|
71 |
+
retriever=vector_db.as_retriever()
|
72 |
+
progress(0.8, desc="Defining retrieval chain...")
|
73 |
+
qa_chain = ConversationalRetrievalChain.from_llm(
|
74 |
+
llm,
|
75 |
+
retriever=retriever,
|
76 |
+
chain_type="stuff",
|
77 |
+
memory=memory,
|
78 |
+
return_source_documents=True,
|
79 |
+
)
|
80 |
+
progress(0.9, desc="Done!")
|
81 |
+
return qa_chain
|
82 |
+
|
83 |
+
|
84 |
+
# Initialize database
|
85 |
+
def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
|
86 |
+
# Create list of documents (when valid)
|
87 |
+
#file_path = file_obj.name
|
88 |
+
list_file_path = [x.name for x in list_file_obj if x is not None]
|
89 |
+
# print('list_file_path', list_file_path)
|
90 |
+
progress(0.25, desc="Loading document...")
|
91 |
+
# Load document and create splits
|
92 |
+
doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
|
93 |
+
# Create or load Vector database
|
94 |
+
progress(0.5, desc="Generating vector database...")
|
95 |
+
# global vector_db
|
96 |
+
vector_db = create_db(doc_splits)
|
97 |
+
progress(0.9, desc="Done!")
|
98 |
+
return vector_db, "Complete!"
|
99 |
+
|
100 |
+
|
101 |
+
def initialize_LLM(llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
102 |
+
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
|
103 |
+
return qa_chain, "Complete!"
|
104 |
+
|
105 |
+
|
106 |
+
def format_chat_history(message, chat_history):
|
107 |
+
formatted_chat_history = []
|
108 |
+
for user_message, bot_message in chat_history:
|
109 |
+
formatted_chat_history.append(f"User: {user_message}")
|
110 |
+
formatted_chat_history.append(f"Assistant: {bot_message}")
|
111 |
+
return formatted_chat_history
|
112 |
+
|
113 |
+
|
114 |
+
def conversation(qa_chain, message, history):
|
115 |
+
formatted_chat_history = format_chat_history(message, history)
|
116 |
+
|
117 |
+
# Generate response using QA chain
|
118 |
+
response = qa_chain({"question": message, "chat_history": formatted_chat_history})
|
119 |
+
response_answer = response["answer"]
|
120 |
+
response_sources = response["source_documents"]
|
121 |
+
response_source1 = response_sources[0].page_content.strip()
|
122 |
+
response_source2 = response_sources[1].page_content.strip()
|
123 |
+
# Langchain sources are zero-based
|
124 |
+
response_source1_page = response_sources[0].metadata["page"] + 1
|
125 |
+
response_source2_page = response_sources[1].metadata["page"] + 1
|
126 |
+
# print ('chat response: ', response_answer)
|
127 |
+
# print('DB source', response_sources)
|
128 |
+
|
129 |
+
# Append user message and response to chat history
|
130 |
+
new_history = history + [(message, response_answer)]
|
131 |
+
# return gr.update(value=""), new_history, response_sources[0], response_sources[1]
|
132 |
+
return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page
|
133 |
+
|
134 |
+
|
135 |
+
def upload_file(file_obj):
|
136 |
+
list_file_path = []
|
137 |
+
for idx, file in enumerate(file_obj):
|
138 |
+
file_path = file_obj.name
|
139 |
+
list_file_path.append(file_path)
|
140 |
+
# print(file_path)
|
141 |
+
# initialize_database(file_path, progress)
|
142 |
+
return list_file_path
|
143 |
+
|
144 |
+
|
145 |
+
def demo():
|
146 |
+
with gr.Blocks(theme="base") as demo:
|
147 |
+
vector_db = gr.State()
|
148 |
+
qa_chain = gr.State()
|
149 |
+
|
150 |
+
gr.Markdown(
|
151 |
+
"""<center><h2>Mistral 7B Document Chat</center></h2>
|
152 |
+
<h3>Ask any questions about your PDF documents, along with follow-ups</h3>
|
153 |
+
<br/>
|
154 |
+
<b>Note:</b> This AI assistant performs retrieval-augmented generation from your PDF documents. \
|
155 |
+
When generating answers, it takes past questions into account (via conversational memory), and includes document references for clarity purposes.</i>
|
156 |
+
<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 an output.<br>
|
157 |
+
""")
|
158 |
+
with gr.Tab("Step 1 - Document pre-processing"):
|
159 |
+
with gr.Row():
|
160 |
+
document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
|
161 |
+
with gr.Row():
|
162 |
+
db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")
|
163 |
+
with gr.Accordion("Advanced options - Document text splitter", open=False):
|
164 |
+
with gr.Row():
|
165 |
+
slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)
|
166 |
+
with gr.Row():
|
167 |
+
slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
|
168 |
+
with gr.Row():
|
169 |
+
db_progress = gr.Textbox(label="Vector database initialization", value="None")
|
170 |
+
with gr.Row():
|
171 |
+
db_btn = gr.Button("Generating vector database...")
|
172 |
+
|
173 |
+
with gr.Tab("Step 2 - QA chain initialization"):
|
174 |
+
with gr.Accordion("Advanced options - LLM model", open=False):
|
175 |
+
slider_temperature = gr.Slider(minimum = 0.0, maximum = 1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
|
176 |
+
slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
|
177 |
+
slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
|
178 |
+
with gr.Row():
|
179 |
+
llm_progress = gr.Textbox(value="None",label="QA chain initialization")
|
180 |
+
with gr.Row():
|
181 |
+
qachain_btn = gr.Button("Initializing question-answering chain...")
|
182 |
+
|
183 |
+
with gr.Tab("Step 3 - Conversation with chatbot"):
|
184 |
+
chatbot = gr.Chatbot(height=300)
|
185 |
+
with gr.Accordion("Advanced - Document references", open=False):
|
186 |
+
with gr.Row():
|
187 |
+
doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
|
188 |
+
source1_page = gr.Number(label="Page", scale=1)
|
189 |
+
with gr.Row():
|
190 |
+
doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
|
191 |
+
source2_page = gr.Number(label="Page", scale=1)
|
192 |
+
with gr.Row():
|
193 |
+
msg = gr.Textbox(placeholder="Type message", container=True)
|
194 |
+
with gr.Row():
|
195 |
+
submit_btn = gr.Button("Submit")
|
196 |
+
clear_btn = gr.ClearButton([msg, chatbot])
|
197 |
+
|
198 |
+
# Preprocessing events
|
199 |
+
#upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])
|
200 |
+
db_btn.click(initialize_database, \
|
201 |
+
inputs=[document, slider_chunk_size, slider_chunk_overlap], \
|
202 |
+
outputs=[vector_db, db_progress])
|
203 |
+
qachain_btn.click(initialize_LLM, \
|
204 |
+
inputs=[slider_temperature, slider_maxtokens, slider_topk, vector_db], \
|
205 |
+
outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0], \
|
206 |
+
inputs=None, \
|
207 |
+
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page], \
|
208 |
+
queue=False)
|
209 |
+
|
210 |
+
# Chatbot events
|
211 |
+
msg.submit(conversation, \
|
212 |
+
inputs=[qa_chain, msg, chatbot], \
|
213 |
+
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page], \
|
214 |
+
queue=False)
|
215 |
+
submit_btn.click(conversation, \
|
216 |
+
inputs=[qa_chain, msg, chatbot], \
|
217 |
+
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page], \
|
218 |
+
queue=False)
|
219 |
+
clear_btn.click(lambda:[None,"",0,"",0], \
|
220 |
+
inputs=None, \
|
221 |
+
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page], \
|
222 |
+
queue=False)
|
223 |
+
demo.queue().launch(debug=True)
|
224 |
+
|
225 |
+
|
226 |
+
if __name__ == "__main__":
|
227 |
+
demo()
|