import gradio as gr from transformers import pipeline, AutoTokenizer import pdfplumber from docx import Document # ✅ Load tokenizer and summarization model MODEL_NAME = "facebook/bart-large-cnn" tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, local_files_only=False, force_download=True) summarizer = pipeline("summarization", model=MODEL_NAME, tokenizer=MODEL_NAME, device=-1) # ✅ Function to extract text from different file formats def extract_text(file): if file is None: return "No file uploaded." file_name = file.name.lower() try: if file_name.endswith(".pdf"): with pdfplumber.open(file.name) as pdf: text = "\n".join([page.extract_text() for page in pdf.pages if page.extract_text()]) elif file_name.endswith(".docx"): doc = Document(file.name) text = "\n".join([para.text for para in doc.paragraphs]) elif file_name.endswith(".txt"): text = file.read().decode("utf-8") else: return "❌ Unsupported file format. Please upload a PDF, DOCX, or TXT file." return text if text.strip() else "⚠ No readable text found in the file." except Exception as e: return f"❌ Error reading file: {str(e)}" # ✅ Function to summarize text def summarize_text(text, file): # If file uploaded, extract text if file is not None: text = extract_text(file) # Ensure valid text and truncate to 1024 tokens if text.strip() and "Error" not in text: inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=1024) summary = summarizer(tokenizer.decode(inputs["input_ids"][0]), max_length=150, min_length=50, do_sample=False) return summary[0]["summary_text"] else: return "⚠ No valid text found to summarize." # ✅ Gradio Interface with Footer app = gr.Blocks() with app: gr.Markdown("## 📝 AI-Powered Text Summarization") gr.Markdown("📄 Upload a document or enter text to get a concise AI-generated summary.") with gr.Row(): text_input = gr.Textbox(lines=10, placeholder="📌 Enter text here or upload a file below ⬇") file_input = gr.File(label="📂 Upload File (PDF, DOCX, TXT)") output_text = gr.Textbox(label="📃 Summarized Text") summarize_button = gr.Button("✨ Summarize") summarize_button.click(summarize_text, inputs=[text_input, file_input], outputs=output_text) # ✅ Footer gr.Markdown("---") # ✅ Fixed Footer with Clickable Links gr.HTML( """
""" ) # ✅ Launch App if __name__ == "__main__": app.launch(debug=True)