Download Webapp/core/database.py from Sakda101/explorer-consultant-bot: direct link, hf CLI and curl.
- Browser
- Download file 23.1 kB
-
https://huggingface.co/spaces/Sakda101/explorer-consultant-bot/resolve/main/Webapp/core/database.py
- Command line
-
hf download hf://spaces/Sakda101/explorer-consultant-bot/Webapp/core/database.py
-
curl -L -o database.py https://huggingface.co/spaces/Sakda101/explorer-consultant-bot/resolve/main/Webapp/core/database.py
23.1 kB
| """ | |
| SQLite database layer for Explorer Consultant Bot. | |
| Tables | |
| ------ | |
| users registered staff, their roles, and login history | |
| interactions every Consultants page analysis (usage analytics) | |
| activity_log audit trail: logins, edits, admin actions | |
| DB file: Final Project/explorer.db (one level above Webapp/) | |
| Persistence on HF Spaces | |
| ------------------------ | |
| HF Spaces has an ephemeral filesystem — explorer.db is wiped on every restart. | |
| Set these two secrets in your HF Space to enable persistent storage via a | |
| private HF Dataset: | |
| HF_DB_REPO = Sakda101/explorer-db (your private dataset repo) | |
| HF_TOKEN = hf_xxxxxxxxxxxx (write-access token) | |
| On startup, init_db() downloads explorer.db from the dataset. | |
| After every write (log_interaction, delete) it re-uploads in a background | |
| thread so the user experiences no delay. | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import sqlite3 | |
| import threading | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Optional | |
| # On Railway: set DB_PATH env var to point to a persistent volume | |
| # e.g. DB_PATH=/app_data/explorer.db | |
| _default_db = Path(__file__).resolve().parents[2] / "explorer.db" | |
| DB_PATH = Path(os.environ.get("DB_PATH", str(_default_db))) | |
| # HF Dataset repo used for persistent DB storage on HF Spaces | |
| _HF_DB_REPO = os.environ.get("HF_DB_REPO", "").strip() | |
| _HF_TOKEN = os.environ.get("HF_TOKEN", "").strip() or None | |
| # Seeded admin account — override via ADMIN_EMAIL env var when transferring ownership | |
| _ADMIN_EMAIL = os.environ.get("ADMIN_EMAIL", "huthsakda525@gmail.com").strip().lower() | |
| # Module-level flag: only download the DB once per server process | |
| _db_synced_from_hub: bool = False | |
| def _conn() -> sqlite3.Connection: | |
| con = sqlite3.connect(str(DB_PATH), check_same_thread=False) | |
| con.row_factory = sqlite3.Row | |
| return con | |
| def _now() -> str: | |
| return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") | |
| # --------------------------------------------------------------------------- | |
| # HF Hub persistence helpers | |
| # --------------------------------------------------------------------------- | |
| def _sync_db_from_hub() -> None: | |
| """Download explorer.db from HF Hub dataset (runs once at startup).""" | |
| if not _HF_DB_REPO: | |
| return | |
| try: | |
| from huggingface_hub import hf_hub_download | |
| import shutil | |
| cached = hf_hub_download( | |
| repo_id=_HF_DB_REPO, | |
| filename="explorer.db", | |
| repo_type="dataset", | |
| token=_HF_TOKEN, | |
| force_download=True, # always get the latest version | |
| ) | |
| DB_PATH.parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copy2(cached, str(DB_PATH)) | |
| except Exception: | |
| # File not in repo yet (first run) or network error — start fresh. | |
| pass | |
| def _sync_db_to_hub() -> None: | |
| """Upload explorer.db to HF Hub dataset (called in background thread).""" | |
| if not _HF_DB_REPO or not DB_PATH.exists(): | |
| return | |
| try: | |
| from huggingface_hub import HfApi | |
| api = HfApi(token=_HF_TOKEN) | |
| api.upload_file( | |
| path_or_fileobj=str(DB_PATH), | |
| path_in_repo="explorer.db", | |
| repo_id=_HF_DB_REPO, | |
| repo_type="dataset", | |
| commit_message="auto: update explorer.db", | |
| ) | |
| except Exception: | |
| pass # Don't crash the app if upload fails | |
| def _push_db() -> None: | |
| """Kick off a background upload of explorer.db to HF Hub.""" | |
| if _HF_DB_REPO: | |
| threading.Thread(target=_sync_db_to_hub, daemon=True).start() | |
| # --------------------------------------------------------------------------- | |
| # Schema bootstrap | |
| # --------------------------------------------------------------------------- | |
| def _bootstrap_admin_password(con: sqlite3.Connection) -> None: | |
| """Set the admin password from ADMIN_PASSWORD env var if not already set. | |
| Called inside init_db() so it runs every time Streamlit starts. | |
| Safe to call repeatedly — it skips if a hash is already present. | |
| """ | |
| import hashlib | |
| pw = os.environ.get("ADMIN_PASSWORD", "").strip() | |
| if not pw: | |
| return | |
| row = con.execute( | |
| "SELECT password_hash FROM users WHERE email = ?", | |
| (_ADMIN_EMAIL,), | |
| ).fetchone() | |
| if row is None or row[0]: | |
| return # user doesn't exist yet, or password already set | |
| salt = os.urandom(16).hex() | |
| key = hashlib.pbkdf2_hmac( | |
| "sha256", pw.encode("utf-8"), salt.encode("utf-8"), 260_000 | |
| ).hex() | |
| hashed = salt + ":" + key | |
| con.execute( | |
| "UPDATE users SET password_hash = ? WHERE email = ?", | |
| (hashed, _ADMIN_EMAIL), | |
| ) | |
| def init_db() -> None: | |
| """Create tables if they do not exist and seed the first admin.""" | |
| global _db_synced_from_hub | |
| if not _db_synced_from_hub: | |
| _sync_db_from_hub() # restore persisted DB from HF Hub (once per process) | |
| _db_synced_from_hub = True | |
| with _conn() as con: | |
| con.executescript(""" | |
| CREATE TABLE IF NOT EXISTS users ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| email TEXT UNIQUE NOT NULL, | |
| name TEXT NOT NULL DEFAULT \'\', | |
| role TEXT NOT NULL DEFAULT \'employee\', | |
| active INTEGER NOT NULL DEFAULT 1, | |
| created_at TEXT NOT NULL, | |
| last_login TEXT, | |
| password_hash TEXT | |
| ); | |
| CREATE TABLE IF NOT EXISTS interactions ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| timestamp TEXT NOT NULL, | |
| user_email TEXT NOT NULL, | |
| user_name TEXT NOT NULL DEFAULT \'\', | |
| quote TEXT NOT NULL, | |
| objection_type TEXT, | |
| cluster TEXT, | |
| customer_group TEXT, | |
| destination TEXT, | |
| service TEXT, | |
| objection_status TEXT NOT NULL DEFAULT \'\', | |
| first_contact_date TEXT NOT NULL DEFAULT \'\', | |
| objection_date TEXT NOT NULL DEFAULT \'\', | |
| main_contact_platform TEXT NOT NULL DEFAULT \'\', | |
| ad_source TEXT NOT NULL DEFAULT \'\', | |
| lead_quality TEXT NOT NULL DEFAULT \'\', | |
| severity TEXT, | |
| stage1_confidence REAL, | |
| response_found INTEGER | |
| ); | |
| CREATE TABLE IF NOT EXISTS activity_log ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| timestamp TEXT NOT NULL, | |
| user_email TEXT NOT NULL, | |
| user_name TEXT NOT NULL DEFAULT \'\', | |
| action TEXT NOT NULL, | |
| details TEXT, | |
| page TEXT | |
| ); | |
| CREATE TABLE IF NOT EXISTS sessions ( | |
| token TEXT PRIMARY KEY, | |
| email TEXT NOT NULL, | |
| expires_at TEXT NOT NULL | |
| ); | |
| CREATE TABLE IF NOT EXISTS corrections ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| timestamp TEXT NOT NULL, | |
| user_email TEXT NOT NULL, | |
| user_name TEXT NOT NULL DEFAULT \'\', | |
| quote TEXT NOT NULL, | |
| quote_normalized TEXT NOT NULL, | |
| original_type TEXT NOT NULL, | |
| original_cluster TEXT NOT NULL, | |
| corrected_type TEXT NOT NULL, | |
| corrected_cluster TEXT NOT NULL, | |
| customer_group TEXT DEFAULT \'\', | |
| destination TEXT DEFAULT \'\', | |
| service TEXT DEFAULT \'\', | |
| applied_count INTEGER DEFAULT 0 | |
| ); | |
| CREATE TABLE IF NOT EXISTS responses ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| customer_group TEXT NOT NULL DEFAULT \'\', | |
| destination TEXT NOT NULL DEFAULT \'\', | |
| cluster TEXT NOT NULL DEFAULT \'\', | |
| objection_type TEXT NOT NULL DEFAULT \'\', | |
| severity TEXT NOT NULL DEFAULT \'\', | |
| solution TEXT NOT NULL DEFAULT \'\', | |
| perfect_response TEXT NOT NULL DEFAULT \'\', | |
| follow_up_question TEXT NOT NULL DEFAULT \'\', | |
| video_id TEXT NOT NULL DEFAULT \'\', | |
| perfect_response_km TEXT NOT NULL DEFAULT \'\', | |
| solution_km TEXT NOT NULL DEFAULT \'\', | |
| follow_up_question_km TEXT NOT NULL DEFAULT \'\', | |
| service TEXT NOT NULL DEFAULT \'\', | |
| updated_at TEXT, | |
| updated_by TEXT | |
| ); | |
| """) | |
| # Migration: add password_hash column if it doesn't exist yet | |
| try: | |
| con.execute("ALTER TABLE users ADD COLUMN password_hash TEXT") | |
| except Exception: | |
| pass # Column already exists | |
| # Migration: add lead tracking fields to older interaction databases. | |
| for col_name, col_type in [ | |
| ("objection_status", "TEXT NOT NULL DEFAULT ''"), | |
| ("first_contact_date", "TEXT NOT NULL DEFAULT ''"), | |
| ("objection_date", "TEXT NOT NULL DEFAULT ''"), | |
| ("main_contact_platform", "TEXT NOT NULL DEFAULT ''"), | |
| ("ad_source", "TEXT NOT NULL DEFAULT ''"), | |
| ("lead_quality", "TEXT NOT NULL DEFAULT ''"), | |
| ]: | |
| try: | |
| con.execute(f"ALTER TABLE interactions ADD COLUMN {col_name} {col_type}") | |
| except Exception: | |
| pass # Column already exists | |
| # Seed first admin only when the table is completely empty | |
| existing = con.execute("SELECT COUNT(*) FROM users").fetchone()[0] | |
| if existing == 0: | |
| con.execute( | |
| "INSERT INTO users (email, name, role, active, created_at) VALUES (?, ?, ?, 1, ?)", | |
| (_ADMIN_EMAIL, "Sakda", "admin", _now()), | |
| ) | |
| # Bootstrap admin password from ADMIN_PASSWORD env var (Railway). | |
| # Only writes if the admin row currently has no password_hash set. | |
| _bootstrap_admin_password(con) | |
| def get_all_responses() -> list[dict]: | |
| """Return every row in the responses table as a list of dicts.""" | |
| with _conn() as con: | |
| rows = con.execute( | |
| """SELECT customer_group, destination, cluster, objection_type, severity, | |
| solution, perfect_response, follow_up_question, video_id, | |
| perfect_response_km, solution_km, follow_up_question_km, service | |
| FROM responses | |
| ORDER BY objection_type, cluster, customer_group, destination""" | |
| ).fetchall() | |
| return [dict(r) for r in rows] | |
| def update_response( | |
| customer_group: str, | |
| destination: str, | |
| cluster: str, | |
| fields: dict, | |
| updated_by: str = "", | |
| ) -> bool: | |
| """Update editable fields for the response identified by (customer_group, destination, cluster). | |
| Returns True if a row was updated, False if no matching row was found. | |
| The `fields` dict may contain any subset of the editable columns: | |
| perfect_response, perfect_response_km, solution, solution_km, | |
| follow_up_question, follow_up_question_km, video_id | |
| """ | |
| allowed = { | |
| "perfect_response", "perfect_response_km", | |
| "solution", "solution_km", | |
| "follow_up_question", "follow_up_question_km", | |
| "video_id", | |
| } | |
| updates = {k: v for k, v in fields.items() if k in allowed} | |
| if not updates: | |
| return False | |
| set_clause = ", ".join(f"{col} = ?" for col in updates) | |
| values = list(updates.values()) + [_now(), updated_by, | |
| customer_group, destination, cluster] | |
| with _conn() as con: | |
| cur = con.execute( | |
| f"UPDATE responses SET {set_clause}, updated_at = ?, updated_by = ? " | |
| f"WHERE customer_group = ? AND destination = ? AND cluster = ?", | |
| values, | |
| ) | |
| changed = cur.rowcount > 0 | |
| if changed: | |
| _push_db() # persist to HF Hub in background | |
| return changed | |
| # --------------------------------------------------------------------------- | |
| # Users | |
| # --------------------------------------------------------------------------- | |
| def get_user(email: str) -> Optional[dict]: | |
| with _conn() as con: | |
| row = con.execute("SELECT * FROM users WHERE email = ?", (email.strip().lower(),)).fetchone() | |
| return dict(row) if row else None | |
| def get_all_users() -> list: | |
| with _conn() as con: | |
| rows = con.execute("SELECT * FROM users ORDER BY created_at DESC").fetchall() | |
| return [dict(r) for r in rows] | |
| def add_user(email: str, name: str, role: str) -> bool: | |
| """Returns True on success, False if email already exists.""" | |
| try: | |
| with _conn() as con: | |
| con.execute( | |
| "INSERT INTO users (email, name, role, active, created_at) VALUES (?, ?, ?, 1, ?)", | |
| (email.strip().lower(), name.strip(), role, _now()), | |
| ) | |
| _push_db() | |
| return True | |
| except sqlite3.IntegrityError: | |
| return False | |
| def update_user_role(email: str, role: str) -> None: | |
| with _conn() as con: | |
| con.execute("UPDATE users SET role = ? WHERE email = ?", (role, email)) | |
| _push_db() | |
| def update_user_active(email: str, active: int) -> None: | |
| with _conn() as con: | |
| con.execute("UPDATE users SET active = ? WHERE email = ?", (active, email)) | |
| _push_db() | |
| def update_user_name(email: str, name: str) -> None: | |
| with _conn() as con: | |
| con.execute("UPDATE users SET name = ? WHERE email = ?", (name, email)) | |
| _push_db() | |
| def update_last_login(email: str) -> None: | |
| with _conn() as con: | |
| con.execute("UPDATE users SET last_login = ? WHERE email = ?", (_now(), email)) | |
| _push_db() | |
| # --------------------------------------------------------------------------- | |
| # Interactions | |
| # --------------------------------------------------------------------------- | |
| def log_interaction( | |
| user_email: str, | |
| user_name: str, | |
| quote: str, | |
| objection_type: str = "", | |
| cluster: str = "", | |
| customer_group: str = "", | |
| destination: str = "", | |
| service: str = "", | |
| severity: str = "", | |
| stage1_confidence: float = None, | |
| response_found: bool = True, | |
| objection_status: str = "", | |
| first_contact_date: str = "", | |
| objection_date: str = "", | |
| main_contact_platform: str = "", | |
| ad_source: str = "", | |
| lead_quality: str = "", | |
| ) -> None: | |
| with _conn() as con: | |
| con.execute( | |
| """INSERT INTO interactions | |
| (timestamp, user_email, user_name, quote, objection_type, cluster, | |
| customer_group, destination, service, objection_status, | |
| first_contact_date, objection_date, main_contact_platform, | |
| ad_source, lead_quality, severity, stage1_confidence, response_found) | |
| VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", | |
| ( | |
| _now(), user_email, user_name, quote, objection_type, cluster, | |
| customer_group, destination, service, objection_status, | |
| first_contact_date, objection_date, main_contact_platform, | |
| ad_source, lead_quality, severity, stage1_confidence, | |
| 1 if response_found else 0, | |
| ), | |
| ) | |
| _push_db() # persist to HF Hub in background | |
| def get_interactions(limit: int = 1000) -> list: | |
| with _conn() as con: | |
| rows = con.execute( | |
| "SELECT * FROM interactions ORDER BY timestamp DESC LIMIT ?", (limit,) | |
| ).fetchall() | |
| return [dict(r) for r in rows] | |
| def update_interaction_status(interaction_id: int, objection_status: str) -> bool: | |
| """Update the solved/unsolved status for a saved consultation record.""" | |
| status = (objection_status or "").strip() | |
| if status not in {"Solved", "Unsolved"}: | |
| return False | |
| with _conn() as con: | |
| cur = con.execute( | |
| "UPDATE interactions SET objection_status = ? WHERE id = ?", | |
| (status, interaction_id), | |
| ) | |
| changed = cur.rowcount > 0 | |
| if changed: | |
| _push_db() | |
| return changed | |
| def delete_interactions_by_ids(ids: list) -> int: | |
| """Delete specific interaction rows by their id. Returns number of rows deleted.""" | |
| if not ids: | |
| return 0 | |
| placeholders = ",".join("?" * len(ids)) | |
| with _conn() as con: | |
| cur = con.execute( | |
| f"DELETE FROM interactions WHERE id IN ({placeholders})", ids | |
| ) | |
| n = cur.rowcount | |
| _push_db() # persist to HF Hub in background | |
| return n | |
| def delete_interactions_by_date_range(from_date: str, to_date: str) -> int: | |
| """Delete all interactions whose timestamp falls within [from_date, to_date]. | |
| Dates should be ISO strings: 'YYYY-MM-DD'. Returns number of rows deleted.""" | |
| with _conn() as con: | |
| cur = con.execute( | |
| "DELETE FROM interactions WHERE DATE(timestamp) BETWEEN ? AND ?", | |
| (from_date, to_date), | |
| ) | |
| n = cur.rowcount | |
| _push_db() # persist to HF Hub in background | |
| return n | |
| # --------------------------------------------------------------------------- | |
| # Activity log | |
| # --------------------------------------------------------------------------- | |
| def log_activity( | |
| user_email: str, | |
| user_name: str, | |
| action: str, | |
| details: str = "", | |
| page: str = "", | |
| ) -> None: | |
| with _conn() as con: | |
| con.execute( | |
| """INSERT INTO activity_log | |
| (timestamp, user_email, user_name, action, details, page) | |
| VALUES (?, ?, ?, ?, ?, ?)""", | |
| (_now(), user_email, user_name, action, details, page), | |
| ) | |
| _push_db() # persist to HF Hub in background | |
| def get_activity_log(limit: int = 1000) -> list: | |
| with _conn() as con: | |
| rows = con.execute( | |
| "SELECT * FROM activity_log ORDER BY timestamp DESC LIMIT ?", (limit,) | |
| ).fetchall() | |
| return [dict(r) for r in rows] | |
| # --------------------------------------------------------------------------- | |
| # Corrections | |
| # --------------------------------------------------------------------------- | |
| def save_correction( | |
| user_email: str, | |
| user_name: str, | |
| quote: str, | |
| quote_normalized: str, | |
| original_type: str, | |
| original_cluster: str, | |
| corrected_type: str, | |
| corrected_cluster: str, | |
| customer_group: str = "", | |
| destination: str = "", | |
| service: str = "", | |
| ) -> int: | |
| """Save a staff correction. Returns the new row id.""" | |
| with _conn() as con: | |
| cur = con.execute( | |
| """INSERT INTO corrections | |
| (timestamp, user_email, user_name, quote, quote_normalized, | |
| original_type, original_cluster, corrected_type, corrected_cluster, | |
| customer_group, destination, service, applied_count) | |
| VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)""", | |
| ( | |
| _now(), user_email, user_name, quote, quote_normalized, | |
| original_type, original_cluster, corrected_type, corrected_cluster, | |
| customer_group, destination, service, | |
| ), | |
| ) | |
| rowid = cur.lastrowid | |
| _push_db() # persist to HF Hub in background | |
| return rowid | |
| def get_correction_count() -> int: | |
| """Return the total number of corrections rows. Used by the CorrectionStore cache | |
| to detect when the table changes without loading all rows.""" | |
| with _conn() as con: | |
| return con.execute("SELECT COUNT(*) FROM corrections").fetchone()[0] | |
| def get_user_interactions(user_email: str, limit: int = 10) -> list: | |
| """Return the most recent interactions for a specific user (for history panel).""" | |
| with _conn() as con: | |
| rows = con.execute( | |
| "SELECT * FROM interactions WHERE user_email = ? ORDER BY timestamp DESC LIMIT ?", | |
| (user_email.strip().lower(), limit), | |
| ).fetchall() | |
| return [dict(r) for r in rows] | |
| def get_all_corrections_raw() -> list: | |
| """Return all corrections ordered by most recent first. Used by CorrectionStore.""" | |
| with _conn() as con: | |
| rows = con.execute( | |
| "SELECT * FROM corrections ORDER BY timestamp DESC" | |
| ).fetchall() | |
| return [dict(r) for r in rows] | |
| def get_corrections(limit: int = 500) -> list: | |
| """Return corrections for display (most recent first, capped).""" | |
| with _conn() as con: | |
| rows = con.execute( | |
| "SELECT * FROM corrections ORDER BY timestamp DESC LIMIT ?", (limit,) | |
| ).fetchall() | |
| return [dict(r) for r in rows] | |
| def increment_correction_applied(correction_id: int) -> None: | |
| """Increment the applied_count counter for a correction row.""" | |
| with _conn() as con: | |
| con.execute( | |
| "UPDATE corrections SET applied_count = applied_count + 1 WHERE id = ?", | |
| (correction_id,), | |
| ) | |
| def delete_correction(correction_id: int) -> None: | |
| with _conn() as con: | |
| con.execute("DELETE FROM corrections WHERE id = ?", (correction_id,)) | |
| _push_db() # persist to HF Hub in background | |
| # --------------------------------------------------------------------------- | |
| # Sessions (persistent login tokens stored per user) | |
| # --------------------------------------------------------------------------- | |
| def create_session(token: str, email: str, expires_at: str) -> None: | |
| """Store a new session token for the given user.""" | |
| with _conn() as con: | |
| con.execute( | |
| "INSERT OR REPLACE INTO sessions (token, email, expires_at) VALUES (?, ?, ?)", | |
| (token, email.strip().lower(), expires_at), | |
| ) | |
| _push_db() | |
| def get_session_email(token: str) -> Optional[str]: | |
| """Return the email for a valid (non-expired) token, or None.""" | |
| with _conn() as con: | |
| row = con.execute( | |
| "SELECT email, expires_at FROM sessions WHERE token = ?", (token,) | |
| ).fetchone() | |
| if not row: | |
| return None | |
| # Check expiry | |
| try: | |
| exp = datetime.strptime(row["expires_at"], "%Y-%m-%d %H:%M:%S").replace( | |
| tzinfo=timezone.utc | |
| ) | |
| if datetime.now(timezone.utc) > exp: | |
| delete_session(token) | |
| return None | |
| except Exception: | |
| pass | |
| return row["email"] | |
| def delete_session(token: str) -> None: | |
| """Remove a session token (logout).""" | |
| with _conn() as con: | |
| con.execute("DELETE FROM sessions WHERE token = ?", (token,)) | |
| _push_db() | |
| def cleanup_expired_sessions() -> None: | |
| """Delete all expired session rows.""" | |
| now = _now() | |
| with _conn() as con: | |
| con.execute("DELETE FROM sessions WHERE expires_at < ?", (now,)) | |