roshithindia commited on
Commit
f03da9f
·
verified ·
1 Parent(s): 0c720e6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +301 -0
app.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+
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
+
14
+ from pathlib import Path
15
+ import chromadb
16
+ from unidecode import unidecode
17
+
18
+ from transformers import AutoTokenizer
19
+ import transformers
20
+ import torch
21
+ import tqdm
22
+ import accelerate
23
+ import re
24
+
25
+
26
+
27
+ # default_persist_directory = './chroma_HF/'
28
+ list_llm = ["mistralai/Mixtral-8x7B-Instruct-v0.1"]
29
+ list_llm_simple = [os.path.basename(llm) for llm in list_llm]
30
+
31
+
32
+ def load_doc(list_file_path, chunk_size, chunk_overlap):
33
+
34
+ loaders = [PyPDFLoader(x) for x in list_file_path]
35
+ pages = []
36
+ for loader in loaders:
37
+ pages.extend(loader.load())
38
+
39
+ text_splitter = RecursiveCharacterTextSplitter(
40
+ chunk_size = chunk_size,
41
+ chunk_overlap = chunk_overlap)
42
+ doc_splits = text_splitter.split_documents(pages)
43
+ return doc_splits
44
+
45
+
46
+ # Create vector database
47
+ def create_db(splits, collection_name):
48
+ embedding = HuggingFaceEmbeddings()
49
+ new_client = chromadb.EphemeralClient()
50
+ vectordb = Chroma.from_documents(
51
+ documents=splits,
52
+ embedding=embedding,
53
+ client=new_client,
54
+ collection_name=collection_name,
55
+ # persist_directory=default_persist_directory
56
+ )
57
+ return vectordb
58
+
59
+
60
+ # Load vector database
61
+ def load_db():
62
+ embedding = HuggingFaceEmbeddings()
63
+ vectordb = Chroma(
64
+ # persist_directory=default_persist_directory,
65
+ embedding_function=embedding)
66
+ return vectordb
67
+
68
+
69
+ # Initialize langchain LLM chain
70
+ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
71
+ progress(0.1, desc="Initializing HF tokenizer...")
72
+
73
+ progress(0.5, desc="Initializing HF Hub...")
74
+
75
+ if llm_model == "mistralai/Mixtral-8x7B-Instruct-v0.1":
76
+ llm = HuggingFaceEndpoint(
77
+ repo_id=llm_model,
78
+
79
+ temperature = temperature,
80
+ max_new_tokens = max_tokens,
81
+ top_k = top_k,
82
+ load_in_8bit = True,
83
+ )
84
+
85
+ progress(0.75, desc="Defining buffer memory...")
86
+ memory = ConversationBufferMemory(
87
+ memory_key="chat_history",
88
+ output_key='answer',
89
+ return_messages=True
90
+ )
91
+
92
+ retriever=vector_db.as_retriever()
93
+ progress(0.8, desc="Defining retrieval chain...")
94
+ qa_chain = ConversationalRetrievalChain.from_llm(
95
+ llm,
96
+ retriever=retriever,
97
+ chain_type="stuff",
98
+ memory=memory,
99
+
100
+ return_source_documents=True,
101
+
102
+ verbose=False,
103
+ )
104
+ progress(0.9, desc="Done!")
105
+ return qa_chain
106
+
107
+
108
+ # Generate collection name for vector database
109
+ # - Use filepath as input, ensuring unicode text
110
+ def create_collection_name(filepath):
111
+ # Extract filename without extension
112
+ collection_name = Path(filepath).stem
113
+
114
+ collection_name = collection_name.replace(" ","-")
115
+ ## ASCII transliterations of Unicode text
116
+ collection_name = unidecode(collection_name)
117
+
118
+ collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
119
+ ## Limit length to 50 characters
120
+ collection_name = collection_name[:50]
121
+ ## Minimum length of 3 characters
122
+ if len(collection_name) < 3:
123
+ collection_name = collection_name + 'xyz'
124
+ ## Enforce start and end as alphanumeric character
125
+ if not collection_name[0].isalnum():
126
+ collection_name = 'A' + collection_name[1:]
127
+ if not collection_name[-1].isalnum():
128
+ collection_name = collection_name[:-1] + 'Z'
129
+ print('Filepath: ', filepath)
130
+ print('Collection name: ', collection_name)
131
+ return collection_name
132
+
133
+
134
+ # Initialize database
135
+ def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
136
+ # Create list of documents (when valid)
137
+ list_file_path = [x.name for x in list_file_obj if x is not None]
138
+ # Create collection_name for vector database
139
+ progress(0.1, desc="Creating collection name...")
140
+ collection_name = create_collection_name(list_file_path[0])
141
+ progress(0.25, desc="Loading document...")
142
+ # Load document and create splits
143
+ doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
144
+ # Create or load vector database
145
+ progress(0.5, desc="Generating vector database...")
146
+ # global vector_db
147
+ vector_db = create_db(doc_splits, collection_name)
148
+ progress(0.9, desc="Done!")
149
+ return vector_db, collection_name, "Complete!"
150
+
151
+
152
+ def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
153
+ # print("llm_option",llm_option)
154
+ llm_name = list_llm[llm_option]
155
+ print("llm_name: ",llm_name)
156
+ qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
157
+ return qa_chain, "Complete!"
158
+
159
+
160
+ def format_chat_history(message, chat_history):
161
+ formatted_chat_history = []
162
+ for user_message, bot_message in chat_history:
163
+ formatted_chat_history.append(f"User: {user_message}")
164
+ formatted_chat_history.append(f"Assistant: {bot_message}")
165
+ return formatted_chat_history
166
+
167
+
168
+ def conversation(qa_chain, message, history):
169
+ formatted_chat_history = format_chat_history(message, history)
170
+ #print("formatted_chat_history",formatted_chat_history)
171
+
172
+ # Generate response using QA chain
173
+ response = qa_chain({"question": message, "chat_history": formatted_chat_history})
174
+ response_answer = response["answer"]
175
+ if response_answer.find("Helpful Answer:") != -1:
176
+ response_answer = response_answer.split("Helpful Answer:")[-1]
177
+ response_sources = response["source_documents"]
178
+ response_source1 = response_sources[0].page_content.strip()
179
+ response_source2 = response_sources[1].page_content.strip()
180
+ response_source3 = response_sources[2].page_content.strip()
181
+ # Langchain sources are zero-based
182
+ response_source1_page = response_sources[0].metadata["page"] + 1
183
+ response_source2_page = response_sources[1].metadata["page"] + 1
184
+ response_source3_page = response_sources[2].metadata["page"] + 1
185
+ # print ('chat response: ', response_answer)
186
+ # print('DB source', response_sources)
187
+
188
+ # Append user message and response to chat history
189
+ new_history = history + [(message, response_answer)]
190
+ # return gr.update(value=""), new_history, response_sources[0], response_sources[1]
191
+ return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
192
+
193
+
194
+ def upload_file(file_obj):
195
+ list_file_path = []
196
+ for idx, file in enumerate(file_obj):
197
+ file_path = file_obj.name
198
+ list_file_path.append(file_path)
199
+ # print(file_path)
200
+ # initialize_database(file_path, progress)
201
+ return list_file_path
202
+
203
+
204
+ def demo():
205
+ with gr.Blocks(theme="base") as demo:
206
+ vector_db = gr.State()
207
+ qa_chain = gr.State()
208
+ collection_name = gr.State()
209
+
210
+ gr.Markdown(
211
+ """<center><h2>PDF-based chatbot</center></h2>
212
+ <h3>Ask any questions about your PDF documents</h3>""")
213
+ gr.Markdown(
214
+ """<b>Note:</b> This AI assistant, using Langchain and open-source LLMs, performs retrieval-augmented generation (RAG) from your PDF documents. \
215
+ The user interface explicitely shows multiple steps to help understand the RAG workflow.
216
+ This chatbot takes past questions into account when generating answers (via conversational memory), and includes document references for clarity purposes.<br>
217
+ <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 a reply.
218
+ """)
219
+
220
+ with gr.Tab("Step 1 - Upload PDF"):
221
+ with gr.Row():
222
+ document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
223
+ # upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)
224
+
225
+ with gr.Tab("Step 2 - Process document"):
226
+ with gr.Row():
227
+ db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")
228
+ with gr.Accordion("Advanced options - Document text splitter", open=False):
229
+ with gr.Row():
230
+ slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)
231
+ with gr.Row():
232
+ slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
233
+ with gr.Row():
234
+ db_progress = gr.Textbox(label="Vector database initialization", value="None")
235
+ with gr.Row():
236
+ db_btn = gr.Button("Generate vector database")
237
+
238
+ with gr.Tab("Step 3 - Initialize QA chain"):
239
+ with gr.Row():
240
+ llm_btn = gr.Radio(list_llm_simple, \
241
+ label="LLM models", value = list_llm_simple[0], type="index", info="Choose your LLM model")
242
+ with gr.Accordion("Advanced options - LLM model", open=False):
243
+ with gr.Row():
244
+ slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
245
+ with gr.Row():
246
+ slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
247
+ with gr.Row():
248
+ slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
249
+ with gr.Row():
250
+ llm_progress = gr.Textbox(value="None",label="QA chain initialization")
251
+ with gr.Row():
252
+ qachain_btn = gr.Button("Initialize Question Answering chain")
253
+
254
+ with gr.Tab("Step 4 - Chatbot"):
255
+ chatbot = gr.Chatbot(height=300)
256
+ with gr.Accordion("Advanced - Document references", open=False):
257
+ with gr.Row():
258
+ doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
259
+ source1_page = gr.Number(label="Page", scale=1)
260
+ with gr.Row():
261
+ doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
262
+ source2_page = gr.Number(label="Page", scale=1)
263
+ with gr.Row():
264
+ doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
265
+ source3_page = gr.Number(label="Page", scale=1)
266
+ with gr.Row():
267
+ msg = gr.Textbox(placeholder="Type message (e.g. 'What is this document about?')", container=True)
268
+ with gr.Row():
269
+ submit_btn = gr.Button("Submit message")
270
+ clear_btn = gr.ClearButton([msg, chatbot], value="Clear conversation")
271
+
272
+ # Preprocessing events
273
+ #upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])
274
+ db_btn.click(initialize_database, \
275
+ inputs=[document, slider_chunk_size, slider_chunk_overlap], \
276
+ outputs=[vector_db, collection_name, db_progress])
277
+ qachain_btn.click(initialize_LLM, \
278
+ inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
279
+ outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0], \
280
+ inputs=None, \
281
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
282
+ queue=False)
283
+
284
+ # Chatbot events
285
+ msg.submit(conversation, \
286
+ inputs=[qa_chain, msg, chatbot], \
287
+ outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
288
+ queue=False)
289
+ submit_btn.click(conversation, \
290
+ inputs=[qa_chain, msg, chatbot], \
291
+ outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
292
+ queue=False)
293
+ clear_btn.click(lambda:[None,"",0,"",0,"",0], \
294
+ inputs=None, \
295
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
296
+ queue=False)
297
+ demo.queue().launch(debug=True)
298
+
299
+
300
+ if __name__ == "__main__":
301
+ demo()