sohampawar1030 commited on
Commit
709ebd3
Β·
verified Β·
1 Parent(s): 2cfaaf2

Upload 2 files

Browse files
Files changed (2) hide show
  1. requirements.txt +6 -0
  2. summarization_app.py +205 -0
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ streamlit==1.9.0
2
+ groq==1.0.0
3
+ python-dotenv==0.20.0
4
+ PyPDF2==1.26.0
5
+ reportlab==3.6.2
6
+ Pillow==9.0.0
summarization_app.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ from groq import Groq
4
+ from dotenv import load_dotenv
5
+ from PyPDF2 import PdfReader, PdfWriter
6
+ from io import BytesIO
7
+ from reportlab.lib.pagesizes import letter
8
+ from reportlab.pdfgen import canvas
9
+ from PIL import Image
10
+
11
+ # Load environment variables
12
+ load_dotenv()
13
+
14
+ # Initialize Groq API client
15
+ client = Groq(
16
+ api_key=os.environ.get("GROQ_API_KEY"), # Ensure this is defined in your .env file
17
+ )
18
+
19
+ # Function to summarize text using Groq API
20
+ def summarize_text_groq(input_text, model="llama-3.3-70b-versatile", max_tokens=150):
21
+ try:
22
+ response = client.chat.completions.create(
23
+ messages=[
24
+ {
25
+ "role": "system",
26
+ "content": "You are a helpful assistant.",
27
+ },
28
+ {
29
+ "role": "user",
30
+ "content": f"Summarize the following text:\n\n{input_text}",
31
+ },
32
+ ],
33
+ model=model,
34
+ )
35
+ return response.choices[0].message.content.strip()
36
+ except Exception as e:
37
+ raise RuntimeError(f"API call failed: {e}")
38
+
39
+ # Function to extract text from a PDF file
40
+ def extract_text_from_pdf(uploaded_pdf):
41
+ try:
42
+ pdf_reader = PdfReader(uploaded_pdf)
43
+ if pdf_reader.is_encrypted:
44
+ st.error("❌ The uploaded PDF is encrypted and cannot be processed.")
45
+ return ""
46
+ text = ""
47
+ for page in pdf_reader.pages:
48
+ text += page.extract_text() or "" # Handle pages with no text gracefully
49
+ if not text.strip():
50
+ raise RuntimeError("No extractable text found in the PDF.")
51
+ return text
52
+ except Exception as e:
53
+ raise RuntimeError(f"Failed to extract text from PDF: {e}")
54
+
55
+ # Function to save summary as a PDF
56
+ def save_summary_to_pdf(summary_text):
57
+ try:
58
+ # Use BytesIO to create an in-memory PDF
59
+ summary_stream = BytesIO()
60
+ c = canvas.Canvas(summary_stream, pagesize=letter)
61
+ c.drawString(100, 750, "Summary:")
62
+ text_object = c.beginText(100, 730) # Start the text object at this position
63
+ text_object.setFont("Helvetica", 10)
64
+
65
+ # Split text into lines for better formatting
66
+ lines = summary_text.splitlines()
67
+ for line in lines:
68
+ text_object.textLine(line)
69
+
70
+ c.drawText(text_object)
71
+ c.save()
72
+
73
+ # Seek to the start of the BytesIO stream
74
+ summary_stream.seek(0)
75
+ return summary_stream
76
+ except Exception as e:
77
+ raise RuntimeError(f"Failed to save summary to PDF: {e}")
78
+
79
+ # Streamlit App Setup
80
+ st.set_page_config(page_title="Text Summarization App", page_icon="πŸ“š", layout="wide")
81
+ st.title("πŸ“š Text Summarization App with Groq API")
82
+
83
+ # Custom CSS styling
84
+ st.markdown("""
85
+ <style>
86
+ .main {
87
+ background-color: #f4f7fc;
88
+ padding: 20px;
89
+ }
90
+ .stButton>button {
91
+ background-color: #4CAF50;
92
+ color: white;
93
+ border: none;
94
+ padding: 15px 32px;
95
+ font-size: 16px;
96
+ cursor: pointer;
97
+ border-radius: 5px;
98
+ margin-top: 20px;
99
+ }
100
+ .stButton>button:hover {
101
+ background-color: #45a049;
102
+ }
103
+ .stTextInput>div>div>input {
104
+ font-size: 16px;
105
+ padding: 10px;
106
+ border-radius: 5px;
107
+ border: 1px solid #ccc;
108
+ }
109
+ </style>
110
+ """, unsafe_allow_html=True)
111
+
112
+ # Instructions or greeting
113
+ st.markdown("""
114
+ <div style="font-size: 18px; color: #444;">
115
+ Welcome to the Text Summarization App! You can enter text or upload a PDF to get a concise summary using Groq API. Feel free to explore the tabs below.
116
+ </div>
117
+ """, unsafe_allow_html=True)
118
+
119
+ # Tabs for manual text and PDF upload
120
+ tab1, tab2, tab3 = st.tabs(["Manual Text Input", "PDF Upload", "πŸ—£οΈ Chat with Bot"])
121
+
122
+ # Manual Text Input Tab
123
+ with tab1:
124
+ st.subheader("πŸ“ Enter Your Text")
125
+ input_text = st.text_area("Enter the text to summarize", height=200, max_chars=2000)
126
+ if st.button("πŸ” Summarize Text"):
127
+ if input_text:
128
+ with st.spinner("Summarizing your text..."):
129
+ try:
130
+ summary = summarize_text_groq(input_text)
131
+ st.success("βœ… Summary:")
132
+ st.write(summary)
133
+ except Exception as e:
134
+ st.error(f"❌ An error occurred: {e}")
135
+ else:
136
+ st.warning("⚠️ Please enter some text to summarize!")
137
+
138
+ # PDF Upload Tab
139
+ with tab2:
140
+ st.subheader("πŸ“€ Upload a PDF for Summarization")
141
+ uploaded_pdf = st.file_uploader("Upload PDF", type=["pdf"])
142
+ if uploaded_pdf is not None:
143
+ with st.spinner("Extracting text from PDF..."):
144
+ try:
145
+ extracted_text = extract_text_from_pdf(uploaded_pdf)
146
+ st.success("βœ… Text extracted from PDF.")
147
+ st.text_area("πŸ“„ Extracted Text:", extracted_text, height=200)
148
+
149
+ if st.button("πŸ” Summarize PDF"):
150
+ with st.spinner("Summarizing the extracted text..."):
151
+ try:
152
+ summary = summarize_text_groq(extracted_text)
153
+ st.success("βœ… PDF Summary:")
154
+ st.write(summary)
155
+
156
+ # Save the summary to a new PDF
157
+ summary_pdf = save_summary_to_pdf(summary)
158
+ st.download_button(
159
+ label="πŸ’Ύ Download Summary PDF",
160
+ data=summary_pdf,
161
+ file_name="summary.pdf",
162
+ mime="application/pdf",
163
+ )
164
+ except Exception as e:
165
+ st.error(f"❌ An error occurred: {e}")
166
+ except RuntimeError as e:
167
+ st.error(f"❌ {e}")
168
+
169
+ # Chat with Bot Tab
170
+ with tab3:
171
+ st.subheader("πŸ—£οΈ Chat with the Bot")
172
+ if "messages" not in st.session_state:
173
+ st.session_state.messages = [{"role": "system", "content": "You are a helpful assistant."}]
174
+
175
+ # Display chat history
176
+ for message in st.session_state.messages:
177
+ if message["role"] == "user":
178
+ st.write(f"**User**: {message['content']}")
179
+ else:
180
+ st.write(f"**Bot**: {message['content']}")
181
+
182
+ user_input = st.text_input("Type your message:", "")
183
+
184
+ if st.button("Send Message"):
185
+ if user_input:
186
+ # Add user input to chat history
187
+ st.session_state.messages.append({"role": "user", "content": user_input})
188
+
189
+ # Get bot's response
190
+ with st.spinner("Bot is typing..."):
191
+ try:
192
+ response = client.chat.completions.create(
193
+ messages=st.session_state.messages,
194
+ model="llama-3.3-70b-versatile", # Groq model
195
+ )
196
+ bot_message = response.choices[0].message.content.strip()
197
+
198
+ # Add bot response to chat history
199
+ st.session_state.messages.append({"role": "assistant", "content": bot_message})
200
+
201
+ st.write(f"**Bot**: {bot_message}")
202
+ except Exception as e:
203
+ st.error(f"❌ An error occurred: {e}")
204
+ else:
205
+ st.warning("⚠️ Please enter a message to send.")