Spaces:
Sleeping
Sleeping
Download database/db.py from FYP20252026/PhishDetect: direct link, hf CLI and curl.
- Browser
- Download file 7.51 kB
-
https://huggingface.co/spaces/FYP20252026/PhishDetect/resolve/main/database/db.py
- Command line
-
hf download hf://spaces/FYP20252026/PhishDetect/database/db.py
-
curl -L -o db.py https://huggingface.co/spaces/FYP20252026/PhishDetect/resolve/main/database/db.py
7.51 kB
| import sqlite3 | |
| import hashlib | |
| import os | |
| from datetime import datetime | |
| DB_PATH = os.path.join(os.path.dirname(__file__), "phishdetect.db") | |
| def get_db(): | |
| conn = sqlite3.connect(DB_PATH) | |
| conn.row_factory = sqlite3.Row | |
| return conn | |
| def init_db(): | |
| """Create all tables and seed default admin account.""" | |
| conn = get_db() | |
| c = conn.cursor() | |
| c.execute(""" | |
| CREATE TABLE IF NOT EXISTS detection_logs ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| label TEXT NOT NULL, | |
| confidence REAL NOT NULL, | |
| latency_ms REAL NOT NULL, | |
| email_text TEXT, | |
| created_at TEXT NOT NULL | |
| ) | |
| """) | |
| # backward-compatible column rename from earlier schema version | |
| try: | |
| c.execute("ALTER TABLE detection_logs RENAME COLUMN email_preview TO email_text") | |
| conn.commit() | |
| except Exception: | |
| pass | |
| c.execute(""" | |
| CREATE TABLE IF NOT EXISTS feedback ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| log_id INTEGER, | |
| original_label TEXT NOT NULL, | |
| reported_classification TEXT NOT NULL, | |
| user_comments TEXT, | |
| is_resolved INTEGER DEFAULT 0, | |
| resolution_label TEXT, | |
| created_at TEXT NOT NULL | |
| ) | |
| """) | |
| # backward-compatible addition of resolution_label introduced in v2 | |
| try: | |
| c.execute("ALTER TABLE feedback ADD COLUMN resolution_label TEXT") | |
| conn.commit() | |
| except Exception: | |
| pass | |
| c.execute(""" | |
| CREATE TABLE IF NOT EXISTS admin ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| admin_id TEXT NOT NULL UNIQUE, | |
| password_hash TEXT NOT NULL | |
| ) | |
| """) | |
| default_id = "admin" | |
| default_hash = hashlib.sha256("admin123".encode()).hexdigest() | |
| c.execute("INSERT OR IGNORE INTO admin (admin_id, password_hash) VALUES (?, ?)", | |
| (default_id, default_hash)) | |
| conn.commit() | |
| conn.close() | |
| def verify_admin(admin_id: str, password: str) -> bool: | |
| pw_hash = hashlib.sha256(password.encode()).hexdigest() | |
| conn = get_db() | |
| c = conn.cursor() | |
| c.execute("SELECT * FROM admin WHERE admin_id=? AND password_hash=?", | |
| (admin_id, pw_hash)) | |
| result = c.fetchone() | |
| conn.close() | |
| return result is not None | |
| class DetectionLog: | |
| """Persists and retrieves email analysis records.""" | |
| def save(label: str, confidence: float, latency_ms: float, email_text: str) -> int: | |
| conn = get_db() | |
| c = conn.cursor() | |
| c.execute(""" | |
| INSERT INTO detection_logs (label, confidence, latency_ms, email_text, created_at) | |
| VALUES (?, ?, ?, ?, ?) | |
| """, (label, confidence, latency_ms, email_text, | |
| datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) | |
| log_id = c.lastrowid | |
| conn.commit() | |
| conn.close() | |
| return log_id | |
| def get_all(label_filter: str = None, limit: int = 200) -> list: | |
| conn = get_db() | |
| c = conn.cursor() | |
| if label_filter and label_filter != "All": | |
| c.execute( | |
| "SELECT * FROM detection_logs WHERE label=? ORDER BY id DESC LIMIT ?", | |
| (label_filter, limit) | |
| ) | |
| else: | |
| c.execute("SELECT * FROM detection_logs ORDER BY id DESC LIMIT ?", (limit,)) | |
| rows = [dict(r) for r in c.fetchall()] | |
| conn.close() | |
| return rows | |
| def delete(log_id: int): | |
| conn = get_db() | |
| c = conn.cursor() | |
| c.execute("DELETE FROM detection_logs WHERE id=?", (log_id,)) | |
| conn.commit() | |
| conn.close() | |
| class Feedback: | |
| """Captures and manages user-reported misclassifications.""" | |
| def save(log_id: int, original_label: str, | |
| reported_classification: str, user_comments: str): | |
| conn = get_db() | |
| c = conn.cursor() | |
| c.execute(""" | |
| INSERT INTO feedback | |
| (log_id, original_label, reported_classification, user_comments, created_at) | |
| VALUES (?, ?, ?, ?, ?) | |
| """, (log_id, original_label, reported_classification, user_comments, | |
| datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) | |
| conn.commit() | |
| conn.close() | |
| def get_all(status_filter: str = None, type_filter: str = None) -> list: | |
| conn = get_db() | |
| c = conn.cursor() | |
| query = """ | |
| SELECT f.*, d.email_text | |
| FROM feedback f | |
| LEFT JOIN detection_logs d ON f.log_id = d.id | |
| WHERE 1=1 | |
| """ | |
| params = [] | |
| if status_filter == "Resolved": | |
| query += " AND f.is_resolved=1" | |
| elif status_filter == "Pending": | |
| query += " AND f.is_resolved=0" | |
| if type_filter and type_filter != "All": | |
| query += " AND f.reported_classification=?" | |
| params.append(type_filter) | |
| query += " ORDER BY f.id DESC" | |
| c.execute(query, params) | |
| rows = [dict(r) for r in c.fetchall()] | |
| conn.close() | |
| return rows | |
| def resolve(feedback_id: int, resolution_label: str): | |
| conn = get_db() | |
| c = conn.cursor() | |
| c.execute( | |
| "UPDATE feedback SET is_resolved=1, resolution_label=? WHERE id=?", | |
| (resolution_label, feedback_id) | |
| ) | |
| conn.commit() | |
| conn.close() | |
| def reopen(feedback_id: int): | |
| conn = get_db() | |
| c = conn.cursor() | |
| c.execute( | |
| "UPDATE feedback SET is_resolved=0, resolution_label=NULL WHERE id=?", | |
| (feedback_id,) | |
| ) | |
| conn.commit() | |
| conn.close() | |
| class SystemStatistics: | |
| """Aggregates detection and feedback data for admin monitoring.""" | |
| def get() -> dict: | |
| conn = get_db() | |
| c = conn.cursor() | |
| c.execute("SELECT COUNT(*) FROM detection_logs") | |
| total = c.fetchone()[0] | |
| c.execute("SELECT COUNT(*) FROM detection_logs WHERE label='Phishing'") | |
| phishing_count = c.fetchone()[0] | |
| c.execute("SELECT COUNT(*) FROM feedback") | |
| feedback_total = c.fetchone()[0] | |
| c.execute("SELECT COUNT(*) FROM feedback WHERE is_resolved=1") | |
| feedback_resolved = c.fetchone()[0] | |
| c.execute(""" | |
| SELECT DATE(created_at) as day, COUNT(*) as count | |
| FROM detection_logs | |
| GROUP BY day | |
| ORDER BY day DESC | |
| LIMIT 7 | |
| """) | |
| daily_rows = [dict(r) for r in c.fetchall()] | |
| c.execute(""" | |
| SELECT * FROM detection_logs | |
| WHERE label='Phishing' | |
| ORDER BY id DESC LIMIT 4 | |
| """) | |
| recent_phishing = [dict(r) for r in c.fetchall()] | |
| conn.close() | |
| phishing_rate = round((phishing_count / total * 100), 1) if total > 0 else 0.0 | |
| return { | |
| "total": total, | |
| "phishing_count": phishing_count, | |
| "phishing_rate": phishing_rate, | |
| "feedback_total": feedback_total, | |
| "feedback_resolved": feedback_resolved, | |
| "feedback_pending": feedback_total - feedback_resolved, | |
| "daily_trend": list(reversed(daily_rows)), | |
| "recent_phishing": recent_phishing, | |
| } | |