TheMaisk commited on
Commit
5d5c492
·
1 Parent(s): 8d086e8

Rename demo_docs to app.py

Browse files
Files changed (2) hide show
  1. app.py +274 -0
  2. demo_docs +0 -0
app.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Warning: 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
+ llm = HuggingFaceHub(
96
+ repo_id=llm_model,
97
+ model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k,\
98
+ "trust_remote_code": True, "torch_dtype": "auto"}
99
+ )
100
+
101
+ progress(0.75, desc="Defining buffer memory...")
102
+ memory = ConversationBufferMemory(
103
+ memory_key="chat_history",
104
+ output_key='answer',
105
+ return_messages=True
106
+ )
107
+ # retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})
108
+ retriever=vector_db.as_retriever()
109
+ progress(0.8, desc="Defining retrieval chain...")
110
+ qa_chain = ConversationalRetrievalChain.from_llm(
111
+ llm,
112
+ retriever=retriever,
113
+ chain_type="stuff",
114
+ memory=memory,
115
+ # combine_docs_chain_kwargs={"prompt": your_prompt})
116
+ return_source_documents=True,
117
+ # return_generated_question=True,
118
+ # verbose=True,
119
+ )
120
+ progress(0.9, desc="Done!")
121
+ return qa_chain
122
+
123
+
124
+ # Initialize database
125
+ def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
126
+ # Create list of documents (when valid)
127
+ #file_path = file_obj.name
128
+ list_file_path = [x.name for x in list_file_obj if x is not None]
129
+ # print('list_file_path', list_file_path)
130
+ progress(0.25, desc="Loading document...")
131
+ # Load document and create splits
132
+ doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
133
+ # Create or load Vector database
134
+ progress(0.5, desc="Generating vector database...")
135
+ # global vector_db
136
+ vector_db = create_db(doc_splits)
137
+ progress(0.9, desc="Done!")
138
+ return vector_db, "Complete!"
139
+
140
+
141
+ def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
142
+ # print("llm_option",llm_option)
143
+ llm_name = list_llm[llm_option]
144
+ # print("llm_name",llm_name)
145
+ qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
146
+ return qa_chain, "Complete!"
147
+
148
+
149
+ def format_chat_history(message, chat_history):
150
+ formatted_chat_history = []
151
+ for user_message, bot_message in chat_history:
152
+ formatted_chat_history.append(f"User: {user_message}")
153
+ formatted_chat_history.append(f"Assistant: {bot_message}")
154
+ return formatted_chat_history
155
+
156
+
157
+ def conversation(qa_chain, message, history):
158
+ formatted_chat_history = format_chat_history(message, history)
159
+ #print("formatted_chat_history",formatted_chat_history)
160
+
161
+ # Generate response using QA chain
162
+ response = qa_chain({"question": message, "chat_history": formatted_chat_history})
163
+ response_answer = response["answer"]
164
+ response_sources = response["source_documents"]
165
+ response_source1 = response_sources[0].page_content.strip()
166
+ response_source2 = response_sources[1].page_content.strip()
167
+ # Langchain sources are zero-based
168
+ response_source1_page = response_sources[0].metadata["page"] + 1
169
+ response_source2_page = response_sources[1].metadata["page"] + 1
170
+ # print ('chat response: ', response_answer)
171
+ # print('DB source', response_sources)
172
+
173
+ # Append user message and response to chat history
174
+ new_history = history + [(message, response_answer)]
175
+ # return gr.update(value=""), new_history, response_sources[0], response_sources[1]
176
+ return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page
177
+
178
+
179
+ def upload_file(file_obj):
180
+ list_file_path = []
181
+ for idx, file in enumerate(file_obj):
182
+ file_path = file_obj.name
183
+ list_file_path.append(file_path)
184
+ # print(file_path)
185
+ # initialize_database(file_path, progress)
186
+ return list_file_path
187
+
188
+
189
+ def demo():
190
+ with gr.Blocks(theme="base") as demo:
191
+ vector_db = gr.State()
192
+ qa_chain = gr.State()
193
+
194
+ gr.Markdown(
195
+ """<center><h2>PDF-based chatbot (powered by LangChain and open-source LLMs)</center></h2>
196
+ <h3>Ask any questions about your PDF documents, along with follow-ups</h3>
197
+ <b>Note:</b> This AI assistant performs retrieval-augmented generation from your PDF documents. \
198
+ When generating answers, it takes past questions into account (via conversational memory), and includes document references for clarity purposes.</i>
199
+ <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>
200
+ """)
201
+ with gr.Tab("Step 1 - Document pre-processing"):
202
+ with gr.Row():
203
+ document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
204
+ # upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)
205
+ with gr.Row():
206
+ db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")
207
+ with gr.Accordion("Advanced options - Document text splitter", open=False):
208
+ with gr.Row():
209
+ slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)
210
+ with gr.Row():
211
+ slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
212
+ with gr.Row():
213
+ db_progress = gr.Textbox(label="Vector database initialization", value="None")
214
+ with gr.Row():
215
+ db_btn = gr.Button("Generating vector database...")
216
+
217
+ with gr.Tab("Step 2 - QA chain initialization"):
218
+ with gr.Row():
219
+ llm_btn = gr.Radio(list_llm_simple, \
220
+ label="LLM models", value = list_llm_simple[0], type="index", info="Choose your LLM model")
221
+ with gr.Accordion("Advanced options - LLM model", open=False):
222
+ slider_temperature = gr.Slider(minimum = 0.0, maximum = 1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
223
+ slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
224
+ slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
225
+ with gr.Row():
226
+ llm_progress = gr.Textbox(value="None",label="QA chain initialization")
227
+ with gr.Row():
228
+ qachain_btn = gr.Button("Initializing question-answering chain...")
229
+
230
+ with gr.Tab("Step 3 - Conversation with chatbot"):
231
+ chatbot = gr.Chatbot(height=300)
232
+ with gr.Accordion("Advanced - Document references", open=False):
233
+ with gr.Row():
234
+ doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
235
+ source1_page = gr.Number(label="Page", scale=1)
236
+ with gr.Row():
237
+ doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
238
+ source2_page = gr.Number(label="Page", scale=1)
239
+ with gr.Row():
240
+ msg = gr.Textbox(placeholder="Type message", container=True)
241
+ with gr.Row():
242
+ submit_btn = gr.Button("Submit")
243
+ clear_btn = gr.ClearButton([msg, chatbot])
244
+
245
+ # Preprocessing events
246
+ #upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])
247
+ db_btn.click(initialize_database, \
248
+ inputs=[document, slider_chunk_size, slider_chunk_overlap], \
249
+ outputs=[vector_db, db_progress])
250
+ qachain_btn.click(initialize_LLM, \
251
+ inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
252
+ outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0], \
253
+ inputs=None, \
254
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page], \
255
+ queue=False)
256
+
257
+ # Chatbot events
258
+ msg.submit(conversation, \
259
+ inputs=[qa_chain, msg, chatbot], \
260
+ outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page], \
261
+ queue=False)
262
+ submit_btn.click(conversation, \
263
+ inputs=[qa_chain, msg, chatbot], \
264
+ outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page], \
265
+ queue=False)
266
+ clear_btn.click(lambda:[None,"",0,"",0], \
267
+ inputs=None, \
268
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page], \
269
+ queue=False)
270
+ demo.queue().launch(debug=True)
271
+
272
+
273
+ if __name__ == "__main__":
274
+ demo()
demo_docs DELETED
File without changes