|
import streamlit as st
|
|
import os
|
|
from groq import Groq
|
|
from dotenv import load_dotenv
|
|
from PyPDF2 import PdfReader, PdfWriter
|
|
from io import BytesIO
|
|
from reportlab.lib.pagesizes import letter
|
|
from reportlab.pdfgen import canvas
|
|
from PIL import Image
|
|
|
|
|
|
load_dotenv()
|
|
|
|
|
|
client = Groq(
|
|
api_key=os.environ.get("GROQ_API_KEY"),
|
|
)
|
|
|
|
|
|
def summarize_text_groq(input_text, model="llama-3.3-70b-versatile", max_tokens=150):
|
|
try:
|
|
response = client.chat.completions.create(
|
|
messages=[
|
|
{
|
|
"role": "system",
|
|
"content": "You are a helpful assistant.",
|
|
},
|
|
{
|
|
"role": "user",
|
|
"content": f"Summarize the following text:\n\n{input_text}",
|
|
},
|
|
],
|
|
model=model,
|
|
)
|
|
return response.choices[0].message.content.strip()
|
|
except Exception as e:
|
|
raise RuntimeError(f"API call failed: {e}")
|
|
|
|
|
|
def extract_text_from_pdf(uploaded_pdf):
|
|
try:
|
|
pdf_reader = PdfReader(uploaded_pdf)
|
|
if pdf_reader.is_encrypted:
|
|
st.error("β The uploaded PDF is encrypted and cannot be processed.")
|
|
return ""
|
|
text = ""
|
|
for page in pdf_reader.pages:
|
|
text += page.extract_text() or ""
|
|
if not text.strip():
|
|
raise RuntimeError("No extractable text found in the PDF.")
|
|
return text
|
|
except Exception as e:
|
|
raise RuntimeError(f"Failed to extract text from PDF: {e}")
|
|
|
|
|
|
def save_summary_to_pdf(summary_text):
|
|
try:
|
|
|
|
summary_stream = BytesIO()
|
|
c = canvas.Canvas(summary_stream, pagesize=letter)
|
|
c.drawString(100, 750, "Summary:")
|
|
text_object = c.beginText(100, 730)
|
|
text_object.setFont("Helvetica", 10)
|
|
|
|
|
|
lines = summary_text.splitlines()
|
|
for line in lines:
|
|
text_object.textLine(line)
|
|
|
|
c.drawText(text_object)
|
|
c.save()
|
|
|
|
|
|
summary_stream.seek(0)
|
|
return summary_stream
|
|
except Exception as e:
|
|
raise RuntimeError(f"Failed to save summary to PDF: {e}")
|
|
|
|
|
|
st.set_page_config(page_title="Text Summarization App", page_icon="π", layout="wide")
|
|
st.title("π Text Summarization App with Groq API")
|
|
|
|
|
|
st.markdown("""
|
|
<style>
|
|
.main {
|
|
background-color: #f4f7fc;
|
|
padding: 20px;
|
|
}
|
|
.stButton>button {
|
|
background-color: #4CAF50;
|
|
color: white;
|
|
border: none;
|
|
padding: 15px 32px;
|
|
font-size: 16px;
|
|
cursor: pointer;
|
|
border-radius: 5px;
|
|
margin-top: 20px;
|
|
}
|
|
.stButton>button:hover {
|
|
background-color: #45a049;
|
|
}
|
|
.stTextInput>div>div>input {
|
|
font-size: 16px;
|
|
padding: 10px;
|
|
border-radius: 5px;
|
|
border: 1px solid #ccc;
|
|
}
|
|
</style>
|
|
""", unsafe_allow_html=True)
|
|
|
|
|
|
st.markdown("""
|
|
<div style="font-size: 18px; color: #444;">
|
|
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.
|
|
</div>
|
|
""", unsafe_allow_html=True)
|
|
|
|
|
|
tab1, tab2, tab3 = st.tabs(["Manual Text Input", "PDF Upload", "π£οΈ Chat with Bot"])
|
|
|
|
|
|
with tab1:
|
|
st.subheader("π Enter Your Text")
|
|
input_text = st.text_area("Enter the text to summarize", height=200, max_chars=2000)
|
|
if st.button("π Summarize Text"):
|
|
if input_text:
|
|
with st.spinner("Summarizing your text..."):
|
|
try:
|
|
summary = summarize_text_groq(input_text)
|
|
st.success("β
Summary:")
|
|
st.write(summary)
|
|
except Exception as e:
|
|
st.error(f"β An error occurred: {e}")
|
|
else:
|
|
st.warning("β οΈ Please enter some text to summarize!")
|
|
|
|
|
|
with tab2:
|
|
st.subheader("π€ Upload a PDF for Summarization")
|
|
uploaded_pdf = st.file_uploader("Upload PDF", type=["pdf"])
|
|
if uploaded_pdf is not None:
|
|
with st.spinner("Extracting text from PDF..."):
|
|
try:
|
|
extracted_text = extract_text_from_pdf(uploaded_pdf)
|
|
st.success("β
Text extracted from PDF.")
|
|
st.text_area("π Extracted Text:", extracted_text, height=200)
|
|
|
|
if st.button("π Summarize PDF"):
|
|
with st.spinner("Summarizing the extracted text..."):
|
|
try:
|
|
summary = summarize_text_groq(extracted_text)
|
|
st.success("β
PDF Summary:")
|
|
st.write(summary)
|
|
|
|
|
|
summary_pdf = save_summary_to_pdf(summary)
|
|
st.download_button(
|
|
label="πΎ Download Summary PDF",
|
|
data=summary_pdf,
|
|
file_name="summary.pdf",
|
|
mime="application/pdf",
|
|
)
|
|
except Exception as e:
|
|
st.error(f"β An error occurred: {e}")
|
|
except RuntimeError as e:
|
|
st.error(f"β {e}")
|
|
|
|
|
|
with tab3:
|
|
st.subheader("π£οΈ Chat with the Bot")
|
|
if "messages" not in st.session_state:
|
|
st.session_state.messages = [{"role": "system", "content": "You are a helpful assistant."}]
|
|
|
|
|
|
for message in st.session_state.messages:
|
|
if message["role"] == "user":
|
|
st.write(f"**User**: {message['content']}")
|
|
else:
|
|
st.write(f"**Bot**: {message['content']}")
|
|
|
|
user_input = st.text_input("Type your message:", "")
|
|
|
|
if st.button("Send Message"):
|
|
if user_input:
|
|
|
|
st.session_state.messages.append({"role": "user", "content": user_input})
|
|
|
|
|
|
with st.spinner("Bot is typing..."):
|
|
try:
|
|
response = client.chat.completions.create(
|
|
messages=st.session_state.messages,
|
|
model="llama-3.3-70b-versatile",
|
|
)
|
|
bot_message = response.choices[0].message.content.strip()
|
|
|
|
|
|
st.session_state.messages.append({"role": "assistant", "content": bot_message})
|
|
|
|
st.write(f"**Bot**: {bot_message}")
|
|
except Exception as e:
|
|
st.error(f"β An error occurred: {e}")
|
|
else:
|
|
st.warning("β οΈ Please enter a message to send.")
|
|
|