Spaces:
Running on Zero

MyNewWebSite / backend /database.py
SHADOWMONARCK097's picture
Deploy Customer Complaint Sentiment FastAPI Docker backend
77da222 verified
Raw History Blame Contribute Delete
12.5 kB
"""Database layer for customer complaints logging and historical analytics.
Uses SQLite3 for zero-setup, self-contained persistence. Supports
single and bulk record insertions, filtering, and summary statistics.
"""
from __future__ import annotations
import sqlite3
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Generator
VALID_STATUSES = ("Received", "In Review", "Escalated", "Resolved")
BASE_DIR = Path(__file__).resolve().parent.parent
DEFAULT_DB_PATH = BASE_DIR / "backend" / "complaints.db"
def format_ticket_id(row_id: int) -> str:
"""Format a simple sequential customer-facing Ticket Number (e.g., TKT-001)."""
return f"TKT-{int(row_id):03d}"
def get_db_path(custom_path: Path | str | None = None) -> Path:
"""Resolve database file path."""
if custom_path is not None:
p = Path(custom_path)
else:
p = DEFAULT_DB_PATH
p.parent.mkdir(parents=True, exist_ok=True)
return p
@contextmanager
def get_connection(db_path: Path | str | None = None) -> Generator[sqlite3.Connection, None, None]:
"""Yield a managed SQLite connection with Row factory."""
resolved_path = get_db_path(db_path)
conn = sqlite3.connect(str(resolved_path), timeout=15.0)
conn.row_factory = sqlite3.Row
try:
yield conn
conn.commit()
except Exception:
conn.rollback()
raise
finally:
conn.close()
def init_db(db_path: Path | str | None = None) -> None:
"""Initialize database tables, indexes, and safe schema migrations."""
with get_connection(db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS complaints (
id INTEGER PRIMARY KEY AUTOINCREMENT,
reference_id TEXT,
phone_number TEXT DEFAULT '',
text TEXT NOT NULL,
cleaned_text TEXT,
sentiment TEXT NOT NULL,
confidence REAL NOT NULL,
urgency TEXT NOT NULL,
urgency_score REAL DEFAULT 0.0,
model_used TEXT DEFAULT 'baseline',
status TEXT DEFAULT 'Received',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
# Safe migration for existing databases created prior to reference_id/phone_number/status
cursor.execute("PRAGMA table_info(complaints)")
existing_cols = {row["name"] for row in cursor.fetchall()}
if "reference_id" not in existing_cols:
cursor.execute("ALTER TABLE complaints ADD COLUMN reference_id TEXT")
if "phone_number" not in existing_cols:
cursor.execute("ALTER TABLE complaints ADD COLUMN phone_number TEXT DEFAULT ''")
if "status" not in existing_cols:
cursor.execute("ALTER TABLE complaints ADD COLUMN status TEXT DEFAULT 'Received'")
# Backfill reference_id / status for any legacy rows using simple TKT-001 format
cursor.execute("SELECT id FROM complaints WHERE reference_id IS NULL OR reference_id = ''")
for row in cursor.fetchall():
cursor.execute(
"UPDATE complaints SET reference_id = ? WHERE id = ?",
(format_ticket_id(int(row["id"])), row["id"]),
)
cursor.execute("UPDATE complaints SET status = 'Received' WHERE status IS NULL OR status = ''")
cursor.execute(
"""
CREATE INDEX IF NOT EXISTS idx_complaints_sentiment ON complaints(sentiment);
"""
)
cursor.execute(
"""
CREATE INDEX IF NOT EXISTS idx_complaints_urgency ON complaints(urgency);
"""
)
cursor.execute(
"""
CREATE INDEX IF NOT EXISTS idx_complaints_created_at ON complaints(created_at);
"""
)
cursor.execute(
"""
CREATE UNIQUE INDEX IF NOT EXISTS idx_complaints_reference_id ON complaints(reference_id);
"""
)
def insert_complaint(record: dict[str, Any], db_path: Path | str | None = None) -> int:
"""Insert a single processed complaint into the database.
Auto-populates ``reference_id`` (simple sequential ``TKT-001``) and ``status``.
Returns:
The newly inserted record's auto-generated primary key ID.
"""
init_db(db_path)
now_iso = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
status_val = record.get("status") or "Received"
phone_val = (record.get("phone_number") or "").strip()
custom_ref = record.get("reference_id")
record["status"] = status_val
record["phone_number"] = phone_val
with get_connection(db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO complaints (
reference_id, phone_number, text, cleaned_text, sentiment, confidence, urgency, urgency_score, model_used, status, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
custom_ref,
phone_val,
record.get("text", ""),
record.get("cleaned_text", ""),
record.get("sentiment", "Neutral"),
float(record.get("confidence", 0.0)),
record.get("urgency", "Low"),
float(record.get("urgency_score", 0.0)),
record.get("model_used", "baseline"),
status_val,
record.get("created_at", now_iso)
)
)
row_id = int(cursor.lastrowid)
ref_id = custom_ref or format_ticket_id(row_id)
if not custom_ref:
cursor.execute("UPDATE complaints SET reference_id = ? WHERE id = ?", (ref_id, row_id))
record["reference_id"] = ref_id
return row_id
def insert_complaints_batch(records: list[dict[str, Any]], db_path: Path | str | None = None) -> list[int]:
"""Insert a batch of complaints efficiently within a single transaction.
Returns:
List of generated IDs.
"""
if not records:
return []
init_db(db_path)
now_iso = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
inserted_ids: list[int] = []
with get_connection(db_path) as conn:
cursor = conn.cursor()
for r in records:
custom_ref = r.get("reference_id")
status_val = r.get("status") or "Received"
phone_val = (r.get("phone_number") or "").strip()
r["status"] = status_val
r["phone_number"] = phone_val
cursor.execute(
"""
INSERT INTO complaints (
reference_id, phone_number, text, cleaned_text, sentiment, confidence, urgency, urgency_score, model_used, status, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
custom_ref,
phone_val,
r.get("text", ""),
r.get("cleaned_text", ""),
r.get("sentiment", "Neutral"),
float(r.get("confidence", 0.0)),
r.get("urgency", "Low"),
float(r.get("urgency_score", 0.0)),
r.get("model_used", "baseline"),
status_val,
r.get("created_at", now_iso)
)
)
row_id = int(cursor.lastrowid)
ref_id = custom_ref or format_ticket_id(row_id)
if not custom_ref:
cursor.execute("UPDATE complaints SET reference_id = ? WHERE id = ?", (ref_id, row_id))
r["reference_id"] = ref_id
inserted_ids.append(row_id)
return inserted_ids
def get_complaint_by_reference(reference_id: str, db_path: Path | str | None = None) -> dict[str, Any] | None:
"""Look up a single complaint by its Ticket ID (e.g., TKT-001, TKT-1, or 1)."""
clean_ref = (reference_id or "").strip().upper()
if not clean_ref:
return None
init_db(db_path)
with get_connection(db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT * FROM complaints WHERE UPPER(reference_id) = ? LIMIT 1",
(clean_ref,),
)
row = cursor.fetchone()
if row is not None:
return dict(row)
# Fallback: allow lookup by numeric part (e.g. '1', '#1', 'TKT-1')
numeric = clean_ref.replace("TKT-", "").lstrip("#")
if numeric.isdigit():
cursor.execute("SELECT * FROM complaints WHERE id = ? LIMIT 1", (int(numeric),))
row = cursor.fetchone()
if row is not None:
return dict(row)
return None
def update_complaint_status(reference_id: str, new_status: str, db_path: Path | str | None = None) -> bool:
"""Update the workflow progress status for a complaint by Reference ID."""
if new_status not in VALID_STATUSES:
raise ValueError(f"Invalid status '{new_status}'. Must be one of: {VALID_STATUSES}")
clean_ref = (reference_id or "").strip().upper()
if not clean_ref:
return False
init_db(db_path)
with get_connection(db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"UPDATE complaints SET status = ? WHERE UPPER(reference_id) = ?",
(new_status, clean_ref),
)
return cursor.rowcount > 0
def get_history(
limit: int = 100,
offset: int = 0,
sentiment: str | None = None,
urgency: str | None = None,
db_path: Path | str | None = None
) -> list[dict[str, Any]]:
"""Retrieve historical analyzed complaints with optional filtering and pagination."""
query = "SELECT * FROM complaints WHERE 1=1"
params: list[Any] = []
if sentiment:
query += " AND sentiment = ?"
params.append(sentiment)
if urgency:
query += " AND urgency = ?"
params.append(urgency)
query += " ORDER BY id DESC LIMIT ? OFFSET ?"
params.extend([max(1, limit), max(0, offset)])
with get_connection(db_path) as conn:
cursor = conn.cursor()
cursor.execute(query, params)
rows = cursor.fetchall()
return [dict(row) for row in rows]
def get_analytics_summary(db_path: Path | str | None = None) -> dict[str, Any]:
"""Compute aggregate analytical statistics from historical complaints."""
with get_connection(db_path) as conn:
cursor = conn.cursor()
# Total count
cursor.execute("SELECT COUNT(*) AS total FROM complaints")
total = int(cursor.fetchone()["total"])
if total == 0:
return {
"total_complaints": 0,
"sentiment_distribution": {"Negative": 0, "Neutral": 0, "Positive": 0},
"urgency_distribution": {"High": 0, "Medium": 0, "Low": 0},
"average_confidence": 0.0,
"high_urgency_ratio": 0.0,
"negative_ratio": 0.0
}
# Sentiment breakdown
cursor.execute("SELECT sentiment, COUNT(*) as cnt FROM complaints GROUP BY sentiment")
sent_counts = {r["sentiment"]: int(r["cnt"]) for r in cursor.fetchall()}
sentiment_dist = {
"Negative": sent_counts.get("Negative", 0),
"Neutral": sent_counts.get("Neutral", 0),
"Positive": sent_counts.get("Positive", 0)
}
# Urgency breakdown
cursor.execute("SELECT urgency, COUNT(*) as cnt FROM complaints GROUP BY urgency")
urg_counts = {r["urgency"]: int(r["cnt"]) for r in cursor.fetchall()}
urgency_dist = {
"High": urg_counts.get("High", 0),
"Medium": urg_counts.get("Medium", 0),
"Low": urg_counts.get("Low", 0)
}
# Average confidence
cursor.execute("SELECT AVG(confidence) as avg_conf FROM complaints")
avg_conf_row = cursor.fetchone()
avg_confidence = round(float(avg_conf_row["avg_conf"] or 0.0), 4)
return {
"total_complaints": total,
"sentiment_distribution": sentiment_dist,
"urgency_distribution": urgency_dist,
"average_confidence": avg_confidence,
"high_urgency_ratio": round(urgency_dist["High"] / total, 4),
"negative_ratio": round(sentiment_dist["Negative"] / total, 4)
}