barghavani commited on
Commit
9b01105
·
verified ·
1 Parent(s): fa229bd

Update app.py

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