Spaces:
Paused
Paused
File size: 12,314 Bytes
f6ea7de | 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 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | 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)
|