File size: 5,406 Bytes
26704f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import streamlit as st
from transformers import pipeline
from graphviz import Digraph
import pdfplumber
from fpdf import FPDF
import tempfile
import os
import requests

# ------------- PAGE SETUP -------------
st.set_page_config(page_title="Visual Summarizer", page_icon="🧠", layout="centered")

# ------------- THEME TOGGLE -------------
theme = st.sidebar.radio("πŸŒ— Theme", ["Light", "Dark"])
summary_type = st.sidebar.selectbox("πŸ“ Summary Length", ["Brief", "Standard", "Detailed"])
translate_to = st.sidebar.selectbox("🌐 Translate Summary To", ["None", "Urdu", "French", "Spanish"])

if theme == "Dark":
    bg_color = "#212121"
    text_color = "white"
    card_bg = "#424242"
else:
    bg_color = "#f7fafd"
    text_color = "#333"
    card_bg = "#e3f2fd"

st.markdown(f"""
    <style>
    body {{ background-color: {bg_color}; color: {text_color}; }}
    .summary-card {{
        background-color: {card_bg};
        padding: 15px;
        border-radius: 10px;
        box-shadow: 2px 2px 6px #aaa;
        color: {text_color};
    }}
    .title {{ text-align: center; font-size: 32px; color: #4A148C; }}
    .subtitle {{ text-align: center; color: gray; }}
    </style>
""", unsafe_allow_html=True)

# ------------- LOAD SUMMARIZER -------------
@st.cache_resource
def load_model():
    return pipeline("summarization", model="facebook/bart-large-cnn")

summarizer = load_model()

# ------------- HEADER -------------
st.markdown("<h1 class='title'>🧠 Visual Text Summarizer & Learner</h1>", unsafe_allow_html=True)
st.markdown("<p class='subtitle'>Summarize, visualize, download, translate, and even explore YouTube to learn more!</p>", unsafe_allow_html=True)
st.markdown("---")

# ------------- INPUT SECTION -------------
text_input = st.text_area("πŸ“₯ Paste your text here (or upload a file below):", height=250)
uploaded_file = st.file_uploader("πŸ“„ Upload a .txt or .pdf file", type=["txt", "pdf"])

def extract_text(file):
    if file.name.endswith(".txt"):
        return file.read().decode("utf-8")
    elif file.name.endswith(".pdf"):
        with pdfplumber.open(file) as pdf:
            return "\n".join([page.extract_text() for page in pdf.pages if page.extract_text()])
    return ""

input_text = extract_text(uploaded_file) if uploaded_file else text_input

# ------------- SUMMARY LENGTH CONFIG -------------
if summary_type == "Brief":
    max_len, min_len = 60, 20
elif summary_type == "Detailed":
    max_len, min_len = 200, 50
else:
    max_len, min_len = 130, 30

# ------------- TRANSLATION FUNCTION -------------
def translate_text(text, lang_code):
    try:
        url = "https://translate.googleapis.com/translate_a/single"
        params = {
            "client": "gtx",
            "sl": "en",
            "tl": lang_code,
            "dt": "t",
            "q": text
        }
        response = requests.get(url, params=params)
        translated = response.json()[0]
        return ''.join([i[0] for i in translated])
    except:
        return "⚠️ Translation failed."

# ------------- MAIN LOGIC -------------
if st.button("✨ Summarize & Visualize"):
    if len(input_text.strip()) < 20:
        st.warning("⚠️ Please provide more content.")
    else:
        with st.spinner("πŸ”Ž Summarizing..."):
            summary = summarizer(input_text, max_length=max_len, min_length=min_len, do_sample=False)[0]["summary_text"]

        # ----- Summary Display -----
        st.markdown("### ✍️ Summary:")
        st.markdown(f"<div class='summary-card'>{summary}</div>", unsafe_allow_html=True)

        # ----- Visual Diagram -----
        st.markdown("### 🧠 Visual Mind Map:")
        dot = Digraph()
        dot.node("Summary", "Summary", shape="box", style="filled", color="skyblue")

        for i, sent in enumerate(summary.split(". ")[:6]):
            dot.node(f"node{i}", sent.strip(), shape="ellipse", style="filled", color="lightgreen")
            dot.edge("Summary", f"node{i}")

        st.graphviz_chart(dot)

        # ----- PDF Export -----
        pdf = FPDF()
        pdf.add_page()
        pdf.set_font("Arial", size=12)
        pdf.multi_cell(0, 10, "Summary Report\n", align="C")
        pdf.set_font("Arial", size=11)
        pdf.multi_cell(0, 10, summary)

        with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_pdf:
            pdf.output(tmp_pdf.name)
            with open(tmp_pdf.name, "rb") as f:
                st.download_button("πŸ“„ Download as PDF", f, file_name="summary.pdf", mime="application/pdf")
            os.remove(tmp_pdf.name)

        # ----- Translation -----
        if translate_to != "None":
            lang_map = {"Urdu": "ur", "French": "fr", "Spanish": "es"}
            translated = translate_text(summary, lang_map[translate_to])
            st.markdown(f"### 🌐 Translated Summary ({translate_to}):")
            st.success(translated)

        # ----- YouTube Video Search -----
        st.markdown("### πŸ“Ί Learn More on YouTube:")
        query = summary.split(".")[0]
        youtube_link = f"https://www.youtube.com/results?search_query={query.replace(' ', '+')}"
        st.markdown(f"[πŸ”— Click to search YouTube for: `{query}`]({youtube_link})")

# ------------- FOOTER -------------
st.markdown("---")
st.markdown("<p style='text-align:center; color:gray;'>Made with ❀️ by a 4th Semester Software Engineer πŸš€</p>", unsafe_allow_html=True)