shukdevdatta123 commited on
Commit
00d8689
Β·
verified Β·
1 Parent(s): ef2ec1a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +262 -0
app.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import PyPDF2
3
+ import io
4
+ import os
5
+ from groq import Groq
6
+ import tempfile
7
+ import traceback
8
+
9
+ def extract_text_from_pdf(pdf_file):
10
+ """Extract text from uploaded PDF file"""
11
+ try:
12
+ if pdf_file is None:
13
+ return None, "No PDF file provided"
14
+
15
+ # Read the PDF file
16
+ with open(pdf_file.name, 'rb') as file:
17
+ pdf_reader = PyPDF2.PdfReader(file)
18
+ text = ""
19
+
20
+ # Extract text from all pages
21
+ for page_num in range(len(pdf_reader.pages)):
22
+ page = pdf_reader.pages[page_num]
23
+ text += page.extract_text() + "\n"
24
+
25
+ if not text.strip():
26
+ return None, "Could not extract text from PDF. The PDF might be image-based or encrypted."
27
+
28
+ return text, None
29
+
30
+ except Exception as e:
31
+ return None, f"Error reading PDF: {str(e)}"
32
+
33
+ def summarize_with_groq(api_key, text):
34
+ """Generate summary using Groq API"""
35
+ try:
36
+ if not api_key or not api_key.strip():
37
+ return "Please enter your Groq API key"
38
+
39
+ if not text or not text.strip():
40
+ return "No text to summarize"
41
+
42
+ # Initialize Groq client
43
+ client = Groq(api_key=api_key.strip())
44
+
45
+ # System prompt for summarization
46
+ 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 concise summary of the entire document.
47
+
48
+ Focus on the main ideas, key points, arguments, and conclusions presented throughout the document. If the document is technical, legal, academic, or contains structured sections (e.g., introduction, methods, results, discussion), preserve the logical flow while simplifying complex language. Do not include irrelevant details or copy the text verbatim.
49
+
50
+ Output only the summary. Do not explain your process. Maintain a neutral and informative tone. Your summary should be useful to someone who has not read the original document but needs to understand its overall purpose and content."""
51
+
52
+ # Create completion with optimal hyperparameters
53
+ completion = client.chat.completions.create(
54
+ model="llama-3.3-70b-versatile",
55
+ messages=[
56
+ {
57
+ "role": "system",
58
+ "content": system_prompt
59
+ },
60
+ {
61
+ "role": "user",
62
+ "content": f"Please summarize the following document:\n\n{text}"
63
+ }
64
+ ],
65
+ temperature=0.3, # Low randomness for factual, focused summaries
66
+ max_completion_tokens=2048, # Increased to allow longer summaries
67
+ top_p=0.9, # Allows some diversity while still grounded
68
+ stream=False,
69
+ stop=None,
70
+ )
71
+
72
+ summary = completion.choices[0].message.content
73
+ return summary
74
+
75
+ except Exception as e:
76
+ error_msg = f"Error generating summary: {str(e)}"
77
+ if "authentication" in str(e).lower() or "api" in str(e).lower():
78
+ error_msg += "\n\nPlease check your Groq API key and ensure it's valid."
79
+ return error_msg
80
+
81
+ def process_pdf_and_summarize(api_key, pdf_file, progress=gr.Progress()):
82
+ """Main function to process PDF and generate summary"""
83
+ try:
84
+ if not api_key or not api_key.strip():
85
+ return "❌ Please enter your Groq API key", "", ""
86
+
87
+ if pdf_file is None:
88
+ return "❌ Please upload a PDF file", "", ""
89
+
90
+ progress(0.1, desc="Reading PDF file...")
91
+
92
+ # Extract text from PDF
93
+ text, error = extract_text_from_pdf(pdf_file)
94
+ if error:
95
+ return f"❌ {error}", "", ""
96
+
97
+ progress(0.4, desc="Text extracted successfully...")
98
+
99
+ # Show preview of extracted text
100
+ text_preview = text[:500] + "..." if len(text) > 500 else text
101
+
102
+ progress(0.6, desc="Generating summary with Groq AI...")
103
+
104
+ # Generate summary
105
+ summary = summarize_with_groq(api_key, text)
106
+
107
+ progress(1.0, desc="Summary generated successfully!")
108
+
109
+ return "βœ… Summary generated successfully!", text_preview, summary
110
+
111
+ except Exception as e:
112
+ error_traceback = traceback.format_exc()
113
+ return f"❌ Unexpected error: {str(e)}\n\nTraceback:\n{error_traceback}", "", ""
114
+
115
+ def clear_all():
116
+ """Clear all fields"""
117
+ return "", None, "", "", ""
118
+
119
+ # Custom CSS for better styling
120
+ css = """
121
+ .gradio-container {
122
+ max-width: 1200px !important;
123
+ margin: auto !important;
124
+ }
125
+ .main-header {
126
+ text-align: center;
127
+ margin-bottom: 2rem;
128
+ }
129
+ .status-success {
130
+ color: #28a745 !important;
131
+ }
132
+ .status-error {
133
+ color: #dc3545 !important;
134
+ }
135
+ .info-box {
136
+ background-color: #f8f9fa;
137
+ padding: 1rem;
138
+ border-radius: 0.5rem;
139
+ border-left: 4px solid #007bff;
140
+ margin: 1rem 0;
141
+ }
142
+ """
143
+
144
+ # Create Gradio interface
145
+ with gr.Blocks(css=css, title="PDF Summarizer with Groq AI") as demo:
146
+ # Header
147
+ gr.HTML("""
148
+ <div class="main-header">
149
+ <h1>πŸ“„ PDF Summarizer with Groq AI</h1>
150
+ <p>Upload any PDF document and get an AI-powered summary using Groq's Llama model</p>
151
+ </div>
152
+ """)
153
+
154
+ # Info box
155
+ gr.HTML("""
156
+ <div class="info-box">
157
+ <strong>πŸ”‘ How to get your Groq API Key:</strong><br>
158
+ 1. Visit <a href="https://console.groq.com/" target="_blank">console.groq.com</a><br>
159
+ 2. Sign up or log in to your account<br>
160
+ 3. Navigate to API Keys section<br>
161
+ 4. Create a new API key and copy it<br>
162
+ 5. Paste it in the field below
163
+ </div>
164
+ """)
165
+
166
+ with gr.Row():
167
+ with gr.Column(scale=1):
168
+ # Input section
169
+ gr.Markdown("## πŸ”§ Configuration")
170
+ api_key_input = gr.Textbox(
171
+ label="Groq API Key",
172
+ placeholder="Enter your Groq API key here...",
173
+ type="password",
174
+ info="Your API key is not stored and only used for this session"
175
+ )
176
+
177
+ pdf_file_input = gr.File(
178
+ label="Upload PDF Document",
179
+ file_types=[".pdf"],
180
+ info="Upload any PDF file to summarize"
181
+ )
182
+
183
+ with gr.Row():
184
+ summarize_btn = gr.Button("πŸ“‹ Generate Summary", variant="primary", size="lg")
185
+ clear_btn = gr.Button("πŸ—‘οΈ Clear All", variant="secondary")
186
+
187
+ with gr.Column(scale=2):
188
+ # Output section
189
+ gr.Markdown("## πŸ“Š Results")
190
+ status_output = gr.Textbox(
191
+ label="Status",
192
+ interactive=False,
193
+ show_label=True
194
+ )
195
+
196
+ with gr.Tabs():
197
+ with gr.TabItem("πŸ“ Summary"):
198
+ summary_output = gr.Textbox(
199
+ label="AI Generated Summary",
200
+ lines=15,
201
+ interactive=False,
202
+ placeholder="Your PDF summary will appear here..."
203
+ )
204
+
205
+ with gr.TabItem("πŸ“„ Extracted Text Preview"):
206
+ text_preview_output = gr.Textbox(
207
+ label="Extracted Text (First 500 characters)",
208
+ lines=10,
209
+ interactive=False,
210
+ placeholder="Preview of extracted text will appear here..."
211
+ )
212
+
213
+ # Usage instructions
214
+ gr.HTML("""
215
+ <div class="info-box">
216
+ <strong>πŸ“‹ Usage Instructions:</strong><br>
217
+ 1. Enter your Groq API key in the field above<br>
218
+ 2. Upload a PDF document (any size, any content)<br>
219
+ 3. Click "Generate Summary" to process your document<br>
220
+ 4. View the AI-generated summary and extracted text preview<br>
221
+ 5. Use "Clear All" to reset all fields
222
+ </div>
223
+ """)
224
+
225
+ # Model information
226
+ gr.HTML("""
227
+ <div style="margin-top: 2rem; padding: 1rem; background-color: #e9ecef; border-radius: 0.5rem;">
228
+ <strong>πŸ€– Model Information:</strong><br>
229
+ β€’ Model: Llama-3.3-70B-Versatile (via Groq)<br>
230
+ β€’ Temperature: 0.3 (focused, factual summaries)<br>
231
+ β€’ Max Tokens: 2048 (comprehensive summaries)<br>
232
+ β€’ Top-p: 0.9 (balanced creativity and accuracy)
233
+ </div>
234
+ """)
235
+
236
+ # Event handlers
237
+ summarize_btn.click(
238
+ fn=process_pdf_and_summarize,
239
+ inputs=[api_key_input, pdf_file_input],
240
+ outputs=[status_output, text_preview_output, summary_output],
241
+ show_progress=True
242
+ )
243
+
244
+ clear_btn.click(
245
+ fn=clear_all,
246
+ outputs=[api_key_input, pdf_file_input, status_output, text_preview_output, summary_output]
247
+ )
248
+
249
+ # Launch the app
250
+ if __name__ == "__main__":
251
+ print("πŸš€ Starting PDF Summarizer App...")
252
+ print("πŸ“‹ Make sure you have the required packages installed:")
253
+ print(" pip install gradio groq PyPDF2")
254
+ print("\nπŸ”‘ Don't forget to get your Groq API key from: https://console.groq.com/")
255
+
256
+ demo.launch(
257
+ server_name="0.0.0.0", # Allow external connections
258
+ server_port=7860, # Default port
259
+ share=True, # Create shareable link
260
+ debug=True, # Enable debug mode
261
+ show_error=True # Show detailed errors
262
+ )