yogesh69 commited on
Commit
495873b
·
verified ·
1 Parent(s): c2fd9e7

Upload app (2) (1).py

Browse files
Files changed (1) hide show
  1. app (2) (1).py +383 -0
app (2) (1).py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, AutoModelForMaskedLM
19
+ import transformers
20
+ import torch
21
+ import tqdm
22
+ import accelerate
23
+ import re
24
+
25
+ # Load the tokenizer and model
26
+ tokenizer = AutoTokenizer.from_pretrained("google/muril-base-cased")
27
+ model = AutoModelForMaskedLM.from_pretrained("google/muril-base-cased")
28
+
29
+ # default_persist_directory = './chroma_HF/'
30
+ list_llm = ["mistralai/Mistral-7B-Instruct-v0.2", "mistralai/Mixtral-8x7B-Instruct-v0.1", "mistralai/Mistral-7B-Instruct-v0.1", \
31
+ "google/gemma-7b-it","google/gemma-2b-it", \
32
+ "HuggingFaceH4/zephyr-7b-beta", "HuggingFaceH4/zephyr-7b-gemma-v0.1", \
33
+ "meta-llama/Llama-2-7b-chat-hf", "microsoft/phi-2", \
34
+ "TinyLlama/TinyLlama-1.1B-Chat-v1.0", "mosaicml/mpt-7b-instruct", "tiiuae/falcon-7b-instruct", \
35
+ "google/flan-t5-xxl"
36
+ ]
37
+ list_llm_simple = [os.path.basename(llm) for llm in list_llm]
38
+
39
+ # Load PDF document and create doc splits
40
+ def load_doc(list_file_path, chunk_size, chunk_overlap):
41
+ # Processing for one document only
42
+ # loader = PyPDFLoader(file_path)
43
+ # pages = loader.load()
44
+ loaders = [PyPDFLoader(x) for x in list_file_path]
45
+ pages = []
46
+ for loader in loaders:
47
+ pages.extend(loader.load())
48
+ # text_splitter = RecursiveCharacterTextSplitter(chunk_size = 600, chunk_overlap = 50)
49
+ text_splitter = RecursiveCharacterTextSplitter(
50
+ chunk_size = chunk_size,
51
+ chunk_overlap = chunk_overlap)
52
+ doc_splits = text_splitter.split_documents(pages)
53
+ return doc_splits
54
+
55
+ # The rest of your code continues here...
56
+
57
+
58
+
59
+ # Create vector database
60
+ def create_db(splits, collection_name):
61
+ embedding = HuggingFaceEmbeddings()
62
+ new_client = chromadb.EphemeralClient()
63
+ vectordb = Chroma.from_documents(
64
+ documents=splits,
65
+ embedding=embedding,
66
+ client=new_client,
67
+ collection_name=collection_name,
68
+ # persist_directory=default_persist_directory
69
+ )
70
+ return vectordb
71
+
72
+
73
+ # Load vector database
74
+ def load_db():
75
+ embedding = HuggingFaceEmbeddings()
76
+ vectordb = Chroma(
77
+ # persist_directory=default_persist_directory,
78
+ embedding_function=embedding)
79
+ return vectordb
80
+
81
+
82
+ # Initialize langchain LLM chain
83
+ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
84
+ progress(0.1, desc="Initializing HF tokenizer...")
85
+ # HuggingFacePipeline uses local model
86
+ # Note: it will download model locally...
87
+ # tokenizer=AutoTokenizer.from_pretrained(llm_model)
88
+ # progress(0.5, desc="Initializing HF pipeline...")
89
+ # pipeline=transformers.pipeline(
90
+ # "text-generation",
91
+ # model=llm_model,
92
+ # tokenizer=tokenizer,
93
+ # torch_dtype=torch.bfloat16,
94
+ # trust_remote_code=True,
95
+ # device_map="auto",
96
+ # # max_length=1024,
97
+ # max_new_tokens=max_tokens,
98
+ # do_sample=True,
99
+ # top_k=top_k,
100
+ # num_return_sequences=1,
101
+ # eos_token_id=tokenizer.eos_token_id
102
+ # )
103
+ # llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature': temperature})
104
+
105
+ # HuggingFaceHub uses HF inference endpoints
106
+ progress(0.5, desc="Initializing HF Hub...")
107
+ # Use of trust_remote_code as model_kwargs
108
+ # Warning: langchain issue
109
+ # URL: https://github.com/langchain-ai/langchain/issues/6080
110
+ if llm_model == "mistralai/Mixtral-8x7B-Instruct-v0.1":
111
+ llm = HuggingFaceEndpoint(
112
+ repo_id=llm_model,
113
+ # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "load_in_8bit": True}
114
+ temperature = temperature,
115
+ max_new_tokens = max_tokens,
116
+ top_k = top_k,
117
+ load_in_8bit = True,
118
+ )
119
+ elif llm_model in ["HuggingFaceH4/zephyr-7b-gemma-v0.1","mosaicml/mpt-7b-instruct"]:
120
+ raise gr.Error("LLM model is too large to be loaded automatically on free inference endpoint")
121
+ llm = HuggingFaceEndpoint(
122
+ repo_id=llm_model,
123
+ temperature = temperature,
124
+ max_new_tokens = max_tokens,
125
+ top_k = top_k,
126
+ )
127
+ elif llm_model == "microsoft/phi-2":
128
+ # raise gr.Error("phi-2 model requires 'trust_remote_code=True', currently not supported by langchain HuggingFaceHub...")
129
+ llm = HuggingFaceEndpoint(
130
+ repo_id=llm_model,
131
+ # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
132
+ temperature = temperature,
133
+ max_new_tokens = max_tokens,
134
+ top_k = top_k,
135
+ trust_remote_code = True,
136
+ torch_dtype = "auto",
137
+ )
138
+ elif llm_model == "TinyLlama/TinyLlama-1.1B-Chat-v1.0":
139
+ llm = HuggingFaceEndpoint(
140
+ repo_id=llm_model,
141
+ # model_kwargs={"temperature": temperature, "max_new_tokens": 250, "top_k": top_k}
142
+ temperature = temperature,
143
+ max_new_tokens = 250,
144
+ top_k = top_k,
145
+ )
146
+ elif llm_model == "meta-llama/Llama-2-7b-chat-hf":
147
+ raise gr.Error("Llama-2-7b-chat-hf model requires a Pro subscription...")
148
+ llm = HuggingFaceEndpoint(
149
+ repo_id=llm_model,
150
+ # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
151
+ temperature = temperature,
152
+ max_new_tokens = max_tokens,
153
+ top_k = top_k,
154
+ )
155
+ else:
156
+ llm = HuggingFaceEndpoint(
157
+ repo_id=llm_model,
158
+ # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
159
+ # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
160
+ temperature = temperature,
161
+ max_new_tokens = max_tokens,
162
+ top_k = top_k,
163
+ )
164
+
165
+ progress(0.75, desc="Defining buffer memory...")
166
+ memory = ConversationBufferMemory(
167
+ memory_key="chat_history",
168
+ output_key='answer',
169
+ return_messages=True
170
+ )
171
+ # retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})
172
+ retriever=vector_db.as_retriever()
173
+ progress(0.8, desc="Defining retrieval chain...")
174
+ qa_chain = ConversationalRetrievalChain.from_llm(
175
+ llm,
176
+ retriever=retriever,
177
+ chain_type="stuff",
178
+ memory=memory,
179
+ # combine_docs_chain_kwargs={"prompt": your_prompt})
180
+ return_source_documents=True,
181
+ #return_generated_question=False,
182
+ verbose=False,
183
+ )
184
+ progress(0.9, desc="Done!")
185
+ return qa_chain
186
+
187
+
188
+ # Generate collection name for vector database
189
+ # - Use filepath as input, ensuring unicode text
190
+ def create_collection_name(filepath):
191
+ # Extract filename without extension
192
+ collection_name = Path(filepath).stem
193
+ # Fix potential issues from naming convention
194
+ ## Remove space
195
+ collection_name = collection_name.replace(" ","-")
196
+ ## ASCII transliterations of Unicode text
197
+ collection_name = unidecode(collection_name)
198
+ ## Remove special characters
199
+ #collection_name = re.findall("[\dA-Za-z]*", collection_name)[0]
200
+ collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
201
+ ## Limit length to 50 characters
202
+ collection_name = collection_name[:50]
203
+ ## Minimum length of 3 characters
204
+ if len(collection_name) < 3:
205
+ collection_name = collection_name + 'xyz'
206
+ ## Enforce start and end as alphanumeric character
207
+ if not collection_name[0].isalnum():
208
+ collection_name = 'A' + collection_name[1:]
209
+ if not collection_name[-1].isalnum():
210
+ collection_name = collection_name[:-1] + 'Z'
211
+ print('Filepath: ', filepath)
212
+ print('Collection name: ', collection_name)
213
+ return collection_name
214
+
215
+
216
+ # Initialize database
217
+ def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
218
+ # Create list of documents (when valid)
219
+ list_file_path = [x.name for x in list_file_obj if x is not None]
220
+ # Create collection_name for vector database
221
+ progress(0.1, desc="Creating collection name...")
222
+ collection_name = create_collection_name(list_file_path[0])
223
+ progress(0.25, desc="Loading document...")
224
+ # Load document and create splits
225
+ doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
226
+ # Create or load vector database
227
+ progress(0.5, desc="Generating vector database...")
228
+ # global vector_db
229
+ vector_db = create_db(doc_splits, collection_name)
230
+ progress(0.9, desc="Done!")
231
+ return vector_db, collection_name, "Complete!"
232
+
233
+
234
+ def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
235
+ # print("llm_option",llm_option)
236
+ llm_name = list_llm[llm_option]
237
+ print("llm_name: ",llm_name)
238
+ qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
239
+ return qa_chain, "Complete!"
240
+
241
+
242
+ def format_chat_history(message, chat_history):
243
+ formatted_chat_history = []
244
+ for user_message, bot_message in chat_history:
245
+ formatted_chat_history.append(f"User: {user_message}")
246
+ formatted_chat_history.append(f"Assistant: {bot_message}")
247
+ return formatted_chat_history
248
+
249
+
250
+ def conversation(qa_chain, message, history):
251
+ formatted_chat_history = format_chat_history(message, history)
252
+ #print("formatted_chat_history",formatted_chat_history)
253
+
254
+ # Generate response using QA chain
255
+ response = qa_chain({"question": message, "chat_history": formatted_chat_history})
256
+ response_answer = response["answer"]
257
+ if response_answer.find("Helpful Answer:") != -1:
258
+ response_answer = response_answer.split("Helpful Answer:")[-1]
259
+ response_sources = response["source_documents"]
260
+ response_source1 = response_sources[0].page_content.strip()
261
+ response_source2 = response_sources[1].page_content.strip()
262
+ response_source3 = response_sources[2].page_content.strip()
263
+ # Langchain sources are zero-based
264
+ response_source1_page = response_sources[0].metadata["page"] + 1
265
+ response_source2_page = response_sources[1].metadata["page"] + 1
266
+ response_source3_page = response_sources[2].metadata["page"] + 1
267
+ # print ('chat response: ', response_answer)
268
+ # print('DB source', response_sources)
269
+
270
+ # Append user message and response to chat history
271
+ new_history = history + [(message, response_answer)]
272
+ # return gr.update(value=""), new_history, response_sources[0], response_sources[1]
273
+ return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
274
+
275
+
276
+ def upload_file(file_obj):
277
+ list_file_path = []
278
+ for idx, file in enumerate(file_obj):
279
+ file_path = file_obj.name
280
+ list_file_path.append(file_path)
281
+ # print(file_path)
282
+ # initialize_database(file_path, progress)
283
+ return list_file_path
284
+
285
+
286
+ def demo():
287
+ with gr.Blocks(theme="base") as demo:
288
+ vector_db = gr.State()
289
+ qa_chain = gr.State()
290
+ collection_name = gr.State()
291
+
292
+ gr.Markdown(
293
+ """<center><h2>PDF-based chatbot</center></h2>
294
+ <h3>Ask any questions about your PDF documents</h3>""")
295
+ gr.Markdown(
296
+ """<b>Note:</b> This AI assistant, using Langchain and open-source LLMs, performs retrieval-augmented generation (RAG) from your PDF documents. \
297
+ The user interface explicitely shows multiple steps to help understand the RAG workflow.
298
+ This chatbot takes past questions into account when generating answers (via conversational memory), and includes document references for clarity purposes.<br>
299
+ <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.
300
+ """)
301
+
302
+ with gr.Tab("Step 1 - Upload PDF"):
303
+ with gr.Row():
304
+ document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
305
+ # upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)
306
+
307
+ with gr.Tab("Step 2 - Process document"):
308
+ with gr.Row():
309
+ db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")
310
+ with gr.Accordion("Advanced options - Document text splitter", open=False):
311
+ with gr.Row():
312
+ slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)
313
+ with gr.Row():
314
+ slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
315
+ with gr.Row():
316
+ db_progress = gr.Textbox(label="Vector database initialization", value="None")
317
+ with gr.Row():
318
+ db_btn = gr.Button("Generate vector database")
319
+
320
+ with gr.Tab("Step 3 - Initialize QA chain"):
321
+ with gr.Row():
322
+ llm_btn = gr.Radio(list_llm_simple, \
323
+ label="LLM models", value = list_llm_simple[0], type="index", info="Choose your LLM model")
324
+ with gr.Accordion("Advanced options - LLM model", open=False):
325
+ with gr.Row():
326
+ slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
327
+ with gr.Row():
328
+ slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
329
+ with gr.Row():
330
+ slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
331
+ with gr.Row():
332
+ llm_progress = gr.Textbox(value="None",label="QA chain initialization")
333
+ with gr.Row():
334
+ qachain_btn = gr.Button("Initialize Question Answering chain")
335
+
336
+ with gr.Tab("Step 4 - Chatbot"):
337
+ chatbot = gr.Chatbot(height=300)
338
+ with gr.Accordion("Advanced - Document references", open=False):
339
+ with gr.Row():
340
+ doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
341
+ source1_page = gr.Number(label="Page", scale=1)
342
+ with gr.Row():
343
+ doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
344
+ source2_page = gr.Number(label="Page", scale=1)
345
+ with gr.Row():
346
+ doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
347
+ source3_page = gr.Number(label="Page", scale=1)
348
+ with gr.Row():
349
+ msg = gr.Textbox(placeholder="Type message (e.g. 'What is this document about?')", container=True)
350
+ with gr.Row():
351
+ submit_btn = gr.Button("Submit message")
352
+ clear_btn = gr.ClearButton([msg, chatbot], value="Clear conversation")
353
+
354
+ # Preprocessing events
355
+ #upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])
356
+ db_btn.click(initialize_database, \
357
+ inputs=[document, slider_chunk_size, slider_chunk_overlap], \
358
+ outputs=[vector_db, collection_name, db_progress])
359
+ qachain_btn.click(initialize_LLM, \
360
+ inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
361
+ outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0], \
362
+ inputs=None, \
363
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
364
+ queue=False)
365
+
366
+ # Chatbot events
367
+ msg.submit(conversation, \
368
+ inputs=[qa_chain, msg, chatbot], \
369
+ outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
370
+ queue=False)
371
+ submit_btn.click(conversation, \
372
+ inputs=[qa_chain, msg, chatbot], \
373
+ outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
374
+ queue=False)
375
+ clear_btn.click(lambda:[None,"",0,"",0,"",0], \
376
+ inputs=None, \
377
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
378
+ queue=False)
379
+ demo.queue().launch(debug=True)
380
+
381
+
382
+ if __name__ == "__main__":
383
+ demo()