vishwask commited on
Commit
fb9a319
·
verified ·
1 Parent(s): 193d572

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -38
app.py CHANGED
@@ -20,13 +20,6 @@ import torch
20
  import tqdm
21
  import accelerate
22
 
23
- #set parameters
24
- slider_chunk_size = 4096
25
- slider_chunk_overlap = 256
26
- slider_temperature = 0.1
27
- slider_maxtokens = 2048
28
- slider_topk = 3
29
- llm_model = "mistralai/Mistral-7B-Instruct-v0.2"
30
 
31
 
32
  # default_persist_directory = './chroma_HF/'
@@ -79,13 +72,63 @@ def load_db():
79
 
80
 
81
  # Initialize langchain LLM chain
82
- def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db):
83
- llm = HuggingFaceHub(repo_id=llm_model, model_kwargs={"temperature":
84
- temperature, "max_new_tokens":
85
- max_tokens, "top_k": top_k,
86
- "load_in_8bit": True})
87
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
 
89
  memory = ConversationBufferMemory(
90
  memory_key="chat_history",
91
  output_key='answer',
@@ -93,6 +136,7 @@ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db):
93
  )
94
  # retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})
95
  retriever=vector_db.as_retriever()
 
96
  qa_chain = ConversationalRetrievalChain.from_llm(
97
  llm,
98
  retriever=retriever,
@@ -103,14 +147,16 @@ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db):
103
  #return_generated_question=False,
104
  verbose=False,
105
  )
 
106
  return qa_chain
107
 
108
 
109
  # Initialize database
110
- def initialize_database(list_file_obj, chunk_size, chunk_overlap):
111
  # Create list of documents (when valid)
112
  list_file_path = [x.name for x in list_file_obj if x is not None]
113
  # Create collection_name for vector database
 
114
  collection_name = Path(list_file_path[0]).stem
115
  # Fix potential issues from naming convention
116
  ## Remove space
@@ -124,20 +170,23 @@ def initialize_database(list_file_obj, chunk_size, chunk_overlap):
124
  collection_name[-1] = 'Z'
125
  # print('list_file_path: ', list_file_path)
126
  print('Collection name: ', collection_name)
 
127
  # Load document and create splits
128
  doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
129
  # Create or load vector database
 
130
  # global vector_db
131
  vector_db = create_db(doc_splits, collection_name)
132
- return vector_db, collection_name
 
133
 
134
 
135
- def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db):
136
  # print("llm_option",llm_option)
137
  llm_name = list_llm[llm_option]
138
  print("llm_name: ",llm_name)
139
  qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
140
- return qa_chain
141
 
142
 
143
  def format_chat_history(message, chat_history):
@@ -171,7 +220,7 @@ def conversation(qa_chain, message, history):
171
  # Append user message and response to chat history
172
  new_history = history + [(message, response_answer)]
173
  # return gr.update(value=""), new_history, response_sources[0], response_sources[1]
174
- return qa_chain, new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
175
 
176
 
177
  def upload_file(file_obj):
@@ -189,35 +238,71 @@ def demo():
189
  vector_db = gr.State()
190
  qa_chain = gr.State()
191
  collection_name = gr.State()
192
-
193
- document = gr.Files(value = '/home/user/app/pdfs/Annual-Report-2022-2023-English_1.pdf',visible=False,height=100, file_count="multiple", file_types=["pdf"])
194
- chatbot = gr.Chatbot(height=300)
195
- db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database", visible=False)
196
- with gr.Accordion("Document references", open=False):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  with gr.Row():
198
- doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
199
- source1_page = gr.Number(label="Page", scale=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  with gr.Row():
201
- doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
202
- source2_page = gr.Number(label="Page", scale=1)
203
  with gr.Row():
204
- doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
205
- source3_page = gr.Number(label="Page", scale=1)
206
- with gr.Row():
207
- msg = gr.Textbox(placeholder="Type message", container=True)
208
- with gr.Row():
209
- db_btn = gr.Button("Generate vector database...")
210
- qachain_btn = gr.Button("Initialize question-answering chain...")
211
- submit_btn = gr.Button("Submit")
212
- clear_btn = gr.ClearButton([msg, chatbot])
213
 
214
  # Preprocessing events
215
  #upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])
216
  db_btn.click(initialize_database, \
217
  inputs=[document, slider_chunk_size, slider_chunk_overlap], \
218
- outputs=[vector_db, collection_name])
219
  qachain_btn.click(initialize_LLM, \
220
- inputs=[llm_model, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
221
  outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0], \
222
  inputs=None, \
223
  outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
 
20
  import tqdm
21
  import accelerate
22
 
 
 
 
 
 
 
 
23
 
24
 
25
  # default_persist_directory = './chroma_HF/'
 
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',
 
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,
 
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
 
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):
 
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):
 
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], \