Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,75 @@
|
|
1 |
import gradio as gr
|
2 |
import os
|
3 |
-
|
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.
|
|
|
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 |
-
|
|
|
|
|
19 |
list_llm_simple = [os.path.basename(llm) for llm in list_llm]
|
20 |
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
text_splitter = RecursiveCharacterTextSplitter(
|
31 |
-
chunk_size
|
32 |
-
chunk_overlap
|
33 |
-
)
|
34 |
-
|
35 |
-
return
|
36 |
|
37 |
-
# Create vector database
|
38 |
def create_db(splits):
|
|
|
39 |
embeddings = HuggingFaceEmbeddings()
|
40 |
-
vectordb = FAISS.from_documents(splits, embeddings)
|
41 |
return vectordb
|
42 |
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
|
|
|
|
|
|
|
|
62 |
|
63 |
memory = ConversationBufferMemory(
|
64 |
memory_key="chat_history",
|
@@ -66,151 +77,128 @@ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, pr
|
|
66 |
return_messages=True
|
67 |
)
|
68 |
|
69 |
-
retriever=vector_db.as_retriever()
|
70 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
71 |
llm,
|
72 |
-
retriever=
|
73 |
-
chain_type="stuff",
|
74 |
memory=memory,
|
75 |
return_source_documents=True,
|
76 |
verbose=False,
|
77 |
)
|
78 |
return qa_chain
|
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 |
-
|
93 |
llm_name = list_llm[llm_option]
|
94 |
-
|
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:
|
113 |
response_answer = response_answer.split("Helpful Answer:")[-1]
|
114 |
-
response_sources = response["source_documents"]
|
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 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
|
|
|
|
|
|
|
|
|
|
134 |
|
135 |
def demo():
|
136 |
-
|
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 |
-
|
141 |
-
gr.
|
142 |
-
<b>
|
143 |
-
|
144 |
with gr.Row():
|
145 |
-
with gr.Column(scale
|
146 |
-
gr.Markdown("<b>Step 1 -
|
147 |
with gr.Row():
|
148 |
-
|
149 |
with gr.Row():
|
150 |
db_btn = gr.Button("Create vector database")
|
151 |
with gr.Row():
|
152 |
-
|
153 |
-
|
|
|
154 |
with gr.Row():
|
155 |
-
llm_btn = gr.Radio(list_llm_simple, label="Available LLMs", value
|
156 |
with gr.Row():
|
157 |
with gr.Accordion("LLM input parameters", open=False):
|
158 |
-
|
159 |
-
|
160 |
-
|
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 |
-
|
168 |
|
169 |
-
with gr.Column(scale
|
170 |
-
gr.Markdown("<b>Step 2 - Chat
|
171 |
chatbot = gr.Chatbot(height=505)
|
172 |
-
with gr.Accordion("
|
173 |
with gr.Row():
|
174 |
doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
|
175 |
-
source1_page = gr.Number(label="
|
176 |
with gr.Row():
|
177 |
doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
|
178 |
-
source2_page = gr.Number(label="
|
179 |
with gr.Row():
|
180 |
doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
|
181 |
-
source3_page = gr.Number(label="
|
182 |
with gr.Row():
|
183 |
msg = gr.Textbox(placeholder="Ask a question", container=True)
|
184 |
with gr.Row():
|
185 |
submit_btn = gr.Button("Submit")
|
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 |
-
#
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
213 |
|
|
|
214 |
|
215 |
if __name__ == "__main__":
|
216 |
-
demo()
|
|
|
1 |
import gradio as gr
|
2 |
import os
|
3 |
+
from bs4 import BeautifulSoup
|
4 |
+
import requests
|
|
|
|
|
|
|
5 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
6 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
7 |
+
from langchain_community.vectorstores import FAISS
|
8 |
from langchain.chains import ConversationalRetrievalChain
|
|
|
|
|
|
|
9 |
from langchain.memory import ConversationBufferMemory
|
10 |
from langchain_community.llms import HuggingFaceEndpoint
|
|
|
11 |
|
12 |
+
# Initialize environment
|
13 |
+
api_token =os.getenv("HF_TOKEN")
|
14 |
+
list_llm = ["meta-llama/Meta-Llama-3-8B-Instruct", "mistralai/Mistral-7B-Instruct-v0.2"]
|
15 |
list_llm_simple = [os.path.basename(llm) for llm in list_llm]
|
16 |
|
17 |
+
def scrape_website(url):
|
18 |
+
"""Scrape text content from a website"""
|
19 |
+
try:
|
20 |
+
response = requests.get(url)
|
21 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
22 |
+
|
23 |
+
for script in soup(["script", "style"]):
|
24 |
+
script.decompose()
|
25 |
+
|
26 |
+
text = soup.get_text()
|
27 |
+
lines = (line.strip() for line in text.splitlines())
|
28 |
+
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
|
29 |
+
text = ' '.join(chunk for chunk in chunks if chunk)
|
30 |
+
|
31 |
+
return text
|
32 |
+
except Exception as e:
|
33 |
+
return f"Error scraping website: {str(e)}"
|
34 |
+
|
35 |
+
def process_text(text):
|
36 |
+
"""Split text into chunks"""
|
37 |
text_splitter = RecursiveCharacterTextSplitter(
|
38 |
+
chunk_size=1024,
|
39 |
+
chunk_overlap=64
|
40 |
+
)
|
41 |
+
chunks = text_splitter.split_text(text)
|
42 |
+
return chunks
|
43 |
|
|
|
44 |
def create_db(splits):
|
45 |
+
"""Create vector database"""
|
46 |
embeddings = HuggingFaceEmbeddings()
|
47 |
+
vectordb = FAISS.from_documents([{"page_content": text, "metadata": {}} for text in splits], embeddings)
|
48 |
return vectordb
|
49 |
|
50 |
+
def initialize_database(url, progress=gr.Progress()):
|
51 |
+
"""Initialize database from URL"""
|
52 |
+
# Scrape website content
|
53 |
+
text_content = scrape_website(url)
|
54 |
+
if text_content.startswith("Error"):
|
55 |
+
return None, text_content
|
56 |
+
|
57 |
+
# Create text chunks
|
58 |
+
doc_splits = process_text(text_content)
|
59 |
+
|
60 |
+
# Create vector database
|
61 |
+
vector_db = create_db(doc_splits)
|
62 |
+
return vector_db, "Database created successfully!"
|
63 |
+
|
64 |
+
def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db):
|
65 |
+
"""Initialize LLM chain"""
|
66 |
+
llm = HuggingFaceEndpoint(
|
67 |
+
repo_id=llm_model,
|
68 |
+
huggingfacehub_api_token=api_token,
|
69 |
+
temperature=temperature,
|
70 |
+
max_new_tokens=max_tokens,
|
71 |
+
top_k=top_k,
|
72 |
+
)
|
73 |
|
74 |
memory = ConversationBufferMemory(
|
75 |
memory_key="chat_history",
|
|
|
77 |
return_messages=True
|
78 |
)
|
79 |
|
|
|
80 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
81 |
llm,
|
82 |
+
retriever=vector_db.as_retriever(),
|
83 |
+
chain_type="stuff",
|
84 |
memory=memory,
|
85 |
return_source_documents=True,
|
86 |
verbose=False,
|
87 |
)
|
88 |
return qa_chain
|
89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
91 |
+
"""Initialize LLM with selected options"""
|
92 |
llm_name = list_llm[llm_option]
|
93 |
+
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db)
|
|
|
94 |
return qa_chain, "QA chain initialized. Chatbot is ready!"
|
95 |
|
|
|
96 |
def format_chat_history(message, chat_history):
|
97 |
+
"""Format chat history for the model"""
|
98 |
formatted_chat_history = []
|
99 |
for user_message, bot_message in chat_history:
|
100 |
formatted_chat_history.append(f"User: {user_message}")
|
101 |
formatted_chat_history.append(f"Assistant: {bot_message}")
|
102 |
return formatted_chat_history
|
|
|
103 |
|
104 |
def conversation(qa_chain, message, history):
|
105 |
+
"""Handle conversation with the model"""
|
106 |
formatted_chat_history = format_chat_history(message, history)
|
|
|
107 |
response = qa_chain.invoke({"question": message, "chat_history": formatted_chat_history})
|
108 |
+
|
109 |
response_answer = response["answer"]
|
110 |
if response_answer.find("Helpful Answer:") != -1:
|
111 |
response_answer = response_answer.split("Helpful Answer:")[-1]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
|
113 |
+
response_sources = response["source_documents"][:3]
|
114 |
+
sources = []
|
115 |
+
for i in range(3):
|
116 |
+
if i < len(response_sources):
|
117 |
+
sources.append((response_sources[i].page_content.strip(), 1))
|
118 |
+
else:
|
119 |
+
sources.append(("", 1))
|
120 |
+
|
121 |
+
new_history = history + [(message, response_answer)]
|
122 |
+
return (qa_chain, gr.update(value=""), new_history,
|
123 |
+
sources[0][0], sources[0][1],
|
124 |
+
sources[1][0], sources[1][1],
|
125 |
+
sources[2][0], sources[2][1])
|
126 |
|
127 |
def demo():
|
128 |
+
with gr.Blocks(theme=gr.themes.Default(primary_hue="red", secondary_hue="pink", neutral_hue="sky")) as demo:
|
|
|
129 |
vector_db = gr.State()
|
130 |
qa_chain = gr.State()
|
131 |
+
|
132 |
+
gr.HTML("<center><h1>RAG Website Chatbot</h1></center>")
|
133 |
+
gr.Markdown("""<b>Query any website content!</b> This AI agent performs retrieval augmented generation (RAG) on website content.""")
|
134 |
+
|
135 |
with gr.Row():
|
136 |
+
with gr.Column(scale=86):
|
137 |
+
gr.Markdown("<b>Step 1 - Enter Website URL and Initialize RAG pipeline</b>")
|
138 |
with gr.Row():
|
139 |
+
url_input = gr.Textbox(label="Website URL", placeholder="Enter website URL here...")
|
140 |
with gr.Row():
|
141 |
db_btn = gr.Button("Create vector database")
|
142 |
with gr.Row():
|
143 |
+
db_progress = gr.Textbox(value="Not initialized", show_label=False)
|
144 |
+
|
145 |
+
gr.Markdown("<b>Select Large Language Model (LLM) and input parameters</b>")
|
146 |
with gr.Row():
|
147 |
+
llm_btn = gr.Radio(list_llm_simple, label="Available LLMs", value=list_llm_simple[0], type="index")
|
148 |
with gr.Row():
|
149 |
with gr.Accordion("LLM input parameters", open=False):
|
150 |
+
slider_temperature = gr.Slider(0.01, 1.0, 0.5, step=0.1, label="Temperature")
|
151 |
+
slider_maxtokens = gr.Slider(128, 9192, 4096, step=128, label="Max New Tokens")
|
152 |
+
slider_topk = gr.Slider(1, 10, 3, step=1, label="top-k")
|
|
|
|
|
|
|
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 about the Website Content</b>")
|
160 |
chatbot = gr.Chatbot(height=505)
|
161 |
+
with gr.Accordion("Relevant context from the source", 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="Section", scale=1)
|
165 |
with gr.Row():
|
166 |
doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
|
167 |
+
source2_page = gr.Number(label="Section", scale=1)
|
168 |
with gr.Row():
|
169 |
doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
|
170 |
+
source3_page = gr.Number(label="Section", scale=1)
|
171 |
with gr.Row():
|
172 |
msg = gr.Textbox(placeholder="Ask a question", container=True)
|
173 |
with gr.Row():
|
174 |
submit_btn = gr.Button("Submit")
|
175 |
clear_btn = gr.ClearButton([msg, chatbot], value="Clear")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
176 |
|
177 |
+
# Event handlers
|
178 |
+
db_btn.click(initialize_database,
|
179 |
+
inputs=[url_input],
|
180 |
+
outputs=[vector_db, db_progress])
|
181 |
+
|
182 |
+
qachain_btn.click(initialize_LLM,
|
183 |
+
inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db],
|
184 |
+
outputs=[qa_chain, llm_progress])
|
185 |
+
|
186 |
+
msg.submit(conversation,
|
187 |
+
inputs=[qa_chain, msg, chatbot],
|
188 |
+
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page,
|
189 |
+
doc_source2, source2_page, doc_source3, source3_page])
|
190 |
+
|
191 |
+
submit_btn.click(conversation,
|
192 |
+
inputs=[qa_chain, msg, chatbot],
|
193 |
+
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page,
|
194 |
+
doc_source2, source2_page, doc_source3, source3_page])
|
195 |
+
|
196 |
+
clear_btn.click(lambda: [None, "", 0, "", 0, "", 0],
|
197 |
+
inputs=None,
|
198 |
+
outputs=[chatbot, doc_source1, source1_page,
|
199 |
+
doc_source2, source2_page, doc_source3, source3_page])
|
200 |
|
201 |
+
demo.queue().launch(debug=True)
|
202 |
|
203 |
if __name__ == "__main__":
|
204 |
+
demo()
|