ChatPDFPlus / v1.txt
shukdevdatta123's picture
Create v1.txt
524940d verified
raw
history blame
9.76 kB
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("""
<div class="main-header">
<h1>πŸ“„ PDF Summarizer with Groq AI</h1>
<p>Upload any PDF document and get an AI-powered summary using Groq's Llama model</p>
</div>
""")
# Info box
gr.HTML("""
<div class="info-box">
<strong>πŸ”‘ How to get your Groq API Key:</strong><br>
1. Visit <a href="https://console.groq.com/" target="_blank">console.groq.com</a><br>
2. Sign up or log in to your account<br>
3. Navigate to API Keys section<br>
4. Create a new API key and copy it<br>
5. Paste it in the field below
</div>
""")
with gr.Row():
with gr.Column(scale=1):
# Input section
gr.Markdown("## πŸ”§ Configuration")
api_key_input = gr.Textbox(
label="Groq API Key",
placeholder="Enter your Groq API key here...",
type="password"
)
gr.Markdown("*Your API key is not stored and only used for this session*")
pdf_file_input = gr.File(
label="Upload PDF Document",
file_types=[".pdf"]
)
gr.Markdown("*Upload any PDF file to summarize*")
with gr.Row():
summarize_btn = gr.Button("πŸ“‹ Generate Summary", variant="primary", size="lg")
clear_btn = gr.Button("πŸ—‘οΈ Clear All", variant="secondary")
with gr.Column(scale=2):
# Output section
gr.Markdown("## πŸ“Š Results")
status_output = gr.Textbox(
label="Status",
interactive=False,
show_label=True
)
with gr.Tabs():
with gr.TabItem("πŸ“ Summary"):
summary_output = gr.Textbox(
label="AI Generated Summary",
lines=15,
interactive=False,
placeholder="Your PDF summary will appear here..."
)
with gr.TabItem("πŸ“„ Extracted Text Preview"):
text_preview_output = gr.Textbox(
label="Extracted Text (First 500 characters)",
lines=10,
interactive=False,
placeholder="Preview of extracted text will appear here..."
)
# Usage instructions
gr.HTML("""
<div class="info-box">
<strong>πŸ“‹ Usage Instructions:</strong><br>
1. Enter your Groq API key in the field above<br>
2. Upload a PDF document (any size, any content)<br>
3. Click "Generate Summary" to process your document<br>
4. View the AI-generated summary and extracted text preview<br>
5. Use "Clear All" to reset all fields
</div>
""")
# Model information
gr.HTML("""
<div style="margin-top: 2rem; padding: 1rem; background-color: #e9ecef; border-radius: 0.5rem;">
<strong>πŸ€– Model Information:</strong><br>
β€’ Model: Llama-3.3-70B-Versatile (via Groq)<br>
β€’ Temperature: 0.3 (focused, factual summaries)<br>
β€’ Max Tokens: 2048 (comprehensive summaries)<br>
β€’ Top-p: 0.9 (balanced creativity and accuracy)
</div>
""")
# Event handlers
summarize_btn.click(
fn=process_pdf_and_summarize,
inputs=[api_key_input, pdf_file_input],
outputs=[status_output, text_preview_output, summary_output],
show_progress=True
)
clear_btn.click(
fn=clear_all,
outputs=[api_key_input, pdf_file_input, status_output, text_preview_output, summary_output]
)
# Launch the app
if __name__ == "__main__":
print("πŸš€ Starting PDF Summarizer App...")
print("πŸ“‹ Make sure you have the required packages installed:")
print(" pip install gradio groq PyPDF2")
print("\nπŸ”‘ Don't forget to get your Groq API key from: https://console.groq.com/")
demo.launch(
server_name="0.0.0.0", # Allow external connections
server_port=7860, # Default port
share=True, # Create shareable link
debug=True, # Enable debug mode
show_error=True # Show detailed errors
)