vivek9 commited on
Commit
54386a9
·
verified ·
1 Parent(s): 9c722f0

Upload 2 files

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