chatbot / app.py
hema05core's picture
Update app.py
d799a5a verified
raw
history blame
2.85 kB
import os
import gradio as gr
from langchain.text_splitter import CharacterTextSplitter
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from langchain.chains import ConversationalRetrievalChain
from langchain_community.llms import HuggingFaceHub
from langchain_community.document_loaders import PyPDFLoader
# Load PDF
loader = PyPDFLoader("chimera.pdf")
documents = loader.load()
# Split documents
text_splitter = CharacterTextSplitter(chunk_size=800, chunk_overlap=100)
texts = text_splitter.split_documents(documents)
# Embeddings
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
db = FAISS.from_documents(texts, embeddings)
retriever = db.as_retriever(search_kwargs={"k": 3})
# Hugging Face Hub LLM
hf_token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
if hf_token is None:
raise ValueError("HUGGINGFACEHUB_API_TOKEN not set in Space Secrets!")
llm = HuggingFaceHub(
repo_id="google/flan-t5-base",
model_kwargs={"temperature": 0},
huggingfacehub_api_token=hf_token
)
qa = ConversationalRetrievalChain.from_llm(
llm,
retriever=retriever
)
chat_history = []
def respond(message, history):
history = history[-6:]
result = qa({"question": message, "chat_history": history})
history.append((message, result["answer"]))
return history, history
with gr.Blocks() as demo:
with gr.Column():
warning_text = gr.HTML(
"<div style='background-color:black;color:white;padding:20px;'>⚠ WARNING: Investigative Simulation ⚠<br>Are you ready?</div>"
)
enter_btn = gr.Button("Enter the Case")
exit_btn = gr.Button("Exit")
chatbot = gr.Chatbot(visible=False)
user_input = gr.Textbox(placeholder="Type here...", visible=False)
submit_btn = gr.Button("Send", visible=False)
def enter_case():
return (
gr.update(visible=True),
gr.update(visible=True),
gr.update(visible=True),
gr.update(value=""),
gr.update(visible=False),
gr.update(visible=False)
)
def exit_case():
return (
gr.update(value="Session ended."),
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False)
)
enter_btn.click(enter_case, inputs=None, outputs=[chatbot, user_input, submit_btn, warning_text, enter_btn, exit_btn])
exit_btn.click(exit_case, inputs=None, outputs=[warning_text, chatbot, user_input, submit_btn, enter_btn, exit_btn])
submit_btn.click(respond, inputs=[user_input, chatbot], outputs=[chatbot, chatbot])
if __name__ == "__main__":
demo.launch(share=True, enable_queue=True)