Download FastAPI/core/database.py from Sakda101/explorer-consultant-bot: direct link, hf CLI and curl.
- Browser
- Download file 37.3 kB
-
https://huggingface.co/spaces/Sakda101/explorer-consultant-bot/resolve/main/FastAPI/core/database.py
- Command line
-
hf download hf://spaces/Sakda101/explorer-consultant-bot/FastAPI/core/database.py
-
curl -L -o database.py https://huggingface.co/spaces/Sakda101/explorer-consultant-bot/resolve/main/FastAPI/core/database.py
37.3 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 FastAPI/)
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)
HF_SYNC_INTERVAL = 30 (optional, seconds between uploads)
On startup, init_db() downloads explorer.db from the dataset and launches a
single long-lived background sync worker thread. Every write calls _push_db()
which simply sets a threading.Event. The worker wakes, waits HF_SYNC_INTERVAL
seconds (so rapid sequential writes are coalesced into one upload), then
uploads. A final blocking upload fires on process exit via atexit so no data
is lost when HF Spaces restarts the container.
"""
from __future__ import annotations
import atexit
import csv
import io
import os
import sqlite3
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
# On Railway/custom: 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
# How long the worker waits after a dirty signal before uploading (coalesces bursts)
_SYNC_INTERVAL = int(os.environ.get("HF_SYNC_INTERVAL", "30"))
# Seeded admin account — override via ADMIN_EMAIL env var when transferring ownership
_ADMIN_EMAIL = os.environ.get("ADMIN_EMAIL", "").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 (debounced background sync worker)
# ---------------------------------------------------------------------------
# Signals that the DB has un-uploaded changes
_dirty = threading.Event()
# Ensures only one upload runs at a time (prevents interleaved writes to HF)
_upload_lock = threading.Lock()
# Guard so we only ever start one worker thread per process
_worker_started = False
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))
print("[DB] Restored explorer.db from HF Hub dataset.", flush=True)
except Exception as e:
# File not in repo yet (first deploy) or network error — start fresh.
print(f"[DB] Could not restore from HF Hub (first run or network issue): {e}", flush=True)
def _sync_db_to_hub() -> None:
"""Upload explorer.db to HF Hub dataset — always called while holding _upload_lock."""
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",
)
print("[DB] Synced explorer.db → HF Hub dataset.", flush=True)
except Exception as e:
print(f"[DB] HF Hub upload failed (will retry on next dirty signal): {e}", flush=True)
def _sync_worker() -> None:
"""Long-lived daemon thread: coalesces rapid writes into a single upload.
Flow:
1. Block on _dirty (no CPU when idle).
2. Sleep _SYNC_INTERVAL seconds so bursts of writes are batched.
3. Clear the flag, acquire the lock, upload.
4. Loop back to step 1.
"""
while True:
_dirty.wait() # sleep until someone calls _push_db()
time.sleep(_SYNC_INTERVAL) # debounce window — let burst writes finish
_dirty.clear() # consume the signal
with _upload_lock:
_sync_db_to_hub()
def _start_sync_worker() -> None:
"""Launch the background sync thread (idempotent — safe to call multiple times)."""
global _worker_started
if _worker_started or not _HF_DB_REPO:
return
_worker_started = True
t = threading.Thread(target=_sync_worker, daemon=True, name="hf-db-sync")
t.start()
print(f"[DB] Background sync worker started (interval={_SYNC_INTERVAL}s).", flush=True)
def _final_push() -> None:
"""Blocking upload on process exit — guarantees data is saved before HF Spaces
tears down the container. Registered via atexit and called from FastAPI lifespan
teardown so it fires on both graceful shutdowns and SIGTERM."""
if not _HF_DB_REPO:
return
print("[DB] Shutdown: performing final sync to HF Hub…", flush=True)
with _upload_lock:
_sync_db_to_hub()
# Register for process-level exits (covers SIGTERM on HF Spaces)
atexit.register(_final_push)
def _push_db() -> None:
"""Signal that the DB has changed; the background worker will upload it.
Non-blocking — returns immediately. The actual upload is coalesced and
deferred by _SYNC_INTERVAL seconds to avoid hammering HF Hub on rapid writes.
"""
if _HF_DB_REPO:
_dirty.set()
# ---------------------------------------------------------------------------
# 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, seed the first admin, and start HF sync."""
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 \'staff\',
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 \'\',
customer_name TEXT DEFAULT '',
quote TEXT NOT NULL,
objection_type TEXT,
cluster TEXT,
customer_group TEXT,
destination TEXT,
service TEXT,
severity TEXT,
stage1_confidence REAL,
response_found INTEGER,
objection_status TEXT DEFAULT '',
first_contact_date TEXT DEFAULT '',
objection_date TEXT DEFAULT '',
main_contact_platform TEXT DEFAULT '',
ad_source TEXT DEFAULT '',
lead_quality TEXT DEFAULT ''
);
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 browse_responses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
service TEXT NOT NULL DEFAULT '',
customer_group TEXT NOT NULL DEFAULT '',
destination TEXT NOT NULL DEFAULT '',
objection_type TEXT NOT NULL DEFAULT '',
cluster 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 '',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
updated_by TEXT NOT NULL DEFAULT '',
UNIQUE(service, customer_group, destination, objection_type, cluster)
);
CREATE TABLE IF NOT EXISTS browse_deleted_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
scope TEXT NOT NULL,
value TEXT NOT NULL,
created_at TEXT NOT NULL,
created_by TEXT NOT NULL DEFAULT '',
UNIQUE(scope, value)
);
""")
# 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
interaction_columns = {
"customer_name": "TEXT DEFAULT ''",
"objection_status": "TEXT DEFAULT ''",
"first_contact_date": "TEXT DEFAULT ''",
"objection_date": "TEXT DEFAULT ''",
"main_contact_platform": "TEXT DEFAULT ''",
"ad_source": "TEXT DEFAULT ''",
"lead_quality": "TEXT DEFAULT ''",
}
existing_interaction_cols = {
row["name"] for row in con.execute("PRAGMA table_info(interactions)").fetchall()
}
for column, ddl in interaction_columns.items():
if column not in existing_interaction_cols:
con.execute(f"ALTER TABLE interactions ADD COLUMN {column} {ddl}")
# Seed first admin only when the table is completely empty and ADMIN_EMAIL is set
existing = con.execute("SELECT COUNT(*) FROM users").fetchone()[0]
if existing == 0 and _ADMIN_EMAIL:
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)
# Start the single background HF sync worker (no-op if HF_DB_REPO not set)
_start_sync_worker()
# ---------------------------------------------------------------------------
# Browse responses
# ---------------------------------------------------------------------------
BROWSE_RESPONSE_COLUMNS = [
"id",
"service",
"customer_group",
"destination",
"objection_type",
"cluster",
"severity",
"solution",
"perfect_response",
"follow_up_question",
"video_id",
"perfect_response_km",
"solution_km",
"follow_up_question_km",
"updated_at",
"updated_by",
]
BROWSE_EDITABLE_COLUMNS = [
"service",
"customer_group",
"destination",
"objection_type",
"cluster",
"severity",
"solution",
"perfect_response",
"follow_up_question",
"video_id",
"perfect_response_km",
"solution_km",
"follow_up_question_km",
]
BROWSE_RESPONSE_EXPORT_COLUMNS = [
"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",
]
def _clean(value: object) -> str:
return "" if value is None else str(value).strip()
def _normalise_group(value: object) -> str:
group = _clean(value)
if group.upper().replace(" ", "") in {"VISA-FOR", "VISA-FOREIGNER"} or group.upper() == "VISA - FOR":
return "VISA-FOR"
return group
def seed_browse_responses(rows: list[dict], *, updated_by: str = "system") -> int:
"""Insert missing Browse matrix rows without overwriting existing responses.
This is intentionally additive. CSV files can seed or extend the matrix, but
filled database responses remain the source of truth.
"""
if not rows:
return 0
now = _now()
inserted = 0
with _conn() as con:
deleted = get_browse_deleted_items(con)
for row in rows:
values = {
"service": _clean(row.get("service")),
"customer_group": _normalise_group(row.get("customer_group")),
"destination": _clean(row.get("destination")).upper(),
"objection_type": _clean(row.get("objection_type")),
"cluster": _clean(row.get("cluster")),
"severity": _clean(row.get("severity")),
"solution": _clean(row.get("solution")),
"perfect_response": _clean(row.get("perfect_response")),
"follow_up_question": _clean(row.get("follow_up_question")),
"video_id": _clean(row.get("video_id")),
"perfect_response_km": _clean(row.get("perfect_response_km")),
"solution_km": _clean(row.get("solution_km")),
"follow_up_question_km": _clean(row.get("follow_up_question_km")),
"created_at": now,
"updated_at": now,
"updated_by": updated_by,
}
if not (values["service"] and values["customer_group"] and values["cluster"] and values["objection_type"]):
continue
if _browse_row_is_deleted(values, deleted):
continue
cur = con.execute(
"""INSERT OR IGNORE INTO browse_responses
(service, customer_group, destination, objection_type, cluster,
severity, solution, perfect_response, follow_up_question, video_id,
perfect_response_km, solution_km, follow_up_question_km,
created_at, updated_at, updated_by)
VALUES
(:service, :customer_group, :destination, :objection_type, :cluster,
:severity, :solution, :perfect_response, :follow_up_question, :video_id,
:perfect_response_km, :solution_km, :follow_up_question_km,
:created_at, :updated_at, :updated_by)""",
values,
)
inserted += cur.rowcount
if inserted:
_push_db()
return inserted
def get_browse_deleted_items(con: Optional[sqlite3.Connection] = None) -> dict[str, set[str]]:
"""Return deleted matrix scopes used to keep CSV seeding from re-adding rows."""
close_when_done = con is None
con = con or _conn()
try:
rows = con.execute("SELECT scope, value FROM browse_deleted_items").fetchall()
deleted: dict[str, set[str]] = {"service": set(), "objection_type": set(), "cluster": set(), "row": set()}
for row in rows:
scope = _clean(row["scope"]).lower()
value = _clean(row["value"])
if scope in deleted and value:
deleted[scope].add(value.lower())
return deleted
finally:
if close_when_done:
con.close()
def _browse_row_is_deleted(row: dict, deleted: dict[str, set[str]]) -> bool:
return (
_browse_row_delete_key(row).lower() in deleted.get("row", set())
or
_clean(row.get("service")).lower() in deleted.get("service", set())
or _clean(row.get("objection_type")).lower() in deleted.get("objection_type", set())
or _clean(row.get("cluster")).lower() in deleted.get("cluster", set())
)
def _browse_row_delete_key(row: dict) -> str:
"""Stable key for deleting one service/type/cluster row without deleting its peers."""
return "|".join(
[
_clean(row.get("service")).lower(),
_normalise_group(row.get("customer_group")).lower(),
_clean(row.get("destination")).upper().lower(),
_clean(row.get("objection_type")).lower(),
_clean(row.get("cluster")).lower(),
]
)
def get_browse_responses() -> list[dict]:
with _conn() as con:
rows = con.execute(
"""SELECT id, service, customer_group, destination, objection_type, cluster,
severity, solution, perfect_response, follow_up_question, video_id,
perfect_response_km, solution_km, follow_up_question_km,
updated_at, updated_by
FROM browse_responses
ORDER BY customer_group, destination, service, objection_type, cluster"""
).fetchall()
return [dict(row) for row in rows]
def delete_browse_matrix_item(scope: str, value: str, *, deleted_by: str = "") -> int:
"""Delete a service, objection type, or cluster from Browse responses.
The deletion is also recorded in browse_deleted_items so CSV seeding does
not re-create the same matrix rows on the next app startup.
"""
scope = _clean(scope).lower()
value = _clean(value)
if scope not in {"service", "objection_type", "cluster"}:
raise ValueError("Delete scope must be service, objection_type, or cluster.")
if not value:
raise ValueError("Delete value is required.")
now = _now()
with _conn() as con:
con.execute(
"""INSERT OR IGNORE INTO browse_deleted_items
(scope, value, created_at, created_by)
VALUES (?, ?, ?, ?)""",
(scope, value, now, deleted_by),
)
cur = con.execute(f"DELETE FROM browse_responses WHERE {scope} = ?", (value,))
deleted = int(cur.rowcount)
_push_db()
return deleted
def delete_browse_response_row(row_id: int, *, deleted_by: str = "") -> dict:
"""Delete exactly one Browse response row and prevent CSV seeding from recreating it."""
now = _now()
with _conn() as con:
row = con.execute("SELECT * FROM browse_responses WHERE id = ?", (row_id,)).fetchone()
if not row:
raise KeyError(f"Browse response row not found: {row_id}")
row_dict = dict(row)
con.execute(
"""INSERT OR IGNORE INTO browse_deleted_items
(scope, value, created_at, created_by)
VALUES (?, ?, ?, ?)""",
("row", _browse_row_delete_key(row_dict), now, deleted_by),
)
con.execute("DELETE FROM browse_responses WHERE id = ?", (row_id,))
_push_db()
return row_dict
def update_browse_response(row_id: Optional[int], values: dict, *, updated_by: str = "") -> int:
cleaned = {col: _clean(values.get(col)) for col in BROWSE_EDITABLE_COLUMNS}
cleaned["customer_group"] = _normalise_group(cleaned["customer_group"])
cleaned["destination"] = cleaned["destination"].upper()
now = _now()
with _conn() as con:
if row_id is not None:
existing = con.execute("SELECT id FROM browse_responses WHERE id = ?", (row_id,)).fetchone()
if not existing:
raise KeyError(f"Browse response row not found: {row_id}")
assignments = ", ".join(f"{col} = :{col}" for col in BROWSE_EDITABLE_COLUMNS)
params = dict(cleaned)
params.update({"id": row_id, "updated_at": now, "updated_by": updated_by})
con.execute(
f"""UPDATE browse_responses
SET {assignments}, updated_at = :updated_at, updated_by = :updated_by
WHERE id = :id""",
params,
)
saved_id = row_id
else:
params = dict(cleaned)
params.update({"created_at": now, "updated_at": now, "updated_by": updated_by})
cur = con.execute(
"""INSERT INTO browse_responses
(service, customer_group, destination, objection_type, cluster,
severity, solution, perfect_response, follow_up_question, video_id,
perfect_response_km, solution_km, follow_up_question_km,
created_at, updated_at, updated_by)
VALUES
(:service, :customer_group, :destination, :objection_type, :cluster,
:severity, :solution, :perfect_response, :follow_up_question, :video_id,
:perfect_response_km, :solution_km, :follow_up_question_km,
:created_at, :updated_at, :updated_by)""",
params,
)
saved_id = int(cur.lastrowid)
_push_db()
return int(saved_id)
def browse_responses_csv() -> str:
rows = get_browse_responses()
buffer = io.StringIO()
buffer.write("\ufeff")
writer = csv.DictWriter(buffer, fieldnames=BROWSE_RESPONSE_EXPORT_COLUMNS, lineterminator="\n")
writer.writeheader()
for row in rows:
writer.writerow({col: row.get(col, "") for col in BROWSE_RESPONSE_EXPORT_COLUMNS})
return buffer.getvalue()
# ---------------------------------------------------------------------------
# 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()
def delete_user(email: str) -> None:
with _conn() as con:
con.execute("DELETE FROM users WHERE email = ?", (email.strip().lower(),))
_push_db()
# ---------------------------------------------------------------------------
# Interactions
# ---------------------------------------------------------------------------
def log_interaction(
user_email: str,
user_name: str,
quote: str,
customer_name: 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, customer_name, quote, objection_type, cluster,
customer_group, destination, service, severity, stage1_confidence, response_found,
objection_status, first_contact_date, objection_date, main_contact_platform,
ad_source, lead_quality)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
_now(), user_email, user_name, customer_name, quote, objection_type, cluster,
customer_group, destination, service, severity, stage1_confidence,
1 if response_found else 0, objection_status, first_contact_date,
objection_date, main_contact_platform, ad_source, lead_quality,
),
)
_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 update_interaction_lead_quality(interaction_id: int, lead_quality: str) -> bool:
"""Update lead quality for a saved consultation record."""
quality = (lead_quality or "").strip()
allowed = {
"Qualified",
"Not Qualified",
"Lost",
"Converted",
"Intake",
"Awaiting Documents",
}
if quality not in allowed:
return False
with _conn() as con:
cur = con.execute(
"UPDATE interactions SET lead_quality = ? WHERE id = ?",
(quality, interaction_id),
)
changed = cur.rowcount > 0
if changed:
_push_db()
return changed
def update_interaction_fields(interaction_id: int, fields: dict) -> bool:
"""Update editable customer objection tracking fields for one interaction."""
allowed = {
"customer_name",
"quote",
"objection_type",
"cluster",
"severity",
"service",
"destination",
"objection_status",
"first_contact_date",
"objection_date",
"main_contact_platform",
"ad_source",
"lead_quality",
}
updates = {
key: _clean(value)
for key, value in (fields or {}).items()
if key in allowed
}
if not updates:
return False
set_clause = ", ".join(f"{column} = ?" for column in updates)
values = list(updates.values()) + [interaction_id]
with _conn() as con:
cur = con.execute(
f"UPDATE interactions SET {set_clause} WHERE id = ?",
values,
)
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_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,),
)
_push_db()
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:
cur = con.execute("DELETE FROM sessions WHERE expires_at < ?", (now,))
deleted = cur.rowcount
if deleted:
_push_db()
def cleanup_old_logs(days: int = 90) -> tuple[int, int]:
"""Delete activity_log and interactions rows older than `days` days.
Returns (activity_deleted, interactions_deleted).
Interactions are analytics data — we keep them longer by default but still
purge very old rows to prevent unbounded DB growth.
"""
import datetime as _dt
cutoff = (
_dt.datetime.now(_dt.timezone.utc) - _dt.timedelta(days=days)
).strftime("%Y-%m-%d %H:%M:%S")
with _conn() as con:
cur_a = con.execute("DELETE FROM activity_log WHERE timestamp < ?", (cutoff,))
cur_i = con.execute("DELETE FROM interactions WHERE timestamp < ?", (cutoff,))
a, i = cur_a.rowcount, cur_i.rowcount
if a or i:
_push_db()
return a, i
"""
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 FastAPI/)
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)
HF_SYNC_INTERVAL = 30 (optional, seconds between uploads)
On startup, init_db() downloads explorer.db from the dataset and launches a
single long-lived background sync worker thread. Every write calls _push_db()
which simply sets a threading.Event. The worker wakes, waits HF_SYNC_INTERVAL
seconds (so rapid sequential writes are coalesced into one upload), then
uploads. A final blocking upload fires on process exit via atexit so no data
is lost when HF Spaces restarts the container.
"""
from __future__ import annotations
import atexit
import csv
import io
import os
import sqlite3
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
# On Railway/custom: 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
# How long the worker waits after a dirty signal before uploading (coalesces bursts)
_SYNC_INTERVAL = int(os.environ.get("HF_SYNC_INTERVAL", "30"))
# Seeded admin account — override via ADMIN_EMAIL env var when transferring ownership
_ADMIN_EMAIL = os.environ.get("ADMIN_EMAIL", "").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 (debounced background sync worker)
# ---------------------------------------------------------------------------
# Signals that the DB has un-uploaded changes
_dirty = threading.Event()
# Ensures only one upload runs at a time (prevents interleaved writes to HF)
_upload_lock = threading.Lock()
# Guard so we only ever start one worker thread per process
_worker_started = False
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)