Spaces:
Build error
Build error
Regino commited on
Commit Β·
8d54f3a
1
Parent(s): 1c11257
dbfdb
Browse filesFiles changed (2)
- app.py+91-24
- requirements.txt+5-2
1234567891011121314151617181920212223242526272829import streamlit as stfrom transformers import pipeline# Set page title and descriptionst.title("π Text Summarization App")st.write("""This app allows users to upload a text file and get a summarized version using a Natural Language Processing (NLP) model.It uses the `transformers` library from Hugging Face, which provides state-of-the-art machine learning models.""")# Load summarization pipelinesummarizer = pipeline("summarization")# File uploaderuploaded_file = st.file_uploader("Upload a text file", type=["txt"])if uploaded_file is not None:# Read the file contenttext = uploaded_file.read().decode("utf-8")# Display original text (optional)st.subheader("Original Text")st.text_area("Content:", text, height=200)# Summarize the textif st.button("Summarize"):summary = summarizer(text, max_length=150, min_length=50, do_sample=False)st.subheader("Summarized Text")st.write(summary[0]['summary_text'])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import streamlit as stimport fitz # PyMuPDF for PDF extractionimport refrom sumy.parsers.plaintext import PlaintextParserfrom sumy.nlp.tokenizers import Tokenizerfrom sumy.summarizers.lsa import LsaSummarizerfrom rouge_score import rouge_scorer # For ROUGE score evaluation# Function to extract text from PDFdef extract_text_from_pdf(uploaded_file):doc = fitz.open(stream=uploaded_file.read(), filetype="pdf")text = ""for page in doc:text += page.get_text("text") + "\n"return clean_text(text)# Function to clean text (removes unwanted symbols, extra spaces, and bullets)def clean_text(text):text = re.sub(r"[β’βͺββ¦ββΆβ¦]", "", text) # Remove bullet pointstext = re.sub(r"[\u2022\u2023\u25AA\u25AB\u25A0\u25CF\u00B7]", "", text) # Additional bulletstext = re.sub(r"\s+", " ", text) # Normalize spacestext = re.sub(r"[^a-zA-Z0-9.,!?()'\"%$@&\s]", "", text) # Keep only readable textreturn text.strip()# Function to summarize text using LSAdef summarize_text(text, num_sentences=3):text = clean_text(text) # Clean text before summarizingparser = PlaintextParser.from_string(text, Tokenizer("english"))summarizer = LsaSummarizer()summary = summarizer(parser.document, num_sentences)return " ".join(str(sentence) for sentence in summary)# Function to calculate ROUGE scoresdef calculate_rouge(reference_text, generated_summary):scorer = rouge_scorer.RougeScorer(["rouge1", "rouge2", "rougeL"], use_stemmer=True)scores = scorer.score(reference_text, generated_summary)rouge1 = scores["rouge1"].fmeasurerouge2 = scores["rouge2"].fmeasurerougeL = scores["rougeL"].fmeasurereturn rouge1, rouge2, rougeL# Streamlit UIst.title("π Text Summarization App")st.write("This app summarizes long text using **Latent Semantic Analysis (LSA)**, an **unsupervised learning method**, and evaluates the summary using **ROUGE scores**.")# Sidebar input optionsst.sidebar.header("Options")file_uploaded = st.sidebar.file_uploader("Upload a file (TXT or PDF)", type=["txt", "pdf"])manual_text = st.sidebar.text_area("Or enter text manually", "")# Explanation of the modelsst.subheader("π How It Works")st.markdown("""- **Summarization Model: Latent Semantic Analysis (LSA)**LSA is an **unsupervised learning method** that identifies important sentences using **Singular Value Decomposition (SVD)**.It finds hidden relationships between words and sentences **without requiring labeled data**.- **Evaluation Metric: ROUGE Score**- **ROUGE-1**: Measures single-word overlap- **ROUGE-2**: Measures two-word sequence overlap- **ROUGE-L**: Measures the longest common subsequence""")# Summarization buttonif st.sidebar.button("Summarize"):if file_uploaded:if file_uploaded.type == "text/plain": # TXT filetext = file_uploaded.read().decode("utf-8")elif file_uploaded.type == "application/pdf": # PDF filetext = extract_text_from_pdf(file_uploaded)else:st.sidebar.error("Unsupported file format.")st.stop()elif manual_text.strip():text = manual_textelse:st.sidebar.error("Please upload a file or enter text.")st.stop()# Generate summarysummary = summarize_text(text, num_sentences=5)# Calculate ROUGE scorerouge1, rouge2, rougeL = calculate_rouge(text, summary)# Display summary in justified formatst.subheader("π Summarized Text")st.markdown(f"<p style='text-align: justify;'>{summary}</p>", unsafe_allow_html=True)# Display ROUGE scoresst.subheader("π Summary Quality (ROUGE Score)")st.write(f"**ROUGE-1 Score:** {rouge1:.4f}")st.write(f"**ROUGE-2 Score:** {rouge2:.4f}")st.write(f"**ROUGE-L Score:** {rougeL:.4f}")
123streamlittorchtransformers123456streamlitpymupdfsumyrouge-scorenumpynltk
app.py+91-24
requirements.txt+5-2