import streamlit as st
from contextlib import contextmanager
from typing import Optional, List, Dict, Any, Generator, Iterator, TypeVar
import pandas as pd
import re
T = TypeVar('T')
def load_css() -> None:
"""Load custom CSS styles for the application."""
css = """
"""
st.markdown(css, unsafe_allow_html=True)
def show_success(message: str) -> None:
"""Show a success message.
Args:
message: The success message to display
"""
st.success(message)
def show_info(message: str) -> None:
"""Show an info message.
Args:
message: The info message to display
"""
st.info(message)
def show_warning(message: str) -> None:
"""Show a warning message.
Args:
message: The warning message to display
"""
st.warning(message)
def show_error(message: str) -> None:
"""Show an error message.
Args:
message: The error message to display
"""
st.error(message)
@contextmanager
def show_spinner(text: str = "Processing...") -> Iterator[None]:
"""Context manager for showing a spinner during operations.
Args:
text: The text to display with the spinner
"""
with st.spinner(text):
yield
def create_prediction_card(prediction: Dict[str, Any]) -> None:
"""Create a custom HTML card for displaying predictions.
Args:
prediction: Dictionary containing prediction details
"""
is_spam = prediction.get("is_spam", False)
probability = prediction.get("spam_probability", 0)
card_class = "spam-card" if is_spam else "ham-card"
html = f"""
{"Spam" if is_spam else "Not Spam"} ({probability:.2%})
{prediction.get("explanation", "")}
"""
st.markdown(html, unsafe_allow_html=True)
def render_metric_tile(
title: str,
value: str,
description: Optional[str] = None,
bg_color: str = "#1e2a38", # Darker background for better UI
title_color: str = "#e1e1e1", # Light text for dark background
value_color: str = "#ffffff", # White text for emphasis
border_color: Optional[str] = None
) -> None:
"""Render a metric tile with a title, value, and optional description.
Args:
title: Title of the metric
value: Value to display
description: Optional description text
bg_color: Background color of the tile
title_color: Color for the title text
value_color: Color for the value text
border_color: Optional border color
"""
border_style = f"border-left: 3px solid {border_color};" if border_color else ""
# Enhanced animation and improved styling with professional font
st.markdown(f"""
{title}
{value}
{f'
{description}' if description else ""}
""", unsafe_allow_html=True)
def create_batch_interface() -> Optional[List[str]]:
"""Create an interface for batch email uploads or manual entry.
Uses session state to store input values between reruns.
Returns:
List of email contents (List[str]) if valid, None otherwise
"""
# Initialize session state for file uploader
if "uploaded_file" not in st.session_state:
st.session_state.uploaded_file = None
# Initialize session state for text area
if "batch_email_input" not in st.session_state:
st.session_state.batch_email_input = ""
with st.expander("Upload Emails for Batch Analysis", expanded=True):
st.write("The file should contain a column named 'email' or 'text' with the email content.")
uploaded_file = st.file_uploader(
"Choose a file",
type=["csv", "xlsx", "xls"],
help="Upload a CSV or Excel file with email content",
key="file_uploader"
)
# Update session state if file uploaded
if uploaded_file is not None:
st.session_state.uploaded_file = uploaded_file
with st.expander("Or write emails directly:", expanded=False):
email_input = st.text_area(
"Enter email content (use email or double line breaks to separate emails)",
height=200,
help="Paste multiple emails here, separated by ... or double line breaks",
key="batch_email_input"
)
# Process the inputs
if st.session_state.uploaded_file is None and not email_input:
return None
# If file is uploaded, extract emails as list of str
if st.session_state.uploaded_file is not None:
try:
uploaded_file = st.session_state.uploaded_file
# Determine file type and read accordingly
if uploaded_file.name.endswith('.csv'):
df = pd.read_csv(uploaded_file)
else:
df = pd.read_excel(uploaded_file)
# Check for required columns
if 'email' in df.columns:
email_column = 'email'
elif 'text' in df.columns:
email_column = 'text'
else:
st.error("File must contain a column named 'email' or 'text'")
return None
# Preview the dataframe
with st.expander("Preview of uploaded data", expanded=True):
st.dataframe(df.head(5))
# Extract emails as list of str, drop NaN and strip whitespace
emails = df[email_column].dropna().astype(str).map(str.strip).tolist()
return emails
except Exception as e:
st.error(f"Error processing file: {str(e)}")
return None
# If text area is used, parse emails
if email_input:
emails = _parse_emails_from_text(email_input)
if not emails:
st.warning("No valid emails found in the input.")
return None
return emails
return None
def _parse_emails_from_text(email_input: str) -> List[str]:
"""Parse emails from text input using either tags or line breaks.
Args:
email_input: Raw text containing multiple emails
Returns:
List of parsed emails
"""
emails = []
# Try to extract using ... tags
pattern = re.compile(r"(.*?)", re.DOTALL | re.IGNORECASE)
matches = pattern.findall(email_input)
if matches:
emails = [m.strip() for m in matches if m.strip()]
else:
# Fallback: split by double line breaks (2 or more newlines)
emails = [e.strip() for e in re.split(r"\n{2,}", email_input) if e.strip()]
return emails
def display_batch_results(results: List[Dict[str, Any]]) -> None:
"""Display batch processing results.
Args:
results: List of dictionaries containing classification results
"""
if not results:
st.warning("No results to display")
return
# Create DataFrame from results
df = pd.DataFrame(results)
# Add index as Email ID
df.insert(0, 'Email ID', range(1, len(df) + 1))
# Format probability as percentage
if 'spam_probability' in df.columns:
df['spam_probability'] = df['spam_probability'].apply(lambda x: f"{x*100:.2f}%")
# Calculate statistics
spam_count = sum(1 for result in results if result.get('is_spam', False))
ham_count = len(results) - spam_count
# Display metrics with improved styling
st.markdown("Analysis Summary
", unsafe_allow_html=True)
col1, col2, col3 = st.columns(3)
with col1:
render_metric_tile(
"Total Emails",
str(len(results)),
"Processed emails",
bg_color="#1e2a38",
title_color="#e1e1e1",
value_color="#3498db",
border_color="#3498db"
)
with col2:
render_metric_tile(
"Spam Detected",
str(spam_count),
f"{spam_count/len(results)*100:.1f}% of total",
bg_color="#1e2a38",
title_color="#e1e1e1",
value_color="#e74c3c",
border_color="#470501"
)
with col3:
render_metric_tile(
"Ham Detected",
str(ham_count),
f"{ham_count/len(results)*100:.1f}% of total",
bg_color="#1e2a38",
title_color="#e1e1e1",
value_color="#2ecc71",
border_color="#2ecc71"
)
# Display results table with improved heading
st.markdown("Classification Results
", unsafe_allow_html=True)
# Style the dataframe
st.dataframe(
df,
use_container_width=True,
hide_index=True,
)
# Download option
csv = df.to_csv(index=False).encode('utf-8')
st.download_button(
"Download Results as CSV",
csv,
"spam_classification_results.csv",
"text/csv",
key="download-csv"
)
def batch_progress_bar(iterable: List[T], label: str = "Processing emails...") -> Generator[T, None, None]:
"""Display a progress bar for batch processing.
Args:
iterable: An iterable to process
label: Text label for the progress bar
Yields:
Items from the iterable one by one
"""
progress_bar = st.progress(0)
total = len(iterable)
for i, item in enumerate(iterable):
yield item
progress_bar.progress((i + 1) / total)