amraly1983 commited on
Commit
5b6f5f1
1 Parent(s): 10fc421

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -141
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import gradio as gr
2
  import os
3
  from dotenv import load_dotenv
4
-
5
  from langchain_community.document_loaders import PyPDFLoader
6
  from langchain.text_splitter import RecursiveCharacterTextSplitter
7
  from langchain_community.vectorstores import Chroma
@@ -11,13 +10,11 @@ from langchain_community.llms import HuggingFacePipeline
11
  from langchain.chains import ConversationChain
12
  from langchain.memory import ConversationBufferMemory
13
  from langchain_huggingface.llms import HuggingFaceEndpoint
14
- #from huggingface_hub import login # Import the login function
15
-
16
  from pathlib import Path
17
  import chromadb
18
  from unidecode import unidecode
19
-
20
- # from transformers import AutoTokenizer
21
  import transformers
22
  import torch
23
  import tqdm
@@ -28,30 +25,20 @@ load_dotenv()
28
 
29
  huggingface_api_key = os.getenv("HUGGINGFACE_API_KEY")
30
 
31
- # print('HF TOKEN: ', huggingface_api_key)
32
 
33
- # default_persist_directory = './chroma_HF/'
34
- list_llm = ["mistralai/Mistral-7B-Instruct-v0.3"]
35
  list_llm_simple = [os.path.basename(llm) for llm in list_llm]
36
 
37
- # Load PDF document and create doc splits
38
  def load_doc(list_file_path, chunk_size, chunk_overlap):
39
- # Processing for one document only
40
- # loader = PyPDFLoader(file_path)
41
- # pages = loader.load()
42
  loaders = [PyPDFLoader(x) for x in list_file_path]
43
  pages = []
44
  for loader in loaders:
45
  pages.extend(loader.load())
46
  text_splitter = RecursiveCharacterTextSplitter(chunk_size = 600, chunk_overlap = 50)
47
- #text_splitter = RecursiveCharacterTextSplitter(
48
- # chunk_size = chunk_size,
49
- # chunk_overlap = chunk_overlap)
50
  doc_splits = text_splitter.split_documents(pages)
51
  return doc_splits
52
 
53
-
54
- # Create vector database
55
  def create_db(splits, collection_name):
56
  embedding = HuggingFaceEmbeddings()
57
  new_client = chromadb.EphemeralClient()
@@ -60,100 +47,50 @@ def create_db(splits, collection_name):
60
  embedding=embedding,
61
  client=new_client,
62
  collection_name=collection_name,
63
- # persist_directory=default_persist_directory
64
  )
65
  return vectordb
66
 
67
-
68
- # Load vector database
69
  def load_db():
70
  embedding = HuggingFaceEmbeddings()
71
- vectordb = Chroma(
72
- # persist_directory=default_persist_directory,
73
- embedding_function=embedding)
74
  return vectordb
75
 
76
-
77
- # Initialize langchain LLM chain
78
  def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
79
  progress(0.1, desc="Initializing HF tokenizer...")
80
- # HuggingFacePipeline uses local model
81
- # Note: it will download model locally...
82
- # tokenizer=AutoTokenizer.from_pretrained(llm_model)
83
- # progress(0.5, desc="Initializing HF pipeline...")
84
- # pipeline=transformers.pipeline(
85
- # "text-generation",
86
- # model=llm_model,
87
- # tokenizer=tokenizer,
88
- # torch_dtype=torch.bfloat16,
89
- # trust_remote_code=True,
90
- # device_map="auto",
91
- # # max_length=1024,
92
- # max_new_tokens=max_tokens,
93
- # do_sample=True,
94
- # top_k=top_k,
95
- # num_return_sequences=1,
96
- # eos_token_id=tokenizer.eos_token_id
97
- # )
98
- # llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature': temperature})
99
-
100
- # HuggingFaceHub uses HF inference endpoints
101
  progress(0.5, desc="Initializing HF Hub...")
102
- # Use of trust_remote_code as model_kwargs
103
- # Warning: langchain issue
104
- # URL: https://github.com/langchain-ai/langchain/issues/6080
105
- #login(token=huggingface_api_key)
106
  llm = HuggingFaceEndpoint(
107
  repo_id=llm_model,
108
- #model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
109
- #model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
110
  temperature = temperature,
111
  max_new_tokens = max_tokens,
112
  top_k = top_k,
113
  )
114
-
115
  progress(0.75, desc="Defining buffer memory...")
116
  memory = ConversationBufferMemory(
117
  memory_key="chat_history",
118
  output_key='answer',
119
  return_messages=True
120
  )
121
- # retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})
122
- retriever=vector_db.as_retriever()
123
  progress(0.8, desc="Defining retrieval chain...")
124
  qa_chain = ConversationalRetrievalChain.from_llm(
125
  llm,
126
  retriever=retriever,
127
  chain_type="stuff",
128
  memory=memory,
129
- # combine_docs_chain_kwargs={"prompt": your_prompt})
130
  return_source_documents=True,
131
- #return_generated_question=False,
132
  verbose=False,
133
  )
134
  progress(0.9, desc="Done!")
135
  return qa_chain
136
 
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():
@@ -162,46 +99,32 @@ def create_collection_name(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:
@@ -210,29 +133,19 @@ 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()
@@ -252,7 +165,6 @@ def demo():
252
  with gr.Tab("Step 1 - Upload PDF"):
253
  with gr.Row():
254
  document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
255
- # upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)
256
 
257
  with gr.Tab("Step 2 - Process document"):
258
  with gr.Row():
@@ -265,7 +177,7 @@ def demo():
265
  with gr.Row():
266
  db_progress = gr.Textbox(label="Vector database initialization", value="None")
267
  with gr.Row():
268
- db_btn = gr.Button("Generate vector database")
269
 
270
  with gr.Tab("Step 3 - Initialize QA chain"):
271
  with gr.Row():
@@ -275,59 +187,38 @@ def demo():
275
  with gr.Row():
276
  slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
277
  with gr.Row():
278
- slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
279
  with gr.Row():
280
- slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
281
  with gr.Row():
282
- llm_progress = gr.Textbox(value="None",label="QA chain initialization")
283
  with gr.Row():
284
- qachain_btn = gr.Button("Initialize Question Answering chain")
285
 
286
- with gr.Tab("Step 4 - Chatbot"):
287
- chatbot = gr.Chatbot(height=300)
288
- with gr.Accordion("Advanced - Document references", open=False):
289
- with gr.Row():
290
- doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
291
- source1_page = gr.Number(label="Page", scale=1)
292
- with gr.Row():
293
- doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
294
- source2_page = gr.Number(label="Page", scale=1)
295
- with gr.Row():
296
- doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
297
- source3_page = gr.Number(label="Page", scale=1)
298
  with gr.Row():
299
- msg = gr.Textbox(placeholder="Type message (e.g. 'What is this document about?')", container=True)
300
  with gr.Row():
301
- submit_btn = gr.Button("Submit message")
302
- clear_btn = gr.ClearButton([msg, chatbot], value="Clear conversation")
303
-
304
- # Preprocessing events
305
- #upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])
306
- db_btn.click(initialize_database, \
307
- inputs=[document, slider_chunk_size, slider_chunk_overlap], \
308
- outputs=[vector_db, collection_name, db_progress])
309
- qachain_btn.click(initialize_LLM, \
310
- inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
311
- outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0], \
312
- inputs=None, \
313
- outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
314
- queue=False)
315
 
316
- # Chatbot events
317
- msg.submit(conversation, \
318
- inputs=[qa_chain, msg, chatbot], \
319
- outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
320
- queue=False)
321
- submit_btn.click(conversation, \
322
- inputs=[qa_chain, msg, chatbot], \
323
- outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
324
- queue=False)
325
- clear_btn.click(lambda:[None,"",0,"",0,"",0], \
326
- inputs=None, \
327
- outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
328
- queue=False)
329
- demo.queue().launch(debug=True)
330
 
 
331
 
332
  if __name__ == "__main__":
333
- demo().queue().launch(debug=True, server_port=7861)
 
1
  import gradio as gr
2
  import os
3
  from dotenv import load_dotenv
 
4
  from langchain_community.document_loaders import PyPDFLoader
5
  from langchain.text_splitter import RecursiveCharacterTextSplitter
6
  from langchain_community.vectorstores import Chroma
 
10
  from langchain.chains import ConversationChain
11
  from langchain.memory import ConversationBufferMemory
12
  from langchain_huggingface.llms import HuggingFaceEndpoint
13
+ from huggingface_hub import login
 
14
  from pathlib import Path
15
  import chromadb
16
  from unidecode import unidecode
17
+ from transformers import AutoTokenizer
 
18
  import transformers
19
  import torch
20
  import tqdm
 
25
 
26
  huggingface_api_key = os.getenv("HUGGINGFACE_API_KEY")
27
 
28
+ print('HF TOKEN: ', huggingface_api_key)
29
 
30
+ list_llm = ["mistralai/Mistral-7B-Instruct-v0.2"]
 
31
  list_llm_simple = [os.path.basename(llm) for llm in list_llm]
32
 
 
33
  def load_doc(list_file_path, chunk_size, chunk_overlap):
 
 
 
34
  loaders = [PyPDFLoader(x) for x in list_file_path]
35
  pages = []
36
  for loader in loaders:
37
  pages.extend(loader.load())
38
  text_splitter = RecursiveCharacterTextSplitter(chunk_size = 600, chunk_overlap = 50)
 
 
 
39
  doc_splits = text_splitter.split_documents(pages)
40
  return doc_splits
41
 
 
 
42
  def create_db(splits, collection_name):
43
  embedding = HuggingFaceEmbeddings()
44
  new_client = chromadb.EphemeralClient()
 
47
  embedding=embedding,
48
  client=new_client,
49
  collection_name=collection_name,
 
50
  )
51
  return vectordb
52
 
 
 
53
  def load_db():
54
  embedding = HuggingFaceEmbeddings()
55
+ vectordb = Chroma(embedding_function=embedding)
 
 
56
  return vectordb
57
 
 
 
58
  def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
59
  progress(0.1, desc="Initializing HF tokenizer...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  progress(0.5, desc="Initializing HF Hub...")
 
 
 
 
61
  llm = HuggingFaceEndpoint(
62
  repo_id=llm_model,
 
 
63
  temperature = temperature,
64
  max_new_tokens = max_tokens,
65
  top_k = top_k,
66
  )
 
67
  progress(0.75, desc="Defining buffer memory...")
68
  memory = ConversationBufferMemory(
69
  memory_key="chat_history",
70
  output_key='answer',
71
  return_messages=True
72
  )
73
+ retriever = vector_db.as_retriever()
 
74
  progress(0.8, desc="Defining retrieval chain...")
75
  qa_chain = ConversationalRetrievalChain.from_llm(
76
  llm,
77
  retriever=retriever,
78
  chain_type="stuff",
79
  memory=memory,
 
80
  return_source_documents=True,
 
81
  verbose=False,
82
  )
83
  progress(0.9, desc="Done!")
84
  return qa_chain
85
 
 
 
 
86
  def create_collection_name(filepath):
 
87
  collection_name = Path(filepath).stem
 
 
88
  collection_name = collection_name.replace(" ","-")
 
89
  collection_name = unidecode(collection_name)
 
 
90
  collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
 
91
  collection_name = collection_name[:50]
 
92
  if len(collection_name) < 3:
93
  collection_name = collection_name + 'xyz'
 
94
  if not collection_name[0].isalnum():
95
  collection_name = 'A' + collection_name[1:]
96
  if not collection_name[-1].isalnum():
 
99
  print('Collection name: ', collection_name)
100
  return collection_name
101
 
 
 
102
  def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
 
103
  list_file_path = [x.name for x in list_file_obj if x is not None]
 
104
  progress(0.1, desc="Creating collection name...")
105
  collection_name = create_collection_name(list_file_path[0])
106
  progress(0.25, desc="Loading document...")
 
107
  doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
 
108
  progress(0.5, desc="Generating vector database...")
 
109
  vector_db = create_db(doc_splits, collection_name)
110
  progress(0.9, desc="Done!")
111
  return vector_db, collection_name, "Complete!"
112
 
 
113
  def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
 
114
  llm_name = list_llm[llm_option]
115
  print("llm_name: ",llm_name)
116
  qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
117
  return qa_chain, "Complete!"
118
 
 
119
  def format_chat_history(message, chat_history):
120
  formatted_chat_history = []
121
  for user_message, bot_message in chat_history:
122
  formatted_chat_history.append(f"User: {user_message}")
123
  formatted_chat_history.append(f"Assistant: {bot_message}")
124
  return formatted_chat_history
 
125
 
126
  def conversation(qa_chain, message, history):
127
  formatted_chat_history = format_chat_history(message, history)
 
 
 
128
  response = qa_chain({"question": message, "chat_history": formatted_chat_history})
129
  response_answer = response["answer"]
130
  if response_answer.find("Helpful Answer:") != -1:
 
133
  response_source1 = response_sources[0].page_content.strip()
134
  response_source2 = response_sources[1].page_content.strip()
135
  response_source3 = response_sources[2].page_content.strip()
 
136
  response_source1_page = response_sources[0].metadata["page"] + 1
137
  response_source2_page = response_sources[1].metadata["page"] + 1
138
  response_source3_page = response_sources[2].metadata["page"] + 1
 
 
 
 
139
  new_history = history + [(message, response_answer)]
 
140
  return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
 
141
 
142
  def upload_file(file_obj):
143
  list_file_path = []
144
  for idx, file in enumerate(file_obj):
145
  file_path = file_obj.name
146
  list_file_path.append(file_path)
 
 
147
  return list_file_path
148
 
 
149
  def demo():
150
  with gr.Blocks(theme="base") as demo:
151
  vector_db = gr.State()
 
165
  with gr.Tab("Step 1 - Upload PDF"):
166
  with gr.Row():
167
  document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
 
168
 
169
  with gr.Tab("Step 2 - Process document"):
170
  with gr.Row():
 
177
  with gr.Row():
178
  db_progress = gr.Textbox(label="Vector database initialization", value="None")
179
  with gr.Row():
180
+ db_generate_btn = gr.Button("Generate vector database")
181
 
182
  with gr.Tab("Step 3 - Initialize QA chain"):
183
  with gr.Row():
 
187
  with gr.Row():
188
  slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
189
  with gr.Row():
190
+ slider_maxtokens = gr.Slider(minimum = 32, maximum = 2048, value=1024, step=16, label="Max tokens", info="Maximum tokens", interactive=True)
191
  with gr.Row():
192
+ slider_topk = gr.Slider(minimum = 10, maximum = 50, value=40, step=2, label="Top K", info="Top K", interactive=True)
193
  with gr.Row():
194
+ llm_progress = gr.Textbox(label="LLM initialization", value="None")
195
  with gr.Row():
196
+ llm_generate_btn = gr.Button("Initialize LLM chain")
197
 
198
+ with gr.Tab("Step 4 - Ask questions to your chatbot"):
 
 
 
 
 
 
 
 
 
 
 
199
  with gr.Row():
200
+ chatbot = gr.Chatbot(label="Langchain PDF chatbot", height=400)
201
  with gr.Row():
202
+ msg = gr.Textbox(label="Ask anything about your PDF document", placeholder="Type your message here...", show_label=False).style(container=False)
203
+ with gr.Row():
204
+ response_source1 = gr.Textbox(label="Source document #1", value="", interactive=False)
205
+ response_source1_page = gr.Number(label="Page", value=0, interactive=False)
206
+ with gr.Row():
207
+ response_source2 = gr.Textbox(label="Source document #2", value="", interactive=False)
208
+ response_source2_page = gr.Number(label="Page", value=0, interactive=False)
209
+ with gr.Row():
210
+ response_source3 = gr.Textbox(label="Source document #3", value="", interactive=False)
211
+ response_source3_page = gr.Number(label="Page", value=0, interactive=False)
212
+ with gr.Row():
213
+ clear = gr.Button("Clear")
 
 
214
 
215
+ document.upload(upload_file, [document], [document])
216
+ db_generate_btn.click(initialize_database, inputs=[document, slider_chunk_size, slider_chunk_overlap], outputs=[vector_db, collection_name, db_progress])
217
+ llm_generate_btn.click(initialize_LLM, inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], outputs=[qa_chain, llm_progress])
218
+ msg.submit(conversation, [qa_chain, msg, chatbot], [qa_chain, msg, chatbot, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page])
219
+ clear.click(lambda: None, None, chatbot, queue=False)
 
 
 
 
 
 
 
 
 
220
 
221
+ return demo
222
 
223
  if __name__ == "__main__":
224
+ demo().queue().launch(debug=True, server_port=7861) # Use a different port, e.g., 7861