import gradio as gr from transformers import AutoTokenizer, AutoModelForSeq2SeqLM from sentence_transformers import SentenceTransformer import faiss import numpy as np from pypdf import PdfReader # ================================ # 🔹 LOAD MODELS (SAFE) # ================================ model_name = "google/flan-t5-small" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSeq2SeqLM.from_pretrained(model_name) embedder = SentenceTransformer("all-MiniLM-L6-v2") index = None chunks = None # ================================ # 🔹 PROCESS PDF # ================================ def process_pdf(file): global index, chunks if file is None: return "⚠️ Please upload a PDF" reader = PdfReader(file.name) text = "" for page in reader.pages: content = page.extract_text() if content: text += content + "\n" # Split text chunks = [] for i in range(0, len(text), 400): chunks.append(text[i:i+500]) # Create embeddings embeddings = embedder.encode(chunks) dimension = embeddings.shape[1] index = faiss.IndexFlatL2(dimension) index.add(np.array(embeddings)) return "✅ PDF processed successfully!" # ================================ # 🔹 GENERATE ANSWER # ================================ def generate_answer(prompt): inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512) outputs = model.generate(**inputs, max_new_tokens=150) return tokenizer.decode(outputs[0], skip_special_tokens=True) # ================================ # 🔹 QA FUNCTION # ================================ def answer_question(question): global index, chunks if index is None: return "⚠️ Upload a PDF first." q_embedding = embedder.encode([question]) _, indices = index.search(np.array(q_embedding), k=3) context = " ".join([chunks[i] for i in indices[0]]) prompt = f""" Answer using the context below. Context: {context} Question: {question} Answer: """ return generate_answer(prompt) # ================================ # 🔹 CHAT FUNCTION # ================================ def chat(message, history): response = answer_question(message) history.append((message, response)) return "", history # ================================ # 🔹 BEAUTIFUL UI # ================================ custom_css = """ body { background: linear-gradient(135deg, #1e3c72, #2a5298); } .gradio-container { background: transparent !important; } .message.user { background: #2563eb !important; color: white !important; border-radius: 15px; } .message.bot { background: #10b981 !important; color: white !important; border-radius: 15px; } textarea { border-radius: 10px !important; } button { background: #4f46e5 !important; color: white !important; border-radius: 10px !important; } footer {visibility: hidden;} """ # ================================ # 🔹 UI # ================================ with gr.Blocks(css=custom_css) as demo: gr.Markdown("## 📘 Course Chatbot") gr.Markdown("Upload PDF and ask questions") file = gr.File(label="Upload PDF") status = gr.Textbox(label="Status", interactive=False) upload_btn = gr.Button("Process PDF") chatbot = gr.Chatbot() msg = gr.Textbox(placeholder="Ask your question...") upload_btn.click(process_pdf, inputs=file, outputs=status) msg.submit(chat, inputs=[msg, chatbot], outputs=[msg, chatbot]) demo.launch()