DHEIVER commited on
Commit
9030fbe
·
verified ·
1 Parent(s): a5c9a00

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -77
app.py CHANGED
@@ -1,35 +1,29 @@
1
  import gradio as gr
2
  import os
3
- api_token = os.getenv("HF_TOKEN")
4
-
5
 
6
  from langchain_community.vectorstores import FAISS
7
  from langchain_community.document_loaders import PyPDFLoader
8
  from langchain.text_splitter import RecursiveCharacterTextSplitter
9
- from langchain_community.vectorstores import Chroma
10
  from langchain.chains import ConversationalRetrievalChain
11
  from langchain_community.embeddings import HuggingFaceEmbeddings
12
  from langchain_community.llms import HuggingFacePipeline
13
- from langchain.chains import ConversationChain
14
  from langchain.memory import ConversationBufferMemory
15
- from langchain_community.llms import HuggingFaceEndpoint
16
  import torch
 
17
 
18
- list_llm = ["meta-llama/Meta-Llama-3-8B-Instruct", "mistralai/Mistral-7B-Instruct-v0.2"]
 
19
  list_llm_simple = [os.path.basename(llm) for llm in list_llm]
20
 
21
  # Load and split PDF document
22
  def load_doc(list_file_path):
23
- # Processing for one document only
24
- # loader = PyPDFLoader(file_path)
25
- # pages = loader.load()
26
  loaders = [PyPDFLoader(x) for x in list_file_path]
27
  pages = []
28
  for loader in loaders:
29
  pages.extend(loader.load())
30
  text_splitter = RecursiveCharacterTextSplitter(
31
- chunk_size = 1024,
32
- chunk_overlap = 64
33
  )
34
  doc_splits = text_splitter.split_documents(pages)
35
  return doc_splits
@@ -40,33 +34,40 @@ def create_db(splits):
40
  vectordb = FAISS.from_documents(splits, embeddings)
41
  return vectordb
42
 
43
-
44
- # Initialize langchain LLM chain
45
  def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
46
- if llm_model == "meta-llama/Meta-Llama-3-8B-Instruct":
47
- llm = HuggingFaceEndpoint(
48
- repo_id=llm_model,
49
- huggingfacehub_api_token = api_token,
50
- temperature = temperature,
51
- max_new_tokens = max_tokens,
52
- top_k = top_k,
53
- )
54
- else:
55
- llm = HuggingFaceEndpoint(
56
- huggingfacehub_api_token = api_token,
57
- repo_id=llm_model,
58
- temperature = temperature,
59
- max_new_tokens = max_tokens,
60
- top_k = top_k,
61
- )
 
 
 
 
 
 
 
 
62
 
63
  memory = ConversationBufferMemory(
64
  memory_key="chat_history",
65
- output_key='answer',
66
  return_messages=True
67
  )
68
 
69
- retriever=vector_db.as_retriever()
70
  qa_chain = ConversationalRetrievalChain.from_llm(
71
  llm,
72
  retriever=retriever,
@@ -79,34 +80,27 @@ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, pr
79
 
80
  # Initialize database
81
  def initialize_database(list_file_obj, progress=gr.Progress()):
82
- # Create a list of documents (when valid)
83
  list_file_path = [x.name for x in list_file_obj if x is not None]
84
- # Load document and create splits
85
  doc_splits = load_doc(list_file_path)
86
- # Create or load vector database
87
  vector_db = create_db(doc_splits)
88
  return vector_db, "Database created!"
89
 
90
  # Initialize LLM
91
  def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
92
- # print("llm_option",llm_option)
93
  llm_name = list_llm[llm_option]
94
- print("llm_name: ",llm_name)
95
  qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
96
  return qa_chain, "QA chain initialized. Chatbot is ready!"
97
 
98
-
99
  def format_chat_history(message, chat_history):
100
  formatted_chat_history = []
101
  for user_message, bot_message in chat_history:
102
  formatted_chat_history.append(f"User: {user_message}")
103
  formatted_chat_history.append(f"Assistant: {bot_message}")
104
  return formatted_chat_history
105
-
106
 
107
  def conversation(qa_chain, message, history):
108
  formatted_chat_history = format_chat_history(message, history)
109
- # Generate response using QA chain
110
  response = qa_chain.invoke({"question": message, "chat_history": formatted_chat_history})
111
  response_answer = response["answer"]
112
  if response_answer.find("Helpful Answer:") != -1:
@@ -115,14 +109,11 @@ def conversation(qa_chain, message, history):
115
  response_source1 = response_sources[0].page_content.strip()
116
  response_source2 = response_sources[1].page_content.strip()
117
  response_source3 = response_sources[2].page_content.strip()
118
- # Langchain sources are zero-based
119
  response_source1_page = response_sources[0].metadata["page"] + 1
120
  response_source2_page = response_sources[1].metadata["page"] + 1
121
  response_source3_page = response_sources[2].metadata["page"] + 1
122
- # Append user message and response to chat history
123
  new_history = history + [(message, response_answer)]
124
  return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
125
-
126
 
127
  def upload_file(file_obj):
128
  list_file_path = []
@@ -131,45 +122,43 @@ def upload_file(file_obj):
131
  list_file_path.append(file_path)
132
  return list_file_path
133
 
134
-
135
  def demo():
136
- # with gr.Blocks(theme=gr.themes.Default(primary_hue="sky")) as demo:
137
- with gr.Blocks(theme=gr.themes.Default(primary_hue="red", secondary_hue="pink", neutral_hue = "sky")) as demo:
138
  vector_db = gr.State()
139
  qa_chain = gr.State()
140
  gr.HTML("<center><h1>RAG PDF chatbot</h1><center>")
141
- gr.Markdown("""<b>Query your PDF documents!</b> This AI agent is designed to perform retrieval augmented generation (RAG) on PDF documents. The app is hosted on Hugging Face Hub for the sole purpose of demonstration. \
142
  <b>Please do not upload confidential documents.</b>
143
  """)
144
  with gr.Row():
145
- with gr.Column(scale = 86):
146
  gr.Markdown("<b>Step 1 - Upload PDF documents and Initialize RAG pipeline</b>")
147
  with gr.Row():
148
  document = gr.Files(height=300, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload PDF documents")
149
  with gr.Row():
150
  db_btn = gr.Button("Create vector database")
151
  with gr.Row():
152
- db_progress = gr.Textbox(value="Not initialized", show_label=False) # label="Vector database status",
153
  gr.Markdown("<style>body { font-size: 16px; }</style><b>Select Large Language Model (LLM) and input parameters</b>")
154
  with gr.Row():
155
- llm_btn = gr.Radio(list_llm_simple, label="Available LLMs", value = list_llm_simple[0], type="index") # info="Select LLM", show_label=False
156
  with gr.Row():
157
  with gr.Accordion("LLM input parameters", open=False):
158
  with gr.Row():
159
- slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.5, step=0.1, label="Temperature", info="Controls randomness in token generation", interactive=True)
160
  with gr.Row():
161
- slider_maxtokens = gr.Slider(minimum = 128, maximum = 9192, value=4096, step=128, label="Max New Tokens", info="Maximum number of tokens to be generated",interactive=True)
162
  with gr.Row():
163
- slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k", info="Number of tokens to select the next token from", interactive=True)
164
  with gr.Row():
165
  qachain_btn = gr.Button("Initialize Question Answering Chatbot")
166
  with gr.Row():
167
- llm_progress = gr.Textbox(value="Not initialized", show_label=False) # label="Chatbot status",
168
 
169
- with gr.Column(scale = 200):
170
  gr.Markdown("<b>Step 2 - Chat with your Document</b>")
171
  chatbot = gr.Chatbot(height=505)
172
- with gr.Accordion("Relevent context from the source document", open=False):
173
  with gr.Row():
174
  doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
175
  source1_page = gr.Number(label="Page", scale=1)
@@ -186,31 +175,20 @@ def demo():
186
  clear_btn = gr.ClearButton([msg, chatbot], value="Clear")
187
 
188
  # Preprocessing events
189
- db_btn.click(initialize_database, \
190
- inputs=[document], \
191
- outputs=[vector_db, db_progress])
192
- qachain_btn.click(initialize_LLM, \
193
- inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
194
- outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0], \
195
- inputs=None, \
196
- outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
197
- queue=False)
198
 
199
  # Chatbot events
200
- msg.submit(conversation, \
201
- inputs=[qa_chain, msg, chatbot], \
202
- outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
203
- queue=False)
204
- submit_btn.click(conversation, \
205
- inputs=[qa_chain, msg, chatbot], \
206
- outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
207
- queue=False)
208
- clear_btn.click(lambda:[None,"",0,"",0,"",0], \
209
- inputs=None, \
210
- outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
211
- queue=False)
212
  demo.queue().launch(debug=True)
213
 
214
-
215
  if __name__ == "__main__":
216
  demo()
 
1
  import gradio as gr
2
  import os
 
 
3
 
4
  from langchain_community.vectorstores import FAISS
5
  from langchain_community.document_loaders import PyPDFLoader
6
  from langchain.text_splitter import RecursiveCharacterTextSplitter
 
7
  from langchain.chains import ConversationalRetrievalChain
8
  from langchain_community.embeddings import HuggingFaceEmbeddings
9
  from langchain_community.llms import HuggingFacePipeline
 
10
  from langchain.memory import ConversationBufferMemory
 
11
  import torch
12
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
13
 
14
+ # List of local models (no HF_TOKEN required after download)
15
+ list_llm = ["mistralai/Mistral-7B-Instruct-v0.2", "TheBloke/Mixtral-8x7B-Instruct-v0.1-GPTQ"]
16
  list_llm_simple = [os.path.basename(llm) for llm in list_llm]
17
 
18
  # Load and split PDF document
19
  def load_doc(list_file_path):
 
 
 
20
  loaders = [PyPDFLoader(x) for x in list_file_path]
21
  pages = []
22
  for loader in loaders:
23
  pages.extend(loader.load())
24
  text_splitter = RecursiveCharacterTextSplitter(
25
+ chunk_size=1024,
26
+ chunk_overlap=64
27
  )
28
  doc_splits = text_splitter.split_documents(pages)
29
  return doc_splits
 
34
  vectordb = FAISS.from_documents(splits, embeddings)
35
  return vectordb
36
 
37
+ # Initialize langchain LLM chain with local model
 
38
  def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
39
+ # Load the model and tokenizer locally
40
+ tokenizer = AutoTokenizer.from_pretrained(llm_model)
41
+ model = AutoModelForCausalLM.from_pretrained(
42
+ llm_model,
43
+ device_map="auto", # Automatically use GPU if available
44
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, # Optimize for GPU or CPU
45
+ trust_remote_code=True # Required for some models
46
+ )
47
+
48
+ # Create a pipeline for text generation
49
+ pipe = pipeline(
50
+ "text-generation",
51
+ model=model,
52
+ tokenizer=tokenizer,
53
+ max_new_tokens=max_tokens,
54
+ temperature=temperature,
55
+ top_k=top_k,
56
+ do_sample=True,
57
+ repetition_penalty=1.1,
58
+ return_full_text=False
59
+ )
60
+
61
+ # Wrap the pipeline in HuggingFacePipeline for LangChain
62
+ llm = HuggingFacePipeline(pipeline=pipe)
63
 
64
  memory = ConversationBufferMemory(
65
  memory_key="chat_history",
66
+ output_key="answer",
67
  return_messages=True
68
  )
69
 
70
+ retriever = vector_db.as_retriever()
71
  qa_chain = ConversationalRetrievalChain.from_llm(
72
  llm,
73
  retriever=retriever,
 
80
 
81
  # Initialize database
82
  def initialize_database(list_file_obj, progress=gr.Progress()):
 
83
  list_file_path = [x.name for x in list_file_obj if x is not None]
 
84
  doc_splits = load_doc(list_file_path)
 
85
  vector_db = create_db(doc_splits)
86
  return vector_db, "Database created!"
87
 
88
  # Initialize LLM
89
  def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
 
90
  llm_name = list_llm[llm_option]
91
+ print("llm_name: ", llm_name)
92
  qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
93
  return qa_chain, "QA chain initialized. Chatbot is ready!"
94
 
 
95
  def format_chat_history(message, chat_history):
96
  formatted_chat_history = []
97
  for user_message, bot_message in chat_history:
98
  formatted_chat_history.append(f"User: {user_message}")
99
  formatted_chat_history.append(f"Assistant: {bot_message}")
100
  return formatted_chat_history
 
101
 
102
  def conversation(qa_chain, message, history):
103
  formatted_chat_history = format_chat_history(message, history)
 
104
  response = qa_chain.invoke({"question": message, "chat_history": formatted_chat_history})
105
  response_answer = response["answer"]
106
  if response_answer.find("Helpful Answer:") != -1:
 
109
  response_source1 = response_sources[0].page_content.strip()
110
  response_source2 = response_sources[1].page_content.strip()
111
  response_source3 = response_sources[2].page_content.strip()
 
112
  response_source1_page = response_sources[0].metadata["page"] + 1
113
  response_source2_page = response_sources[1].metadata["page"] + 1
114
  response_source3_page = response_sources[2].metadata["page"] + 1
 
115
  new_history = history + [(message, response_answer)]
116
  return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
 
117
 
118
  def upload_file(file_obj):
119
  list_file_path = []
 
122
  list_file_path.append(file_path)
123
  return list_file_path
124
 
 
125
  def demo():
126
+ with gr.Blocks(theme=gr.themes.Default(primary_hue="red", secondary_hue="pink", neutral_hue="sky")) as demo:
 
127
  vector_db = gr.State()
128
  qa_chain = gr.State()
129
  gr.HTML("<center><h1>RAG PDF chatbot</h1><center>")
130
+ gr.Markdown("""<b>Query your PDF documents!</b> This AI agent is designed to perform retrieval augmented generation (RAG) on PDF documents. This version runs locally and does not require an API token. \
131
  <b>Please do not upload confidential documents.</b>
132
  """)
133
  with gr.Row():
134
+ with gr.Column(scale=86):
135
  gr.Markdown("<b>Step 1 - Upload PDF documents and Initialize RAG pipeline</b>")
136
  with gr.Row():
137
  document = gr.Files(height=300, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload PDF documents")
138
  with gr.Row():
139
  db_btn = gr.Button("Create vector database")
140
  with gr.Row():
141
+ db_progress = gr.Textbox(value="Not initialized", show_label=False)
142
  gr.Markdown("<style>body { font-size: 16px; }</style><b>Select Large Language Model (LLM) and input parameters</b>")
143
  with gr.Row():
144
+ llm_btn = gr.Radio(list_llm_simple, label="Available LLMs", value=list_llm_simple[0], type="index")
145
  with gr.Row():
146
  with gr.Accordion("LLM input parameters", open=False):
147
  with gr.Row():
148
+ slider_temperature = gr.Slider(minimum=0.01, maximum=1.0, value=0.5, step=0.1, label="Temperature", info="Controls randomness in token generation", interactive=True)
149
  with gr.Row():
150
+ slider_maxtokens = gr.Slider(minimum=128, maximum=4096, value=1024, step=128, label="Max New Tokens", info="Maximum number of tokens to be generated", interactive=True)
151
  with gr.Row():
152
+ slider_topk = gr.Slider(minimum=1, maximum=10, value=3, step=1, label="top-k", info="Number of tokens to select the next token from", interactive=True)
153
  with gr.Row():
154
  qachain_btn = gr.Button("Initialize Question Answering Chatbot")
155
  with gr.Row():
156
+ llm_progress = gr.Textbox(value="Not initialized", show_label=False)
157
 
158
+ with gr.Column(scale=200):
159
  gr.Markdown("<b>Step 2 - Chat with your Document</b>")
160
  chatbot = gr.Chatbot(height=505)
161
+ with gr.Accordion("Relevant context from the source document", open=False):
162
  with gr.Row():
163
  doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
164
  source1_page = gr.Number(label="Page", scale=1)
 
175
  clear_btn = gr.ClearButton([msg, chatbot], value="Clear")
176
 
177
  # Preprocessing events
178
+ db_btn.click(initialize_database, inputs=[document], outputs=[vector_db, db_progress])
179
+ qachain_btn.click(initialize_LLM, inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], outputs=[qa_chain, llm_progress]).then(
180
+ lambda: [None, "", 0, "", 0, "", 0],
181
+ inputs=None,
182
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
183
+ queue=False
184
+ )
 
 
185
 
186
  # Chatbot events
187
+ msg.submit(conversation, inputs=[qa_chain, msg, chatbot], outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], queue=False)
188
+ submit_btn.click(conversation, inputs=[qa_chain, msg, chatbot], outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], queue=False)
189
+ clear_btn.click(lambda: [None, "", 0, "", 0, "", 0], inputs=None, outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], queue=False)
190
+
 
 
 
 
 
 
 
 
191
  demo.queue().launch(debug=True)
192
 
 
193
  if __name__ == "__main__":
194
  demo()