import os import gradio as gr from transformers import pipeline from PyPDF2 import PdfReader # Load free Hugging Face models summarizer = pipeline("summarization", model="facebook/bart-large-cnn") qa_pipeline = pipeline("question-answering", model="distilbert-base-cased-distilled-squad") # Global variable to store PDF text pdf_text_store = "" def extract_text_from_pdf(pdf_file): reader = PdfReader(pdf_file) text = "" for page in reader.pages: page_text = page.extract_text() if page_text: text += page_text + "\n" return text def upload_pdf(file, history): global pdf_text_store pdf_text_store = extract_text_from_pdf(file) if not pdf_text_store.strip(): history.append(("System", "❌ No text could be extracted from the PDF. Please try another PDF.")) return history summary = summarizer(pdf_text_store[:1000], max_length=200, min_length=50, do_sample=False)[0]['summary_text'] history.append(("System", f"✅ PDF processed!\n\n**Summary:**\n{summary}")) return history def chatbot(user_message, history): if not pdf_text_store: history.append((user_message, "❌ Please upload a PDF first.")) return "", history result = qa_pipeline({ 'context': pdf_text_store, 'question': user_message }) answer = result["answer"] history.append((user_message, answer)) return "", history with gr.Blocks(theme=gr.themes.Soft(primary_hue="purple", secondary_hue="blue")) as demo: gr.HTML(""" """) gr.HTML('
📚 Chat with Your PDF
') gr.HTML('
Upload a PDF, get a summary, and chat with it!
') with gr.Row(): with gr.Column(scale=1, min_width=250): with gr.Group(elem_classes="upload-box"): gr.Markdown("### 📂 Upload Your PDF") pdf_upload = gr.File(label="Upload PDF", file_types=[".pdf"]) upload_btn = gr.Button("🚀 Process PDF", elem_classes="custom-btn") with gr.Column(scale=2): chatbot_ui = gr.Chatbot( label="💬 Chat with your PDF", height=500, show_copy_button=True, elem_classes="chat-area" ) user_input = gr.Textbox( placeholder="Ask something about your PDF...", show_label=False ) upload_btn.click(upload_pdf, inputs=[pdf_upload, chatbot_ui], outputs=chatbot_ui) user_input.submit(chatbot, [user_input, chatbot_ui], [user_input, chatbot_ui]) gr.HTML("""
Made with ❤️ – No API keys needed!
""") if __name__ == "__main__": demo.launch()