-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathdiff_171.patch
More file actions
273 lines (268 loc) · 17.8 KB
/
Copy pathdiff_171.patch
File metadata and controls
273 lines (268 loc) · 17.8 KB
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
diff --git a/.gitignore b/.gitignore
index 8cffc34..137cd8e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,7 +2,6 @@ venv
__pycache__
*.ps1
-<<<<<<< HEAD
# Environment / secrets (never commit real credentials)
.env
.streamlit/secrets.toml
@@ -10,9 +9,6 @@ __pycache__
# Data directory (created at runtime)
data/
-# OS artefacts
-.DS_Store
-Thumbs.db
# IDE / editor
.vscode/
.idea/
diff --git a/config.py b/config.py
index 2b7a1ab..2e3548f 100644
--- a/config.py
+++ b/config.py
@@ -134,3 +134,7 @@ def get_optional(key: str, default: str | None = None) -> str | None:
ANALYTICS_RETENTION_DAYS: int = int(os.getenv("SPAMLYSER_ANALYTICS_RETENTION", "90"))
BATCH_RATE_LIMIT = 50
+
+# ΓöÇΓöÇ Error boundary / resilience ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+ERROR_BOUNDARY_ENABLED: bool = os.getenv("SPAMLYSER_ERROR_BOUNDARY", "true").lower() == "true"
+ERROR_BOUNDARY_SHOW_DETAIL: bool = os.getenv("SPAMLYSER_ERROR_DETAIL", "false").lower() == "true"
diff --git a/models/__init__.py b/models/__init__.py
index 66834c5..1d97d98 100644
--- a/models/__init__.py
+++ b/models/__init__.py
@@ -22,6 +22,15 @@
save_custom_rules,
)
from .encrypted_report import ReportEncryptor
+from .error_boundary import (
+ ConfigurationError,
+ DataAccessError,
+ ModelLoadError,
+ PageError,
+ error_boundary,
+ render_error_panel,
+ safe_execute,
+)
from .export_feature import export_results_button
from .language_detector import detect_language, is_language_supported
from .message_categorizer import MessageCategorizer
@@ -48,11 +57,16 @@
"THREAT_CATEGORIES",
"BatchProcessor",
"ConfidenceCalibrator",
+ "ConfigurationError",
+ "DataAccessError",
"MessageCategorizer",
+ "ModelLoadError",
+ "PageError",
"ReportEncryptor",
"SenderReputation",
"SimpleExplainer",
"StorageManager",
+ "ThemePreset",
"WebhookNotifier",
"WordAnalyzer",
"agreement_score",
@@ -63,6 +77,7 @@
"confidence_distribution",
"default_json_validator",
"detect_language",
+ "error_boundary",
"evaluate_compound_rule",
"evaluate_condition",
"export_results_button",
diff --git a/models/error_boundary.py b/models/error_boundary.py
new file mode 100644
index 0000000..44c05be
--- /dev/null
+++ b/models/error_boundary.py
@@ -0,0 +1,103 @@
+"""Error boundary framework ΓÇö wraps page functions with graceful error handling."""
+
+import functools
+import logging
+import traceback
+from typing import Any, Callable, TypeVar
+
+import streamlit as st
+
+logger = logging.getLogger(__name__)
+
+F = TypeVar("F", bound=Callable[..., Any])
+
+
+class PageError(Exception):
+ """Base exception for Spamlyser page-level errors."""
+
+ def __init__(self, message: str, page: str = "", recoverable: bool = True):
+ super().__init__(message)
+ self.page = page
+ self.recoverable = recoverable
+
+
+class ModelLoadError(PageError):
+ """Raised when a model fails to initialise."""
+
+
+class DataAccessError(PageError):
+ """Raised when storage reads/writes fail."""
+
+
+class ConfigurationError(PageError):
+ """Raised when the app config is invalid."""
+
+
+def error_boundary(page_func: F, fallback_message: str | None = None) -> F:
+ """Decorator that wraps a Streamlit page function in a try/except block.
+
+ On failure it logs the traceback and renders a user-friendly error panel
+ instead of crashing the whole app.
+ """
+ @functools.wraps(page_func)
+ def wrapper(*args, **kwargs):
+ try:
+ return page_func(*args, **kwargs)
+ except PageError as exc:
+ logger.error(
+ "PageError in %s (recoverable=%s): %s",
+ exc.page or page_func.__name__,
+ exc.recoverable,
+ exc,
+ )
+ render_error_panel(
+ title=f"⚠️ {exc.page or page_func.__name__} Error",
+ message=str(exc),
+ detail=traceback.format_exc() if exc.recoverable else None,
+ recoverable=exc.recoverable,
+ )
+ except Exception as exc:
+ logger.error("Unhandled error in %s: %s", page_func.__name__, exc, exc_info=True)
+ render_error_panel(
+ title="⚠️ Unexpected Error",
+ message=fallback_message or "Something went wrong. Please try again.",
+ detail=traceback.format_exc(),
+ recoverable=True,
+ )
+ return wrapper # type: ignore[return-value]
+
+
+def render_error_panel(
+ title: str = "⚠️ Error",
+ message: str = "An error occurred.",
+ detail: str | None = None,
+ recoverable: bool = True,
+) -> None:
+ """Display a styled error panel in the Streamlit UI."""
+ st.markdown(f"### {title}")
+ st.error(message)
+ if detail and st.checkbox("Show technical details", key=f"err_detail_{hash(title)}"):
+ st.code(detail, language="traceback")
+ if recoverable:
+ st.button("🔄 Retry", on_click=st.rerun, type="primary")
+ else:
+ st.warning("This error is not recoverable. Please restart the app.")
+
+
+def safe_execute(
+ fn: Callable[..., Any],
+ default: Any = None,
+ error_message: str = "Operation failed",
+ logger_name: str | None = None,
+ **kwargs,
+) -> Any:
+ """Execute *fn* with sensible error handling.
+
+ Returns *default* on failure rather than raising.
+ """
+ log = logging.getLogger(logger_name or __name__)
+ try:
+ return fn(**kwargs)
+ except Exception as exc:
+ log.warning("%s: %s", error_message, exc)
+ return default
diff --git a/models/model_init.py b/models/model_init.py
index 656906f..2805c23 100644
--- a/models/model_init.py
+++ b/models/model_init.py
@@ -212,7 +212,7 @@ def display_model_status_ui():
except Exception as e:
MODEL_STATUS = False
MODEL_ERROR_MESSAGE = (
- f"❌ Critical error during model initialization: {e!s}\n"
+ f"[ERROR] Critical error during model initialization: {e!s}\n"
" Please check your Python environment and dependencies."
)
MODEL_WARNINGS = []
diff --git a/models/navigation.py b/models/navigation.py
new file mode 100644
index 0000000..4b5534a
--- /dev/null
+++ b/models/navigation.py
@@ -0,0 +1,44 @@
+"""Top navigation bar for page routing."""
+
+import streamlit as st
+
+PAGES = {
+ "home": "🏠 Home",
+ "analyzer": "🔍 SMS Analyzer",
+ "about": "ℹ️ About",
+ "features": "ΓÜí Features",
+ "analytics": "📊 Analytics",
+ "models": "🤖 Models",
+ "feedback": "💬 Feedback",
+ "help": "Γ¥ô Help",
+ "contact": "📞 Contact",
+ "docs": "📚 Docs",
+ "api": "🔌 API",
+ "settings": "⚙️ Settings",
+}
+
+
+def top_navigation_bar(navigate_to):
+ """Render a horizontal navigation bar at the top of the page."""
+ current = st.session_state.get("current_page", "home")
+ cols = st.columns(len(PAGES))
+ for col, (page_key, page_label) in zip(cols, PAGES.items()):
+ with col:
+ is_active = page_key == current
+ if is_active:
+ st.markdown(
+ f'<div style="text-align:center;padding:6px 0;'
+ f'background:#00d4aa20;border-radius:8px;'
+ f'border:1px solid #00d4aa;">'
+ f'<span style="color:#00d4aa;font-weight:600;font-size:0.85rem;">'
+ f"{page_label}</span></div>",
+ unsafe_allow_html=True,
+ )
+ else:
+ if st.button(
+ page_label,
+ key=f"nav_top_{page_key}",
+ use_container_width=True,
+ help=f"Go to {page_label}",
+ ):
+ navigate_to(page_key)
diff --git a/page_functions.py b/page_functions.py
index 72d4201..3d36cea 100644
--- a/page_functions.py
+++ b/page_functions.py
@@ -45,6 +45,17 @@ def load_global_styles():
# Callers must pass it explicitly to show_feedback_page(navigate_to=...).
+def ui_error_boundary(func):
+ """Decorator to isolate component rendering errors and present recovery UI."""
+ def wrapper(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ except Exception as e:
+ st.error(f"⚠️ A rendering error occurred in this component: {e!s}")
+ if st.button("🔄 Reload Page / Recover UI", key=f"recover_{func.__name__}"):
+ st.rerun()
+ return wrapper
+
def show_feedback_page(navigate_to):
"""Feedback page for user comments, suggestions, and bug reports"""
# Import the feedback handler