Dull / app.py
midrees2806's picture
Update app.py
5b57f0c verified
import gradio as gr
from pdf_bot import create_qa_chain_from_pdf
qa_chain = None # Global chain reference
css = """
#chatbot {
height: 350px;
overflow: auto;
border-radius: 10px;
border: 1px solid #e0e0e0;
}
.textbox {
border-radius: 20px !important;
padding: 12px 20px !important;
}
.btn-column {
display: flex;
flex-direction: column;
gap: 10px;
}
"""
def upload_pdf(pdf_file_path):
global qa_chain
try:
qa_chain = create_qa_chain_from_pdf(pdf_file_path)
return gr.update(visible=True), f"βœ… PDF `{pdf_file_path.split('/')[-1]}` loaded successfully!"
except Exception as e:
return gr.update(visible=False), f"❌ Error: {e}"
def respond(message, chat_history):
global qa_chain
if qa_chain is None:
return message, chat_history + [{"role": "assistant", "content": "⚠️ Please upload a PDF first."}]
try:
result = qa_chain({"query": message})
answer = result["result"]
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": answer})
return "", chat_history
except Exception as e:
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": f"❌ Error: {e}"})
return "", chat_history
def create_interface():
with gr.Blocks(css=css, theme="soft") as demo:
gr.Markdown("""
<h1 style='text-align: center;'>πŸ“˜ University of Education Lahore PDF Chatbot</h1>
<p style='text-align: center;'>Upload a university prospectus or document and ask anything!</p>
""")
pdf_input = gr.File(label="Upload PDF", type="filepath", file_types=[".pdf"])
status = gr.Markdown()
chatbot = gr.Chatbot(elem_id="chatbot", visible=False, type="messages") # βœ… fixed type here
examples = [
"What are the admission requirements?",
"How can I contact the administration?",
"What programs are offered?"
]
with gr.Row():
message = gr.Textbox(
label="Type your question here",
placeholder="Ask about the uploaded PDF...",
elem_classes="textbox",
scale=4
)
with gr.Column(scale=1, elem_classes="btn-column"):
submit_button = gr.Button("↩️ Enter")
reset_button = gr.Button("πŸ—‘οΈ Reset Chat")
pdf_input.change(upload_pdf, inputs=[pdf_input], outputs=[chatbot, status])
message.submit(respond, [message, chatbot], [message, chatbot])
submit_button.click(respond, [message, chatbot], [message, chatbot])
reset_button.click(lambda: [], None, chatbot)
gr.Examples(examples, inputs=message)
return demo
if __name__ == "__main__":
demo = create_interface()
demo.launch()