vs commited on
Commit
5647f88
1 Parent(s): f46a9a6
Files changed (3) hide show
  1. app.py +286 -0
  2. readme.txt +1 -0
  3. requirements.txt +8 -0
app.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+
4
+ from langchain.document_loaders 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
+ from transformers import AutoTokenizer
15
+ import transformers
16
+ import torch
17
+ import tqdm
18
+ import accelerate
19
+
20
+
21
+ # default_persist_directory = './chroma_HF/'
22
+
23
+ llm_name1 = "mistralai/Mistral-7B-Instruct-v0.2"
24
+ llm_name2 = "mistralai/Mistral-7B-Instruct-v0.1"
25
+ llm_name3 = "meta-llama/Llama-2-7b-chat-hf"
26
+ llm_name4 = "microsoft/phi-2"
27
+ llm_name5 = "mosaicml/mpt-7b-instruct"
28
+ llm_name6 = "tiiuae/falcon-7b-instruct"
29
+ llm_name7 = "google/flan-t5-xxl"
30
+ list_llm = [llm_name1, llm_name2, llm_name3, llm_name4, llm_name5, llm_name6, llm_name7]
31
+ list_llm_simple = [os.path.basename(llm) for llm in list_llm]
32
+
33
+ # Load PDF document and create doc splits
34
+ def load_doc(list_file_path, chunk_size, chunk_overlap):
35
+ # Processing for one document only
36
+ # loader = PyPDFLoader(file_path)
37
+ # pages = loader.load()
38
+ loaders = [PyPDFLoader(x) for x in list_file_path]
39
+ pages = []
40
+ for loader in loaders:
41
+ pages.extend(loader.load())
42
+ # text_splitter = RecursiveCharacterTextSplitter(chunk_size = 600, chunk_overlap = 50)
43
+ text_splitter = RecursiveCharacterTextSplitter(
44
+ chunk_size = chunk_size,
45
+ chunk_overlap = chunk_overlap)
46
+ doc_splits = text_splitter.split_documents(pages)
47
+ return doc_splits
48
+
49
+
50
+ # Create vector database
51
+ def create_db(splits):
52
+ embedding = HuggingFaceEmbeddings()
53
+ vectordb = Chroma.from_documents(
54
+ documents=splits,
55
+ embedding=embedding,
56
+ # persist_directory=default_persist_directory
57
+ )
58
+ return vectordb
59
+
60
+
61
+ # Load vector database
62
+ def load_db():
63
+ embedding = HuggingFaceEmbeddings()
64
+ vectordb = Chroma(
65
+ persist_directory=default_persist_directory,
66
+ embedding_function=embedding)
67
+ return vectordb
68
+
69
+
70
+ # Initialize langchain LLM chain
71
+ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
72
+ progress(0.1, desc="Initializing HF tokenizer...")
73
+ # HuggingFacePipeline uses local model
74
+ # Note: it will download model locally...
75
+ # tokenizer=AutoTokenizer.from_pretrained(llm_model)
76
+ # progress(0.5, desc="Initializing HF pipeline...")
77
+ # pipeline=transformers.pipeline(
78
+ # "text-generation",
79
+ # model=llm_model,
80
+ # tokenizer=tokenizer,
81
+ # torch_dtype=torch.bfloat16,
82
+ # trust_remote_code=True,
83
+ # device_map="auto",
84
+ # # max_length=1024,
85
+ # max_new_tokens=max_tokens,
86
+ # do_sample=True,
87
+ # top_k=top_k,
88
+ # num_return_sequences=1,
89
+ # eos_token_id=tokenizer.eos_token_id
90
+ # )
91
+ # llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature': temperature})
92
+
93
+ # HuggingFaceHub uses HF inference endpoints
94
+ progress(0.5, desc="Initializing HF Hub...")
95
+ # Use of trust_remote_code as model_kwargs
96
+ # Warning: langchain issue
97
+ # URL: https://github.com/langchain-ai/langchain/issues/6080
98
+ if llm_model == "microsoft/phi-2":
99
+ llm = HuggingFaceHub(
100
+ repo_id=llm_model,
101
+ model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
102
+ )
103
+ else:
104
+ llm = HuggingFaceHub(
105
+ repo_id=llm_model,
106
+ # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
107
+ model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
108
+ )
109
+
110
+ progress(0.75, desc="Defining buffer memory...")
111
+ memory = ConversationBufferMemory(
112
+ memory_key="chat_history",
113
+ output_key='answer',
114
+ return_messages=True
115
+ )
116
+ # retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})
117
+ retriever=vector_db.as_retriever()
118
+ progress(0.8, desc="Defining retrieval chain...")
119
+ qa_chain = ConversationalRetrievalChain.from_llm(
120
+ llm,
121
+ retriever=retriever,
122
+ chain_type="stuff",
123
+ memory=memory,
124
+ # combine_docs_chain_kwargs={"prompt": your_prompt})
125
+ return_source_documents=True,
126
+ # return_generated_question=True,
127
+ # verbose=True,
128
+ )
129
+ progress(0.9, desc="Done!")
130
+ return qa_chain
131
+
132
+
133
+ # Initialize database
134
+ def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
135
+ # Create list of documents (when valid)
136
+ #file_path = file_obj.name
137
+ list_file_path = [x.name for x in list_file_obj if x is not None]
138
+ # print('list_file_path', list_file_path)
139
+ progress(0.25, desc="Loading document...")
140
+ # Load document and create splits
141
+ doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
142
+ # Create or load Vector database
143
+ progress(0.5, desc="Generating vector database...")
144
+ # global vector_db
145
+ vector_db = create_db(doc_splits)
146
+ progress(0.9, desc="Done!")
147
+ return vector_db, "Complete!"
148
+
149
+
150
+ def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
151
+ # print("llm_option",llm_option)
152
+ llm_name = list_llm[llm_option]
153
+ print("llm_name: ",llm_name)
154
+ qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
155
+ return qa_chain, "Complete!"
156
+
157
+
158
+ def format_chat_history(message, chat_history):
159
+ formatted_chat_history = []
160
+ for user_message, bot_message in chat_history:
161
+ formatted_chat_history.append(f"User: {user_message}")
162
+ formatted_chat_history.append(f"Assistant: {bot_message}")
163
+ return formatted_chat_history
164
+
165
+
166
+ def conversation(qa_chain, message, history):
167
+ formatted_chat_history = format_chat_history(message, history)
168
+ #print("formatted_chat_history",formatted_chat_history)
169
+
170
+ # Generate response using QA chain
171
+ response = qa_chain({"question": message, "chat_history": formatted_chat_history})
172
+ response_answer = response["answer"]
173
+ response_sources = response["source_documents"]
174
+ response_source1 = response_sources[0].page_content.strip()
175
+ response_source2 = response_sources[1].page_content.strip()
176
+ # Langchain sources are zero-based
177
+ response_source1_page = response_sources[0].metadata["page"] + 1
178
+ response_source2_page = response_sources[1].metadata["page"] + 1
179
+ # print ('chat response: ', response_answer)
180
+ # print('DB source', response_sources)
181
+
182
+ # Append user message and response to chat history
183
+ new_history = history + [(message, response_answer)]
184
+ # return gr.update(value=""), new_history, response_sources[0], response_sources[1]
185
+ return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page
186
+
187
+
188
+ def upload_file(file_obj):
189
+ list_file_path = []
190
+ for idx, file in enumerate(file_obj):
191
+ file_path = file_obj.name
192
+ list_file_path.append(file_path)
193
+ # print(file_path)
194
+ # initialize_database(file_path, progress)
195
+ return list_file_path
196
+
197
+
198
+ def demo():
199
+ with gr.Blocks(theme="base") as demo:
200
+ vector_db = gr.State()
201
+ qa_chain = gr.State()
202
+
203
+ gr.Markdown(
204
+ """<center><h2>PDF-based chatbot (powered by LangChain and open-source LLMs)</center></h2>
205
+ <h3>Ask any questions about your PDF documents, along with follow-ups</h3>
206
+ <b>Note:</b> This AI assistant performs retrieval-augmented generation from your PDF documents. \
207
+ When generating answers, it takes past questions into account (via conversational memory), and includes document references for clarity purposes.</i>
208
+ <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>
209
+ """)
210
+ with gr.Tab("Step 1 - Document pre-processing"):
211
+ with gr.Row():
212
+ document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
213
+ # upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)
214
+ with gr.Row():
215
+ db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")
216
+ with gr.Accordion("Advanced options - Document text splitter", open=False):
217
+ with gr.Row():
218
+ slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)
219
+ with gr.Row():
220
+ slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
221
+ with gr.Row():
222
+ db_progress = gr.Textbox(label="Vector database initialization", value="None")
223
+ with gr.Row():
224
+ db_btn = gr.Button("Generate vector database...")
225
+
226
+ with gr.Tab("Step 2 - QA chain initialization"):
227
+ with gr.Row():
228
+ llm_btn = gr.Radio(list_llm_simple, \
229
+ label="LLM models", value = list_llm_simple[0], type="index", info="Choose your LLM model")
230
+ with gr.Accordion("Advanced options - LLM model", open=False):
231
+ with gr.Row():
232
+ slider_temperature = gr.Slider(minimum = 0.0, maximum = 1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
233
+ with gr.Row():
234
+ slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
235
+ with gr.Row():
236
+ slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
237
+ with gr.Row():
238
+ llm_progress = gr.Textbox(value="None",label="QA chain initialization")
239
+ with gr.Row():
240
+ qachain_btn = gr.Button("Initialize question-answering chain...")
241
+
242
+ with gr.Tab("Step 3 - Conversation with chatbot"):
243
+ chatbot = gr.Chatbot(height=300)
244
+ with gr.Accordion("Advanced - Document references", open=False):
245
+ with gr.Row():
246
+ doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
247
+ source1_page = gr.Number(label="Page", scale=1)
248
+ with gr.Row():
249
+ doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
250
+ source2_page = gr.Number(label="Page", scale=1)
251
+ with gr.Row():
252
+ msg = gr.Textbox(placeholder="Type message", container=True)
253
+ with gr.Row():
254
+ submit_btn = gr.Button("Submit")
255
+ clear_btn = gr.ClearButton([msg, chatbot])
256
+
257
+ # Preprocessing events
258
+ #upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])
259
+ db_btn.click(initialize_database, \
260
+ inputs=[document, slider_chunk_size, slider_chunk_overlap], \
261
+ outputs=[vector_db, db_progress])
262
+ qachain_btn.click(initialize_LLM, \
263
+ inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
264
+ outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0], \
265
+ inputs=None, \
266
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page], \
267
+ queue=False)
268
+
269
+ # Chatbot events
270
+ msg.submit(conversation, \
271
+ inputs=[qa_chain, msg, chatbot], \
272
+ outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page], \
273
+ queue=False)
274
+ submit_btn.click(conversation, \
275
+ inputs=[qa_chain, msg, chatbot], \
276
+ outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page], \
277
+ queue=False)
278
+ clear_btn.click(lambda:[None,"",0,"",0], \
279
+ inputs=None, \
280
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page], \
281
+ queue=False)
282
+ demo.queue().launch(debug=True)
283
+
284
+
285
+ if __name__ == "__main__":
286
+ demo()
readme.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ https://huggingface.co/spaces/cvachet/pdf-chatbot/tree/main
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ sentence-transformers
4
+ langchain
5
+ tqdm
6
+ accelerate
7
+ pypdf
8
+ chromadb