basildarwazeh commited on
Commit
86c28fb
·
verified ·
1 Parent(s): 2ebbe14

Update ap1.py

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