Update app.py
Browse files
app.py
CHANGED
|
@@ -1,216 +1,95 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import os
|
| 3 |
-
api_token = os.getenv("HF_TOKEN")
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 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
|
| 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 |
-
# 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 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
)
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
def
|
| 92 |
-
|
| 93 |
-
|
| 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 |
-
def upload_file(file_obj):
|
| 128 |
-
list_file_path = []
|
| 129 |
-
for idx, file in enumerate(file_obj):
|
| 130 |
-
file_path = file_obj.name
|
| 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)
|
| 176 |
-
with gr.Row():
|
| 177 |
-
doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
|
| 178 |
-
source2_page = gr.Number(label="Page", scale=1)
|
| 179 |
-
with gr.Row():
|
| 180 |
-
doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
|
| 181 |
-
source3_page = gr.Number(label="Page", scale=1)
|
| 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 |
-
# 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 |
-
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from huggingface_hub import InferenceClient
|
| 3 |
import os
|
|
|
|
| 4 |
|
| 5 |
+
# Mock vector database creation
|
| 6 |
+
vector_db_created = False
|
| 7 |
+
|
| 8 |
+
def create_vector_db(uploaded_files):
|
| 9 |
+
global vector_db_created
|
| 10 |
+
if uploaded_files:
|
| 11 |
+
vector_db_created = True
|
| 12 |
+
return "Vector database created successfully. You can now chat with your documents!"
|
| 13 |
+
return "Please upload a file first."
|
| 14 |
+
|
| 15 |
+
# Initialize Chat Model
|
| 16 |
+
client = InferenceClient("meta-llama/Llama-3.2-3B-Instruct")
|
| 17 |
+
|
| 18 |
+
def respond(
|
| 19 |
+
message,
|
| 20 |
+
history: list[tuple[str, str]],
|
| 21 |
+
system_message,
|
| 22 |
+
max_tokens,
|
| 23 |
+
temperature,
|
| 24 |
+
top_p,
|
| 25 |
+
):
|
| 26 |
+
if not vector_db_created:
|
| 27 |
+
yield "Error: Please create the vector database first."
|
| 28 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
messages = [{"role": "system", "content": system_message}]
|
| 31 |
+
for val in history:
|
| 32 |
+
if val[0]:
|
| 33 |
+
messages.append({"role": "user", "content": val[0]})
|
| 34 |
+
if val[1]:
|
| 35 |
+
messages.append({"role": "assistant", "content": val[1]})
|
| 36 |
+
messages.append({"role": "user", "content": message})
|
| 37 |
+
response = ""
|
| 38 |
+
for message in client.chat_completion(
|
| 39 |
+
messages,
|
| 40 |
+
max_tokens=max_tokens,
|
| 41 |
+
stream=True,
|
| 42 |
+
temperature=temperature,
|
| 43 |
+
top_p=top_p,
|
| 44 |
+
):
|
| 45 |
+
token = message.choices[0].delta.content
|
| 46 |
+
response += token
|
| 47 |
+
yield response
|
| 48 |
+
|
| 49 |
+
# Custom CSS
|
| 50 |
+
css = """
|
| 51 |
+
#drop-area { border: 2px dashed #42B3CE; border-radius: 10px; padding: 20px; }
|
| 52 |
+
.error-message { color: red; font-weight: bold; }
|
| 53 |
+
.vector-btn { background-color: #42B3CE !important; color: white; }
|
| 54 |
+
.chat-submit { background-color: #06688E !important; color: white; }
|
| 55 |
+
.chat-clear { background-color: #e0e0e0 !important; color: black; }
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
def main():
|
| 59 |
+
with gr.Blocks(css=css) as demo:
|
| 60 |
+
gr.Markdown("""# **RAG PDF Chatbot**
|
| 61 |
+
Query your PDF documents! Upload, initialize, and chat using an AI assistant.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
+
# Step 1: File upload and database initialization
|
| 65 |
+
with gr.Row():
|
| 66 |
+
with gr.Column():
|
| 67 |
+
pdf_upload = gr.File(label="Upload PDF documents", file_types=[".pdf"], type="file")
|
| 68 |
+
create_db_btn = gr.Button("Create vector database", elem_classes=["vector-btn"])
|
| 69 |
+
db_status = gr.Textbox("Not initialized", interactive=False)
|
| 70 |
+
|
| 71 |
+
with gr.Column():
|
| 72 |
+
gr.Markdown("**Step 2 - Chat with your Document**")
|
| 73 |
+
chatbot = gr.ChatInterface(
|
| 74 |
+
respond,
|
| 75 |
+
additional_inputs=[
|
| 76 |
+
gr.Textbox(
|
| 77 |
+
value="You are a helpful assistant...",
|
| 78 |
+
label="System Message",
|
| 79 |
+
visible=False
|
| 80 |
+
),
|
| 81 |
+
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens", visible=False),
|
| 82 |
+
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature", visible=False),
|
| 83 |
+
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p", visible=False),
|
| 84 |
+
],
|
| 85 |
+
submit_btn="Submit",
|
| 86 |
+
clear_btn="Clear",
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
# Button events
|
| 90 |
+
create_db_btn.click(create_vector_db, inputs=[pdf_upload], outputs=[db_status])
|
| 91 |
+
|
| 92 |
+
demo.launch(share=True)
|
| 93 |
|
| 94 |
if __name__ == "__main__":
|
| 95 |
+
main()
|