Ubai commited on
Commit
fc1e558
·
verified ·
1 Parent(s): f74a5f5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -210
app.py CHANGED
@@ -20,35 +20,21 @@ import torch
20
  import tqdm
21
  import accelerate
22
 
23
-
24
-
25
- # default_persist_directory = './chroma_HF/'
26
- list_llm = ["mistralai/Mistral-7B-Instruct-v0.2", "mistralai/Mixtral-8x7B-Instruct-v0.1", "mistralai/Mistral-7B-Instruct-v0.1", \
27
- "google/gemma-7b-it","google/gemma-2b-it", \
28
- "HuggingFaceH4/zephyr-7b-beta", "meta-llama/Llama-2-7b-chat-hf", "microsoft/phi-2", \
29
- "TinyLlama/TinyLlama-1.1B-Chat-v1.0", "mosaicml/mpt-7b-instruct", "tiiuae/falcon-7b-instruct", \
30
- "google/flan-t5-xxl"
31
- ]
32
  list_llm_simple = [os.path.basename(llm) for llm in list_llm]
33
 
34
- # Load PDF document and create doc splits
35
  def load_doc(list_file_path, chunk_size, chunk_overlap):
36
- # Processing for one document only
37
- # loader = PyPDFLoader(file_path)
38
- # pages = loader.load()
39
  loaders = [PyPDFLoader(x) for x in list_file_path]
40
  pages = []
41
  for loader in loaders:
42
  pages.extend(loader.load())
43
- # text_splitter = RecursiveCharacterTextSplitter(chunk_size = 600, chunk_overlap = 50)
44
  text_splitter = RecursiveCharacterTextSplitter(
45
- chunk_size = chunk_size,
46
- chunk_overlap = chunk_overlap)
47
  doc_splits = text_splitter.split_documents(pages)
48
  return doc_splits
49
 
50
-
51
- # Create vector database
52
  def create_db(splits, collection_name):
53
  embedding = HuggingFaceEmbeddings()
54
  new_client = chromadb.EphemeralClient()
@@ -57,137 +43,44 @@ def create_db(splits, collection_name):
57
  embedding=embedding,
58
  client=new_client,
59
  collection_name=collection_name,
60
- # persist_directory=default_persist_directory
61
  )
62
  return vectordb
63
 
64
-
65
- # Load vector database
66
- def load_db():
67
- embedding = HuggingFaceEmbeddings()
68
- vectordb = Chroma(
69
- # persist_directory=default_persist_directory,
70
- embedding_function=embedding)
71
- return vectordb
72
-
73
-
74
- # Initialize langchain LLM chain
75
  def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
76
- progress(0.1, desc="Initializing HF tokenizer...")
77
- # HuggingFacePipeline uses local model
78
- # Note: it will download model locally...
79
- # tokenizer=AutoTokenizer.from_pretrained(llm_model)
80
- # progress(0.5, desc="Initializing HF pipeline...")
81
- # pipeline=transformers.pipeline(
82
- # "text-generation",
83
- # model=llm_model,
84
- # tokenizer=tokenizer,
85
- # torch_dtype=torch.bfloat16,
86
- # trust_remote_code=True,
87
- # device_map="auto",
88
- # # max_length=1024,
89
- # max_new_tokens=max_tokens,
90
- # do_sample=True,
91
- # top_k=top_k,
92
- # num_return_sequences=1,
93
- # eos_token_id=tokenizer.eos_token_id
94
- # )
95
- # llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature': temperature})
96
-
97
- # HuggingFaceHub uses HF inference endpoints
98
- progress(0.5, desc="Initializing HF Hub...")
99
- # Use of trust_remote_code as model_kwargs
100
- # Warning: langchain issue
101
- # URL: https://github.com/langchain-ai/langchain/issues/6080
102
- if llm_model == "mistralai/Mixtral-8x7B-Instruct-v0.1":
103
- llm = HuggingFaceHub(
104
- repo_id=llm_model,
105
- model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "load_in_8bit": True}
106
- )
107
- elif llm_model == "microsoft/phi-2":
108
- raise gr.Error("phi-2 model requires 'trust_remote_code=True', currently not supported by langchain HuggingFaceHub...")
109
- llm = HuggingFaceHub(
110
- repo_id=llm_model,
111
- model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
112
- )
113
- elif llm_model == "TinyLlama/TinyLlama-1.1B-Chat-v1.0":
114
- llm = HuggingFaceHub(
115
- repo_id=llm_model,
116
- model_kwargs={"temperature": temperature, "max_new_tokens": 250, "top_k": top_k}
117
- )
118
- elif llm_model == "meta-llama/Llama-2-7b-chat-hf":
119
- raise gr.Error("Llama-2-7b-chat-hf model requires a Pro subscription...")
120
- llm = HuggingFaceHub(
121
- repo_id=llm_model,
122
- model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
123
- )
124
- else:
125
- llm = HuggingFaceHub(
126
- repo_id=llm_model,
127
- # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
128
- model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
129
- )
130
-
131
- progress(0.75, desc="Defining buffer memory...")
132
  memory = ConversationBufferMemory(
133
  memory_key="chat_history",
134
  output_key='answer',
135
  return_messages=True
136
  )
137
- # retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})
138
- retriever=vector_db.as_retriever()
139
- progress(0.8, desc="Defining retrieval chain...")
140
  qa_chain = ConversationalRetrievalChain.from_llm(
141
  llm,
142
  retriever=retriever,
143
  chain_type="stuff",
144
  memory=memory,
145
- # combine_docs_chain_kwargs={"prompt": your_prompt})
146
  return_source_documents=True,
147
- #return_generated_question=False,
148
  verbose=False,
149
  )
150
  progress(0.9, desc="Done!")
151
  return qa_chain
152
 
153
-
154
- # Initialize database
155
- def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
156
- # Create list of documents (when valid)
157
  list_file_path = [x.name for x in list_file_obj if x is not None]
158
- # Create collection_name for vector database
159
- progress(0.1, desc="Creating collection name...")
160
- collection_name = Path(list_file_path[0]).stem
161
- # Fix potential issues from naming convention
162
- ## Remove space
163
- collection_name = collection_name.replace(" ","-")
164
- ## Limit lenght to 50 characters
165
- collection_name = collection_name[:50]
166
- ## Enforce start and end as alphanumeric character
167
- if not collection_name[0].isalnum():
168
- collection_name[0] = 'A'
169
- if not collection_name[-1].isalnum():
170
- collection_name[-1] = 'Z'
171
- # print('list_file_path: ', list_file_path)
172
- print('Collection name: ', collection_name)
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 = []
@@ -195,13 +88,9 @@ def format_chat_history(message, 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:
@@ -210,35 +99,25 @@ def conversation(qa_chain, message, history):
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>
@@ -246,83 +125,21 @@ def demo():
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()
 
20
  import tqdm
21
  import accelerate
22
 
23
+ # Update list of LLM models
24
+ list_llm = ["mistralai/Mistral-7B-Instruct-v0.2"]
 
 
 
 
 
 
 
25
  list_llm_simple = [os.path.basename(llm) for llm in list_llm]
26
 
 
27
  def load_doc(list_file_path, chunk_size, chunk_overlap):
 
 
 
28
  loaders = [PyPDFLoader(x) for x in list_file_path]
29
  pages = []
30
  for loader in loaders:
31
  pages.extend(loader.load())
 
32
  text_splitter = RecursiveCharacterTextSplitter(
33
+ chunk_size=chunk_size,
34
+ chunk_overlap=chunk_overlap)
35
  doc_splits = text_splitter.split_documents(pages)
36
  return doc_splits
37
 
 
 
38
  def create_db(splits, collection_name):
39
  embedding = HuggingFaceEmbeddings()
40
  new_client = chromadb.EphemeralClient()
 
43
  embedding=embedding,
44
  client=new_client,
45
  collection_name=collection_name,
 
46
  )
47
  return vectordb
48
 
 
 
 
 
 
 
 
 
 
 
 
49
  def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
50
+ llm = HuggingFaceHub(
51
+ repo_id=llm_model,
52
+ model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
53
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  memory = ConversationBufferMemory(
55
  memory_key="chat_history",
56
  output_key='answer',
57
  return_messages=True
58
  )
59
+ retriever = vector_db.as_retriever()
 
 
60
  qa_chain = ConversationalRetrievalChain.from_llm(
61
  llm,
62
  retriever=retriever,
63
  chain_type="stuff",
64
  memory=memory,
 
65
  return_source_documents=True,
 
66
  verbose=False,
67
  )
68
  progress(0.9, desc="Done!")
69
  return qa_chain
70
 
71
+ def initialize_database(list_file_obj, chunk_size, chunk_overlap, llm_temperature, max_tokens, top_k, progress=gr.Progress()):
 
 
 
72
  list_file_path = [x.name for x in list_file_obj if x is not None]
73
+ collection_name = Path(list_file_path[0]).stem.replace(" ", "-")[:50]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
 
 
 
75
  vector_db = create_db(doc_splits, collection_name)
76
+ qa_chain = initialize_llmchain(
77
+ list_llm[0],
78
+ llm_temperature,
79
+ max_tokens,
80
+ top_k,
81
+ vector_db,
82
+ progress)
83
+ return vector_db, collection_name, qa_chain, "Complete!"
 
 
 
84
 
85
  def format_chat_history(message, chat_history):
86
  formatted_chat_history = []
 
88
  formatted_chat_history.append(f"User: {user_message}")
89
  formatted_chat_history.append(f"Assistant: {bot_message}")
90
  return formatted_chat_history
 
91
 
92
  def conversation(qa_chain, message, history):
93
  formatted_chat_history = format_chat_history(message, history)
 
 
 
94
  response = qa_chain({"question": message, "chat_history": formatted_chat_history})
95
  response_answer = response["answer"]
96
  if response_answer.find("Helpful Answer:") != -1:
 
99
  response_source1 = response_sources[0].page_content.strip()
100
  response_source2 = response_sources[1].page_content.strip()
101
  response_source3 = response_sources[2].page_content.strip()
 
102
  response_source1_page = response_sources[0].metadata["page"] + 1
103
  response_source2_page = response_sources[1].metadata["page"] + 1
104
  response_source3_page = response_sources[2].metadata["page"] + 1
 
 
 
 
105
  new_history = history + [(message, response_answer)]
 
106
  return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
 
107
 
108
  def upload_file(file_obj):
109
  list_file_path = []
110
  for idx, file in enumerate(file_obj):
111
  file_path = file_obj.name
112
  list_file_path.append(file_path)
 
 
113
  return list_file_path
114
 
 
115
  def demo():
116
  with gr.Blocks(theme="base") as demo:
117
  vector_db = gr.State()
118
  qa_chain = gr.State()
119
  collection_name = gr.State()
120
+
121
  gr.Markdown(
122
  """<center><h2>PDF-based chatbot (powered by LangChain and open-source LLMs)</center></h2>
123
  <h3>Ask any questions about your PDF documents, along with follow-ups</h3>
 
125
  When generating answers, it takes past questions into account (via conversational memory), and includes document references for clarity purposes.</i>
126
  <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>
127
  """)
128
+ with gr.Tab("Chatbot"):
129
  with gr.Row():
130
  document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
131
+ db_btn = gr.Button("Generate vector database...")
 
 
132
  with gr.Accordion("Advanced options - Document text splitter", open=False):
133
  with gr.Row():
134
+ slider_chunk_size = gr.Slider(minimum=100, maximum=1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)
135
  with gr.Row():
136
+ slider_chunk_overlap = gr.Slider(minimum=10, maximum=200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
137
  with gr.Row():
138
  db_progress = gr.Textbox(label="Vector database initialization", value="None")
139
  with gr.Row():
140
+ llm_btn = gr.Radio(list_llm_simple, label="LLM models", value=list_llm_simple[0], type="index", info="Choose your LLM model")
 
 
 
 
 
141
  with gr.Accordion("Advanced options - LLM model", open=False):
142
  with gr.Row():
143
+ slider_temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  with gr.Row():
145
+ slider_maxtokens = gr