Spaces:
Sleeping

File size: 7,510 Bytes
0f65d91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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."""

    @staticmethod
    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

    @staticmethod
    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

    @staticmethod
    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."""

    @staticmethod
    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()

    @staticmethod
    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

    @staticmethod
    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()

    @staticmethod
    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."""

    @staticmethod
    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,
        }