email-classifier / app /utils /ui_elements.py
mrqadeer's picture
Initial project commit with code and figures
f6ea7de
Raw History Blame Contribute Delete
12.3 kB
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 = """
<style>
.reportview-container .main .block-container {
padding-top: 1rem;
}
.stAlert > div {
padding-top: 0.5rem;
padding-bottom: 0.5rem;
}
footer {visibility: hidden;}
.css-12oz5g7 {padding-top: 0rem;}
.css-1d391kg {padding-top: 0rem;}
.spam-card {
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1rem;
background-color: #f0f0f0;
border-left: 4px solid #FF4B4B;
}
.ham-card {
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1rem;
background-color: #f0f0f0;
border-left: 4px solid #00CC96;
}
.custom-info-box {
padding: 1rem;
border-radius: 0.5rem;
margin: 1rem 0;
background-color: #e6f3ff;
border: 1px solid #b3d9ff;
}
.batch-results-table {
width: 100%;
margin: 1rem 0;
}
.batch-progress {
margin: 1rem 0;
}
</style>
"""
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"""
<div class="{card_class}">
<h3>{"Spam" if is_spam else "Not Spam"} ({probability:.2%})</h3>
<p>{prediction.get("explanation", "")}</p>
</div>
"""
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"""
<style>
@keyframes fadeIn {{
from {{ opacity: 0; transform: translateY(10px); }}
to {{ opacity: 1; transform: translateY(0); }}
}}
.metric-tile {{
animation: fadeIn 0.6s ease-out forwards;
background-color: {bg_color};
padding: 20px;
border-radius: 10px;
margin-bottom: 15px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
{border_style}
font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;
transition: transform 0.3s ease, box-shadow 0.3s ease;
}}
.metric-tile:hover {{
transform: translateY(-3px);
box-shadow: 0 6px 12px rgba(0,0,0,0.15);
}}
.metric-title {{
margin: 0;
color: {title_color};
font-size: 1.1rem;
font-weight: 600;
letter-spacing: 0.3px;
}}
.metric-value {{
font-size: 28px;
font-weight: bold;
margin: 10px 0;
color: {value_color};
transition: color 0.3s ease;
}}
.metric-tile:hover .metric-value {{
color: #ffffff;
}}
.metric-desc {{
color: #a0a0a0;
font-size: 14px;
}}
</style>
<div class="metric-tile" style="animation-delay: 0.{id(title)}s;">
<h4 class="metric-title">{title}</h4>
<p class="metric-value">{value}</p>
{f'<small class="metric-desc">{description}</small>' if description else ""}
</div>
""", 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 <start>email</end> or double line breaks to separate emails)",
height=200,
help="Paste multiple emails here, separated by <start>...</end> 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 <start>...</end> tags
pattern = re.compile(r"<start>(.*?)</end>", 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("<h2 style='color:white;font-size:1.5rem;margin-bottom:1rem;'>Analysis Summary</h2>", 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("<h2 style='color:white;font-size:1.5rem;margin:1.5rem 0 1rem 0;'>Classification Results</h2>", 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)