📄 PDF Summarizer with Groq AI
Upload any PDF document and get an AI-powered summary using Groq's Llama model
import gradio as gr import PyPDF2 import io import os from groq import Groq import tempfile import traceback def extract_text_from_pdf(pdf_file): """Extract text from uploaded PDF file""" try: if pdf_file is None: return None, "No PDF file provided" # Read the PDF file with open(pdf_file.name, 'rb') as file: pdf_reader = PyPDF2.PdfReader(file) text = "" # Extract text from all pages for page_num in range(len(pdf_reader.pages)): page = pdf_reader.pages[page_num] text += page.extract_text() + "\n" if not text.strip(): return None, "Could not extract text from PDF. The PDF might be image-based or encrypted." return text, None except Exception as e: return None, f"Error reading PDF: {str(e)}" def summarize_with_groq(api_key, text): """Generate summary using Groq API""" try: if not api_key or not api_key.strip(): return "Please enter your Groq API key" if not text or not text.strip(): return "No text to summarize" # Initialize Groq client client = Groq(api_key=api_key.strip()) # System prompt for summarization system_prompt = """You are a highly capable language model specialized in document summarization. Your task is to read and understand the full content of a multi-page PDF document and generate a clear, accurate, and detailed summary of the entire document. Focus on capturing all main ideas, key points, arguments, findings, and conclusions presented throughout the document. If the document is technical, legal, academic, or contains structured sections (e.g., introduction, methods, results, discussion), maintain the logical flow and structure while expressing the content in a comprehensive and accessible manner. Avoid unnecessary simplification. Include important details, supporting evidence, and nuanced insights that reflect the depth of the original material. Do not copy the text verbatim. Output only the summary. Do not explain your process. Use a neutral, professional, and informative tone. The summary should provide a full understanding of the document to someone who has not read it.""" # Create completion with optimal hyperparameters completion = client.chat.completions.create( model="llama-3.3-70b-versatile", messages=[ { "role": "system", "content": system_prompt }, { "role": "user", "content": f"Please summarize the following document:\n\n{text}" } ], temperature=0.3, # Low randomness for factual, focused summaries max_completion_tokens=2048, # Increased to allow longer summaries top_p=0.9, # Allows some diversity while still grounded stream=False, stop=None, ) summary = completion.choices[0].message.content return summary except Exception as e: error_msg = f"Error generating summary: {str(e)}" if "authentication" in str(e).lower() or "api" in str(e).lower(): error_msg += "\n\nPlease check your Groq API key and ensure it's valid." return error_msg def process_pdf_and_summarize(api_key, pdf_file, progress=gr.Progress()): """Main function to process PDF and generate summary""" try: if not api_key or not api_key.strip(): return "❌ Please enter your Groq API key", "", "" if pdf_file is None: return "❌ Please upload a PDF file", "", "" progress(0.1, desc="Reading PDF file...") # Extract text from PDF text, error = extract_text_from_pdf(pdf_file) if error: return f"❌ {error}", "", "" progress(0.4, desc="Text extracted successfully...") # Show preview of extracted text text_preview = text[:500] + "..." if len(text) > 500 else text progress(0.6, desc="Generating summary with Groq AI...") # Generate summary summary = summarize_with_groq(api_key, text) progress(1.0, desc="Summary generated successfully!") return "✅ Summary generated successfully!", text_preview, summary except Exception as e: error_traceback = traceback.format_exc() return f"❌ Unexpected error: {str(e)}\n\nTraceback:\n{error_traceback}", "", "" def clear_all(): """Clear all fields""" return "", None, "", "", "" # Custom CSS for better styling css = """ .gradio-container { max-width: 1200px !important; margin: auto !important; } .main-header { text-align: center; margin-bottom: 2rem; } .status-success { color: #28a745 !important; } .status-error { color: #dc3545 !important; } .info-box { background-color: #f8f9fa; padding: 1rem; border-radius: 0.5rem; border-left: 4px solid #007bff; margin: 1rem 0; } """ # Create Gradio interface with gr.Blocks(css=css, title="PDF Summarizer with Groq AI") as demo: # Header gr.HTML("""
Upload any PDF document and get an AI-powered summary using Groq's Llama model