Download FastAPI/main.py from Sakda101/explorer-consultant-bot: direct link, hf CLI and curl.
- Browser
- Download file 57.8 kB
-
https://huggingface.co/spaces/Sakda101/explorer-consultant-bot/resolve/main/FastAPI/main.py
- Command line
-
hf download hf://spaces/Sakda101/explorer-consultant-bot/FastAPI/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Sakda101/explorer-consultant-bot/resolve/main/FastAPI/main.py
57.8 kB
"""
Explorer Consultant Bot β FastAPI entry point.
Run locally:
cd FastAPI
uvicorn main:app --reload --port 8000
All routes:
GET / β redirect to /home or /login
GET /login β login form
POST /login β validate, set cookie, redirect
POST /setup-password β first-time password creation
GET /logout β clear session + cookie
GET /home β authenticated home
GET /consultants β objection analyzer page
GET /api/services β JSON: services for a given group
GET /api/type-cluster-map β JSON: objection type β cluster list
POST /api/predict β JSON: run DistilBERT prediction
POST /api/correction β save staff correction
GET /browse β response browser
POST /browse/edit β save response edit to database
POST /browse/delete β delete service/type/cluster from Browse
GET /browse/export.csv β CSV download of Browse responses
GET /analytics β analytics dashboard
GET /api/analytics-data β JSON: interactions + stats for charts
POST /analytics/delete β admin: delete interactions
GET /admin β admin panel (3 tabs)
POST /admin/users/add β add new user
POST /admin/users/update β update user role / name / status / password
POST /admin/corrections/delete β delete a correction row
GET /admin/export/users β CSV download of all users
"""
from __future__ import annotations
import csv
import io
import json
import os
import re
import sys
import threading
from collections import Counter
from contextlib import asynccontextmanager
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from typing import Optional
import pandas as pd
from fastapi import Depends, FastAPI, Form, HTTPException, Request, Response
from fastapi.responses import (
HTMLResponse,
JSONResponse,
RedirectResponse,
StreamingResponse,
)
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from core import auth
from core import database as db
# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
BASE_DIR = Path(__file__).parent
REPO_DIR = BASE_DIR.parent
RESPONSES_CSV = REPO_DIR / "data" / "responses.csv"
SERVICES_CSV = REPO_DIR / "Webapp" / "Services.csv"
# ---------------------------------------------------------------------------
# Group display labels
# ---------------------------------------------------------------------------
GROUP_DISPLAY = {"VISA - KH": "VISA - KHMER", "VISA-FOR": "VISA - FOREIGNER"}
GROUP_INTERNAL = {v: k for k, v in GROUP_DISPLAY.items()}
GROUP_LABELS = list(GROUP_DISPLAY.values()) # ["VISA - KHMER", "VISA - FOREIGNER"]
APP_TZ = timezone(timedelta(hours=7))
# ---------------------------------------------------------------------------
# Helpers: load data from CSV files (called at startup + after edits)
# ---------------------------------------------------------------------------
def _load_services() -> dict[str, list[str]]:
"""Return {internal_group: [service_code, ...]} from Services.csv."""
services: dict[str, list[str]] = {}
try:
with open(SERVICES_CSV, encoding="utf-8") as f:
for line in f:
line = line.strip().rstrip(",")
if not line:
continue
parts = line.split(",", 1)
if len(parts) == 2:
group = parts[0].strip()
code = parts[1].strip()
if code:
services.setdefault(group, []).append(code)
except Exception:
pass
return services
RESPONSE_COLUMNS = (
"service", "customer_group", "destination", "cluster", "objection_type",
"severity", "video_id",
"perfect_response", "perfect_response_km",
"solution", "solution_km",
"follow_up_question", "follow_up_question_km",
)
def _normalise_group(group: str) -> str:
group = (group or "").strip()
if group.upper().replace(" ", "") in {"VISA-FOR", "VISA-FOREIGNER"} or group.upper() == "VISA - FOR":
return "VISA-FOR"
return group
def _load_response_seed_rows() -> list[dict]:
"""Read responses.csv as an additive matrix seed for the DB table."""
if not RESPONSES_CSV.exists():
return []
try:
df = pd.read_csv(RESPONSES_CSV, dtype=str, keep_default_na=False)
except Exception:
return []
for col in RESPONSE_COLUMNS:
if col not in df.columns:
df[col] = ""
df[col] = df[col].fillna("").astype(str).str.strip()
df["customer_group"] = df["customer_group"].map(_normalise_group)
df["destination"] = df["destination"].str.upper()
df = df[
(df["service"].str.strip() != "")
& (df["customer_group"].str.strip() != "")
& (df["cluster"].str.strip() != "")
& (df["objection_type"].str.strip() != "")
].copy()
df = df.drop_duplicates(["service", "customer_group", "destination", "objection_type", "cluster"], keep="first")
return df[list(RESPONSE_COLUMNS)].to_dict(orient="records")
def _load_responses() -> pd.DataFrame:
"""Load database-backed Browse responses, seeding missing matrix rows from CSV."""
try:
db.seed_browse_responses(_load_response_seed_rows(), updated_by="csv-seed")
rows = db.get_browse_responses()
df = pd.DataFrame(rows)
for col in ("id", *RESPONSE_COLUMNS):
if col not in df.columns:
df[col] = ""
df[col] = df[col].fillna("").astype(str).str.strip()
return df
except Exception:
return pd.DataFrame()
def _load_active_services() -> dict[str, list[str]]:
"""Return services that still have active DB response rows."""
df = _load_responses()
services: dict[str, list[str]] = {}
if not df.empty and {"customer_group", "service"}.issubset(df.columns):
for group, group_df in df.groupby("customer_group"):
codes = sorted(
{
str(service).strip()
for service in group_df["service"].tolist()
if str(service).strip()
}
)
if codes:
services[str(group).strip()] = codes
return services or _load_services()
def _load_type_cluster_map() -> dict[str, list[str]]:
"""Return {objection_type: [cluster, ...]} from responses.csv."""
try:
df = _load_responses()
result: dict[str, set] = {}
for _, row in df.iterrows():
t = str(row.get("objection_type", "")).strip()
c = str(row.get("cluster", "")).strip()
if t and c and t != "nan" and c != "nan":
result.setdefault(t, set()).add(c)
return {t: sorted(clusters) for t, clusters in sorted(result.items())}
except Exception:
return {}
def _extract_destination(service_code: str) -> str:
m = re.match(r"VISA\s*[-]\s*([A-Z]+)\s*[|]?", service_code.strip())
return m.group(1) if m else ""
def _service_has_objection(
service: str,
customer_group: str,
destination: str,
objection_type: str,
cluster: str,
) -> Optional[bool]:
"""Return whether a predicted type/cluster is valid for the selected service.
None means there is not enough service context to make the decision.
"""
service = (service or "").strip()
objection_type = (objection_type or "").strip().lower()
cluster = (cluster or "").strip().lower()
if not service or not objection_type or not cluster:
return None
df = _load_responses()
if df.empty:
return None
work = df.copy()
for col in ("service", "customer_group", "destination", "objection_type", "cluster"):
if col not in work.columns:
work[col] = ""
work[col] = work[col].fillna("").astype(str).str.strip()
pair_exists_anywhere = (
(work["objection_type"].str.lower() == objection_type)
& (work["cluster"].str.lower() == cluster)
).any()
if not pair_exists_anywhere:
return None
exact = (
(work["service"].str.lower() == service.lower())
& (work["objection_type"].str.lower() == objection_type)
& (work["cluster"].str.lower() == cluster)
)
if customer_group:
exact &= work["customer_group"].str.lower() == customer_group.strip().lower()
if destination:
exact &= (
(work["destination"].str.upper() == destination.strip().upper())
| (work["destination"].str.strip() == "")
)
return bool(exact.any())
_OBJECTION_SIGNAL_RE = re.compile(
r"\b("
r"do i need|need|required|require|missing|don't have|do not have|cannot prepare|can't prepare|"
r"expensive|price|cost|fee|cheap|discount|refund|"
r"slow|delay|too long|how long|fast|urgent|processing|waiting|"
r"reject|rejected|rejection|refuse|refused|blacklist|guarantee|approve|approval|risk|"
r"document|passport|bank|statement|salary|employment|letter|leave|patent|"
r"certificate|marriage|minor|birth|sponsor|deposit|work permit|"
r"location|office|far|map|come|visit|"
r"trust|scam|fake|forge|forgery|competitor|"
r"another agency|other agency|other company|other business|other firm|"
r"their staff|their service|not like you|not like your side|your side|"
r"answer all my questions|reply all my questions|respond all my questions|"
r"good at explaining|explain more detail|don't know much|don't understand much|"
r"travel history|extension"
r")\b",
re.IGNORECASE,
)
_NON_OBJECTION_RE = re.compile(
r"^\s*(hi|hello|hey|thanks|thank you|ok|okay|yes|no|good morning|good afternoon|"
r"good evening|test|testing|asdf|qwerty|what is your name|who are you)\s*[.!?]*\s*$",
re.IGNORECASE,
)
def _contains_customer_objection(quote: str) -> bool:
"""Return True when text looks relevant to a customer visa objection."""
cleaned = re.sub(r"\s+", " ", quote or "").strip()
if len(cleaned) < 8:
return False
if _NON_OBJECTION_RE.match(cleaned):
return False
return bool(_OBJECTION_SIGNAL_RE.search(cleaned))
def _parse_db_timestamp(value: str) -> Optional[datetime]:
try:
dt = datetime.strptime(str(value), "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
return dt.astimezone(APP_TZ)
except Exception:
return None
def _percent_delta(current: int | float, previous: int | float) -> int:
if previous == 0:
return 0 if current == 0 else 100
return int(round(((current - previous) / previous) * 100))
def _home_dashboard(user: dict) -> dict:
now = datetime.now(APP_TZ)
start_today = now.replace(hour=0, minute=0, second=0, microsecond=0)
start_yesterday = start_today - timedelta(days=1)
start_week = start_today - timedelta(days=start_today.weekday())
start_prev_week = start_week - timedelta(days=7)
one_hour_ago = now - timedelta(hours=1)
interactions = db.get_interactions(1000)
enriched = []
for row in interactions:
ts = _parse_db_timestamp(row.get("timestamp", ""))
if not ts:
continue
item = dict(row)
item["_dt"] = ts
enriched.append(item)
today_count = sum(1 for r in enriched if r["_dt"] >= start_today)
yesterday_count = sum(1 for r in enriched if start_yesterday <= r["_dt"] < start_today)
week_count = sum(1 for r in enriched if r["_dt"] >= start_week)
prev_week_count = sum(1 for r in enriched if start_prev_week <= r["_dt"] < start_week)
last_hour_count = sum(1 for r in enriched if r["_dt"] >= one_hour_ago)
matched = sum(1 for r in enriched if r.get("response_found"))
match_rate = int(round((matched / len(enriched)) * 100)) if enriched else 0
users = db.get_all_users()
active_staff = 0
for staff in users:
last_login = _parse_db_timestamp(staff.get("last_login", "") or "")
if last_login and last_login >= start_today:
active_staff += 1
latest = []
for row in enriched[:5]:
latest.append({
"time": row["_dt"].strftime("%H:%M"),
"staff": row.get("user_name") or (row.get("user_email", "Staff").split("@")[0]),
"quote": row.get("quote", ""),
"type": row.get("objection_type") or "Unclassified",
"cluster": row.get("cluster") or "No cluster",
"severity": row.get("severity") or "Low",
})
first_name = (user.get("name") or user.get("email") or "there").split()[0]
date_label = now.strftime("%A, %B %d").replace(" 0", " ")
hour_word = "objection" if last_hour_count == 1 else "objections"
return {
"first_name": first_name,
"date_label": date_label,
"last_hour_count": last_hour_count,
"last_hour_word": hour_word,
"stats": [
{"label": "Analyses today", "value": today_count, "delta": _percent_delta(today_count, yesterday_count), "hint": "vs. yesterday", "tone": "gold", "spark": "10,26 45,20 80,32 115,18 150,14 185,24 220,10 255,4 290,12 325,2"},
{"label": "This week", "value": week_count, "delta": _percent_delta(week_count, prev_week_count), "hint": "vs. last week", "tone": "gold", "spark": "10,26 62,24 114,22 166,19 218,16 270,12 325,8"},
{"label": "Match rate", "value": f"{match_rate}%", "delta": 0, "hint": "responses found", "tone": "green", "spark": "10,9 62,9 114,10 166,10 218,9 270,8 325,8"},
{"label": "Active staff", "value": active_staff, "delta": 0, "hint": "signed in today", "tone": "blue", "spark": "10,28 62,22 114,16 166,19 218,14 270,17 325,17"},
],
"latest": latest,
}
# ---------------------------------------------------------------------------
# Module-level caches (populated at startup, refreshed after edits)
# ---------------------------------------------------------------------------
_SERVICES_MAP: dict[str, list[str]] = {}
_TYPE_CLUSTER_MAP: dict[str, list[str]] = {}
_PREDICTOR = None # lazy-loaded ObjectionPredictor
def _get_predictor():
global _PREDICTOR
if _PREDICTOR is None:
from core.predictor import ObjectionPredictor
_PREDICTOR = ObjectionPredictor()
return _PREDICTOR
def _warm_predictor() -> None:
"""Load the ML models after startup so the first user request is faster."""
try:
_get_predictor()
print("[ML] Predictor loaded.", flush=True)
except Exception as e:
print(f"[WARNING] Predictor warmup failed: {e}", file=sys.stderr, flush=True)
# ---------------------------------------------------------------------------
# App lifespan
# ---------------------------------------------------------------------------
@asynccontextmanager
async def lifespan(app: FastAPI):
global _SERVICES_MAP, _TYPE_CLUSTER_MAP
# ββ Startup ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# init_db() restores explorer.db from HF Hub (if HF_DB_REPO is set),
# bootstraps the schema, seeds the admin row, and starts the background
# sync worker thread (all idempotent / no-ops when env vars are absent).
db.init_db()
db.seed_browse_responses(_load_response_seed_rows(), updated_by="csv-seed")
_SERVICES_MAP = _load_active_services()
_TYPE_CLUSTER_MAP = _load_type_cluster_map()
_ensure_models()
threading.Thread(target=_warm_predictor, daemon=True, name="predictor-warmup").start()
yield
# ββ Shutdown βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Blocking final upload β ensures no data is lost when HF Spaces tears
# down the container on restart. Safe to call even if HF_DB_REPO is unset.
db._final_push()
def _ensure_models() -> None:
"""Download ML models from HF Hub into /tmp/hf_artifacts if not local."""
repo_artifacts = REPO_DIR / "artifacts"
notebook_artifacts = REPO_DIR / "notebooks" / "artifacts"
for artifacts_dir in (repo_artifacts, notebook_artifacts):
if (artifacts_dir / "final_model.pkl").exists() or (artifacts_dir / "distilbert_stage1").exists():
os.environ["ARTIFACTS_DIR"] = str(artifacts_dir)
return
local_dir = Path("/tmp/hf_artifacts")
if (local_dir / "final_model.pkl").exists() or (local_dir / "distilbert_stage1").exists():
os.environ["ARTIFACTS_DIR"] = str(local_dir)
return
hf_repo = os.environ.get("HF_REPO_ID", "Sakda101/explorer-consultant-models")
hf_token = os.environ.get("HF_TOKEN", "") or None
try:
from huggingface_hub import snapshot_download
import shutil
snapshot_download(
repo_id=hf_repo, repo_type="model", token=hf_token,
local_dir=str(local_dir),
ignore_patterns=["*.gitattributes", ".gitattributes"],
)
nested = local_dir / "artifacts"
if nested.exists() and ((nested / "final_model.pkl").exists() or (nested / "distilbert_stage1").exists()):
for item in nested.iterdir():
shutil.move(str(item), str(local_dir))
nested.rmdir()
except Exception as e:
print(f"[WARNING] Model download failed: {e}", file=sys.stderr)
os.environ["ARTIFACTS_DIR"] = str(local_dir)
# ---------------------------------------------------------------------------
# App + static files
# ---------------------------------------------------------------------------
app = FastAPI(title="Explorer Consultant Bot", lifespan=lifespan)
app.mount("/static", StaticFiles(directory=str(BASE_DIR / "static")), name="static")
_assets_dir = REPO_DIR / "Webapp" / "assets"
if _assets_dir.exists():
app.mount("/assets", StaticFiles(directory=str(_assets_dir)), name="assets")
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
def _render(
request: Request,
template_name: str,
context: Optional[dict] = None,
status_code: int = 200,
):
"""Render templates across Starlette's old and new TemplateResponse APIs."""
ctx = {"request": request}
if context:
ctx.update(context)
try:
return templates.TemplateResponse(request, template_name, ctx, status_code=status_code)
except TypeError:
return templates.TemplateResponse(template_name, ctx, status_code=status_code)
@app.exception_handler(auth._NotAuthenticated)
async def not_authenticated_handler(request: Request, exc: auth._NotAuthenticated):
return RedirectResponse(url="/login", status_code=303)
# ---------------------------------------------------------------------------
# ββ Auth routes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ---------------------------------------------------------------------------
@app.get("/", response_class=HTMLResponse)
async def root(request: Request):
return RedirectResponse(
url="/home" if auth.get_current_user(request) else "/login",
status_code=303,
)
@app.get("/login", response_class=HTMLResponse)
async def login_page(request: Request):
if auth.get_current_user(request):
return RedirectResponse(url="/home", status_code=303)
return _render(request, "login.html")
@app.post("/login")
async def login_submit(
request: Request,
response: Response,
email: str = Form(...),
password: str = Form(...),
):
user = auth.attempt_login(email, password)
if user is None:
return _render(
request,
"login.html",
{"error": "Incorrect email or password, or your account is inactive."},
status_code=401,
)
db.update_last_login(user["email"])
db.log_activity(user["email"], user["name"], "login", page="login")
token = auth.create_session(user)
redirect = RedirectResponse(url="/home", status_code=303)
auth.set_session_cookie(redirect, token)
return redirect
@app.post("/setup-password")
async def setup_password(
request: Request,
email: str = Form(...),
password: str = Form(...),
confirm: str = Form(...),
):
"""First-time password creation β only works when password_hash is NULL."""
email = email.strip().lower()
ctx = {}
if not email or not password:
return _render(
request, "login.html", {**ctx, "error": "Please fill in all fields."}, status_code=400
)
if password != confirm:
return _render(
request, "login.html", {**ctx, "error": "Passwords do not match."}, status_code=400
)
if len(password) < 6:
return _render(
request, "login.html", {**ctx, "error": "Password must be at least 6 characters."}, status_code=400
)
user = db.get_user(email)
if user is None or not user.get("active"):
return _render(
request, "login.html", {**ctx, "error": "Email not found or account is inactive."}, status_code=400
)
if user.get("password_hash"):
return _render(
request,
"login.html",
{**ctx, "error": "This account already has a password β use the Sign In form."},
status_code=400,
)
auth.set_user_password(email, password)
return _render(
request,
"login.html",
{**ctx, "success": "β
Password created! You can now sign in above."},
)
@app.get("/logout")
async def logout(request: Request):
token = request.cookies.get(auth.COOKIE_NAME)
if token:
db.delete_session(token)
redirect = RedirectResponse(url="/login", status_code=303)
auth.clear_session_cookie(redirect)
return redirect
# ---------------------------------------------------------------------------
# ββ Home βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ---------------------------------------------------------------------------
@app.get("/home", response_class=HTMLResponse)
async def home_page(request: Request, user: dict = Depends(auth.require_auth)):
return _render(request, "home.html", {"user": user, "home": _home_dashboard(user)})
# ---------------------------------------------------------------------------
# ββ Consultants ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ---------------------------------------------------------------------------
@app.get("/consultants", response_class=HTMLResponse)
async def consultants_page(
request: Request,
user: dict = Depends(auth.require_role("consultants")),
):
return _render(
request,
"consultants.html",
{
"user": user,
"services_json": json.dumps(_SERVICES_MAP),
"type_cluster_json": json.dumps(_TYPE_CLUSTER_MAP),
"group_labels": GROUP_LABELS,
},
)
@app.get("/api/services")
async def api_services(group: str = ""):
"""Return service list for a given display-label group."""
internal = GROUP_INTERNAL.get(group, group)
return JSONResponse(_SERVICES_MAP.get(internal, []))
@app.get("/api/type-cluster-map")
async def api_type_cluster_map():
return JSONResponse(_TYPE_CLUSTER_MAP)
class PredictRequest(BaseModel):
quote: str
customer_group: str = ""
service: str = ""
customer_name: str = ""
objection_status: str = ""
first_contact_date: str = ""
objection_date: str = ""
main_contact_platform: str = ""
ad_source: str = ""
lead_quality: str = ""
_OBJECTION_STATUSES = {"Solved", "Unsolved"}
_CONTACT_PLATFORMS = {
"Explorer Webapp",
"Explorer by SL",
"Explorer Travel Agency",
}
_LEAD_QUALITIES = {
"Qualified",
"Not Qualified",
"Lost",
"Converted",
"Intake",
"Awaiting Documents",
}
def _clean_tracking_choice(value: str, allowed: set[str], field_name: str, *, default: str = "") -> str:
value = (value or "").strip()
if not value:
return default
if value not in allowed:
raise HTTPException(status_code=400, detail=f"Invalid {field_name}.")
return value
def _clean_tracking_date(value: str, field_name: str) -> str:
value = (value or "").strip()
if not value:
return ""
try:
date.fromisoformat(value)
except ValueError:
raise HTTPException(status_code=400, detail=f"Invalid {field_name}.")
return value
@app.post("/api/predict")
async def api_predict(body: PredictRequest, request: Request):
user = auth.get_current_user(request)
if user is None:
raise HTTPException(status_code=401, detail="Not authenticated")
quote = (body.quote or "").strip()
customer_group = (body.customer_group or "").strip()
service = (body.service or "").strip()
customer_name = (body.customer_name or "").strip()[:120]
objection_status = _clean_tracking_choice(
body.objection_status,
_OBJECTION_STATUSES,
"objection status",
default="Unsolved",
)
first_contact_date = _clean_tracking_date(body.first_contact_date, "first contact date")
objection_date = _clean_tracking_date(body.objection_date, "objection date")
main_contact_platform = _clean_tracking_choice(
body.main_contact_platform,
_CONTACT_PLATFORMS,
"main contact platform",
)
ad_source = (body.ad_source or "").strip()[:120]
lead_quality = _clean_tracking_choice(body.lead_quality, _LEAD_QUALITIES, "lead quality")
if not quote:
raise HTTPException(status_code=400, detail="quote cannot be empty")
if not _contains_customer_objection(quote):
return JSONResponse({
"no_objection": True,
"quote": quote,
"message": "This quote does not contain a customer objection.",
})
# Resolve display group β internal key
internal_group = GROUP_INTERNAL.get(customer_group, customer_group)
destination = _extract_destination(service)
try:
predictor = _get_predictor()
result = predictor.predict(quote, customer_group=internal_group, destination=destination)
# Apply staff corrections (override type/cluster if a match is found)
from core.corrections import apply_corrections_to_result
result = apply_corrections_to_result(
quote, result, predictor=predictor,
customer_group=internal_group, destination=destination,
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Prediction failed: {e}")
# Log the interaction
db.log_interaction(
user_email=user["email"],
user_name=user["name"],
customer_name=customer_name,
quote=quote,
objection_type=result.objection_type,
cluster=result.cluster,
customer_group=internal_group,
destination=destination,
service=service,
severity=result.severity or "",
stage1_confidence=result.objection_type_confidence,
response_found=result.response_lookup_succeeded,
objection_status=objection_status,
first_contact_date=first_contact_date,
objection_date=objection_date,
main_contact_platform=main_contact_platform,
ad_source=ad_source,
lead_quality=lead_quality,
)
payload = result.to_dict()
payload.update({
"customer_name": customer_name,
"objection_status": objection_status,
"first_contact_date": first_contact_date,
"objection_date": objection_date,
"main_contact_platform": main_contact_platform,
"ad_source": ad_source,
"lead_quality": lead_quality,
})
service_objection_exists = _service_has_objection(
service=service,
customer_group=internal_group,
destination=destination,
objection_type=result.objection_type,
cluster=result.cluster,
)
if service_objection_exists is False:
payload["service_objection_exists"] = False
payload["service_objection_message"] = "This objection does not exist for this visa service"
payload["response_lookup_succeeded"] = False
elif service_objection_exists is True:
payload["service_objection_exists"] = True
return JSONResponse(payload)
class CorrectionRequest(BaseModel):
quote: str
original_type: str
original_cluster: str
corrected_type: str
corrected_cluster: str
customer_group: str = ""
destination: str = ""
service: str = ""
@app.post("/api/correction")
async def api_correction(body: CorrectionRequest, request: Request):
user = auth.get_current_user(request)
if user is None:
raise HTTPException(status_code=401, detail="Not authenticated")
from core.corrections import _normalize
quote_norm = _normalize(body.quote)
db.save_correction(
user_email=user["email"],
user_name=user["name"],
quote=body.quote,
quote_normalized=quote_norm,
original_type=body.original_type,
original_cluster=body.original_cluster,
corrected_type=body.corrected_type,
corrected_cluster=body.corrected_cluster,
customer_group=body.customer_group,
destination=body.destination,
service=body.service,
)
db.log_activity(
user["email"], user["name"], "correction",
details=f"{body.original_type}/{body.original_cluster} β {body.corrected_type}/{body.corrected_cluster}",
page="consultants",
)
return JSONResponse({"ok": True})
# ---------------------------------------------------------------------------
# ββ Browse ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ---------------------------------------------------------------------------
def _responses_as_records() -> list[dict]:
"""Load Browse responses from DB and return as JSON-safe records."""
df = _load_responses()
records = []
for idx, row in df.iterrows():
row_id = row.get("id", idx)
try:
row_id = int(row_id)
except Exception:
row_id = int(idx)
records.append({
"row_id": row_id,
"service": row.get("service", ""),
"customer_group": row.get("customer_group", ""),
"destination": row.get("destination", ""),
"objection_type": row.get("objection_type", ""),
"cluster": row.get("cluster", ""),
"severity": row.get("severity", ""),
"video_id": row.get("video_id", ""),
"perfect_response": row.get("perfect_response", ""),
"perfect_response_km": row.get("perfect_response_km", ""),
"solution": row.get("solution", ""),
"solution_km": row.get("solution_km", ""),
"follow_up_question": row.get("follow_up_question", ""),
"follow_up_question_km": row.get("follow_up_question_km", ""),
})
return records
@app.get("/browse", response_class=HTMLResponse)
async def browse_page(
request: Request,
user: dict = Depends(auth.require_role("browse")),
):
can_edit = auth.can_edit_browse_response(user)
records = _responses_as_records()
return _render(
request,
"browse.html",
{
"user": user,
"services_json": json.dumps(_SERVICES_MAP),
"rows_json": json.dumps(records),
"can_edit": can_edit,
"group_labels": GROUP_LABELS,
"response_count": len(records),
},
)
class BrowseEditRequest(BaseModel):
row_id: Optional[int] = None
service: str = ""
customer_group: str = ""
destination: str = ""
cluster: str
objection_type: str = ""
perfect_response: str = ""
perfect_response_km: str = ""
solution: str = ""
solution_km: str = ""
follow_up_question: str = ""
follow_up_question_km: str = ""
severity: str = ""
video_id: str = ""
class BrowseDeleteRequest(BaseModel):
scope: str
value: str
class BrowseDeleteRowRequest(BaseModel):
row_id: int
@app.post("/browse/edit")
async def browse_edit(
body: BrowseEditRequest,
request: Request,
user: dict = Depends(auth.require_role("admin_panel")),
):
"""Write edited fields to the database-backed Browse response table."""
customer_group = body.customer_group
destination = body.destination
cluster = body.cluster
global _TYPE_CLUSTER_MAP
try:
try:
idx = db.update_browse_response(
body.row_id,
{
"service": body.service,
"customer_group": body.customer_group,
"destination": body.destination,
"cluster": body.cluster,
"objection_type": body.objection_type,
"perfect_response": body.perfect_response,
"perfect_response_km": body.perfect_response_km,
"solution": body.solution,
"solution_km": body.solution_km,
"follow_up_question": body.follow_up_question,
"follow_up_question_km": body.follow_up_question_km,
"severity": body.severity,
"video_id": body.video_id,
},
updated_by=user.get("email", ""),
)
except KeyError:
raise HTTPException(status_code=404, detail="Row not found in database")
# Refresh the in-memory cache so next /browse picks up the change
_TYPE_CLUSTER_MAP = _load_type_cluster_map()
# Reload predictor's response dataframe if it's been initialised
if _PREDICTOR is not None:
_PREDICTOR.reload_responses()
db.log_activity(
user["email"], user["name"], "edit_response",
details=f"cluster={cluster} cg={customer_group} dest={destination}",
page="browse",
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to save edit: {e}")
return JSONResponse({"ok": True, "row_id": int(idx)})
@app.post("/browse/delete")
async def browse_delete(
body: BrowseDeleteRequest,
request: Request,
user: dict = Depends(auth.require_role("admin_panel")),
):
"""Delete a service, objection type, or cluster from the Browse matrix."""
global _SERVICES_MAP, _TYPE_CLUSTER_MAP
try:
deleted = db.delete_browse_matrix_item(
body.scope,
body.value,
deleted_by=user.get("email", ""),
)
_SERVICES_MAP = _load_active_services()
_TYPE_CLUSTER_MAP = _load_type_cluster_map()
if _PREDICTOR is not None:
_PREDICTOR.reload_responses()
db.log_activity(
user["email"], user["name"], "delete_browse_matrix_item",
details=f"{body.scope}={body.value}; rows={deleted}",
page="browse",
)
return JSONResponse({"ok": True, "deleted": deleted})
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to delete Browse item: {e}")
@app.post("/browse/delete-row")
async def browse_delete_row(
body: BrowseDeleteRowRequest,
request: Request,
user: dict = Depends(auth.require_role("admin_panel")),
):
"""Delete one service/objection/cluster row from the Browse matrix."""
global _SERVICES_MAP, _TYPE_CLUSTER_MAP
try:
deleted_row = db.delete_browse_response_row(
body.row_id,
deleted_by=user.get("email", ""),
)
_SERVICES_MAP = _load_active_services()
_TYPE_CLUSTER_MAP = _load_type_cluster_map()
if _PREDICTOR is not None:
_PREDICTOR.reload_responses()
db.log_activity(
user["email"], user["name"], "delete_browse_response",
details=(
f"id={body.row_id}; service={deleted_row.get('service', '')}; "
f"type={deleted_row.get('objection_type', '')}; cluster={deleted_row.get('cluster', '')}"
),
page="browse",
)
return JSONResponse({"ok": True, "deleted": 1, "row_id": body.row_id})
except KeyError:
raise HTTPException(status_code=404, detail="Row not found in database")
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to delete Browse row: {e}")
@app.get("/browse/export.csv")
async def browse_export_csv(user: dict = Depends(auth.require_role("browse"))):
"""Export database-backed Browse responses as a CSV download."""
csv_text = db.browse_responses_csv()
filename = f"browse_responses_{datetime.now(APP_TZ).strftime('%Y%m%d_%H%M%S')}.csv"
return StreamingResponse(
io.StringIO(csv_text),
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
)
@app.get("/analytics", response_class=HTMLResponse)
async def analytics_page(
request: Request,
user: dict = Depends(auth.require_role("analytics")),
):
return _render(
request,
"analytics.html",
{
"user": user,
"is_admin": user.get("role") == "admin",
},
)
@app.get("/api/analytics-data")
async def api_analytics_data(
request: Request,
date_from: str = "",
date_to: str = "",
from_date: str = "", # alias β app.js uses both names
to_date: str = "", # alias
):
user = auth.get_current_user(request)
if user is None:
raise HTTPException(status_code=401, detail="Not authenticated")
rows = db.get_interactions(limit=100_000)
df = pd.DataFrame(rows) if rows else pd.DataFrame()
if df.empty:
return JSONResponse({
"rows": [],
"total": 0,
"unique_users": 0,
"active_staff": 0,
"response_rate": 0,
"avg_confidence": 0,
"high_severity_count": 0,
"most_common_type": "",
"most_common_service": "",
"most_common_destination": "",
"metric_deltas": {},
"type_counts": {},
"cluster_counts": {},
"service_counts": {},
"destination_counts": {},
"consultant_usage": [],
"cluster_deltas": {},
"weekly": {},
"is_admin": user.get("role") == "admin",
})
df["timestamp"] = pd.to_datetime(df["timestamp"], errors="coerce")
df_all = df.copy()
# Date filtering β accept both date_from/date_to and from_date/to_date
_from = date_from or from_date
_to = date_to or to_date
from_day = None
to_day = None
if _from:
try:
from_day = date.fromisoformat(_from)
df = df[df["timestamp"].dt.date >= from_day]
except ValueError:
pass
if _to:
try:
to_day = date.fromisoformat(_to)
df = df[df["timestamp"].dt.date <= to_day]
except ValueError:
pass
# Stats
def _stats(frame: pd.DataFrame) -> dict:
count = len(frame)
users = int(frame["user_email"].nunique()) if "user_email" in frame else 0
rate = (
round(frame["response_found"].sum() / count * 100, 1)
if count > 0 and "response_found" in frame else 0
)
confidence_value = 0
if count > 0 and "stage1_confidence" in frame:
confidence = pd.to_numeric(frame["stage1_confidence"], errors="coerce").dropna()
if not confidence.empty:
confidence_value = round(float(confidence.mean()), 2)
return {
"total": count,
"unique_users": users,
"response_rate": rate,
"avg_confidence": confidence_value,
}
def _delta(current: float, previous: float) -> float:
if previous == 0:
return 0 if current == 0 else 100
return round((current - previous) / previous * 100, 1)
stats = _stats(df)
total = stats["total"]
unique_users = stats["unique_users"]
response_rate = stats["response_rate"]
avg_confidence = stats["avg_confidence"]
previous_df = pd.DataFrame()
if from_day and to_day:
period_days = max((to_day - from_day).days + 1, 1)
prev_to = from_day - timedelta(days=1)
prev_from = prev_to - timedelta(days=period_days - 1)
previous_df = df_all[
(df_all["timestamp"].dt.date >= prev_from)
& (df_all["timestamp"].dt.date <= prev_to)
]
previous_stats = _stats(previous_df) if not previous_df.empty else {
"total": 0,
"unique_users": 0,
"response_rate": 0,
"avg_confidence": 0,
}
metric_deltas = {
"total": _delta(total, previous_stats["total"]),
"response_rate": _delta(response_rate, previous_stats["response_rate"]),
"avg_confidence": _delta(avg_confidence, previous_stats["avg_confidence"]),
"active_staff": _delta(unique_users, previous_stats["unique_users"]),
}
def _top_label(counts: dict) -> str:
return str(next(iter(counts.keys()), ""))
# Type distribution
type_counts = (
df["objection_type"].value_counts().to_dict()
if "objection_type" in df else {}
)
# Top 10 clusters
cluster_counts = {}
if "cluster" in df:
cluster_counts = df["cluster"].value_counts().head(10).to_dict()
previous_cluster_counts = (
previous_df["cluster"].value_counts().to_dict()
if not previous_df.empty and "cluster" in previous_df else {}
)
cluster_deltas = {
str(cluster): _delta(float(count), float(previous_cluster_counts.get(cluster, 0)))
for cluster, count in cluster_counts.items()
}
service_counts = {}
if "service" in df:
service_counts = (
df["service"]
.fillna("")
.astype(str)
.str.strip()
.replace("", pd.NA)
.dropna()
.value_counts()
.head(10)
.to_dict()
)
destination_counts = {}
if "destination" in df:
destination_counts = (
df["destination"]
.fillna("")
.astype(str)
.str.strip()
.replace("", pd.NA)
.dropna()
.value_counts()
.head(10)
.to_dict()
)
high_severity_count = 0
if "severity" in df:
high_severity_count = int(
df["severity"].fillna("").astype(str).str.strip().str.lower().eq("high").sum()
)
consultant_usage = []
if "user_name" in df:
user_group = df.copy()
user_group["user_name"] = user_group["user_name"].fillna("").astype(str).str.strip().replace("", "Unknown")
grouped = user_group.groupby("user_name")
for name, frame in grouped:
consultant_usage.append({
"name": str(name),
"count": int(len(frame)),
"high": int(frame["severity"].fillna("").astype(str).str.strip().str.lower().eq("high").sum()) if "severity" in frame else 0,
"response_rate": round(float(frame["response_found"].sum()) / len(frame) * 100, 1) if len(frame) and "response_found" in frame else 0,
})
consultant_usage = sorted(consultant_usage, key=lambda item: item["count"], reverse=True)[:10]
# Weekly volume
weekly_counts: dict = {}
if not df.empty and "timestamp" in df:
df["week"] = df["timestamp"].dt.to_period("W").dt.start_time.dt.strftime("%Y-%m-%d")
weekly_counts = df.groupby("week").size().to_dict()
# Row records for the table (most recent 500)
row_records = []
for _, r in df.sort_values("timestamp", ascending=False).head(500).iterrows():
row_records.append({
"id": int(r.get("id", 0)),
"timestamp": str(r.get("timestamp", ""))[:16],
"user_name": r.get("user_name", ""),
"customer_name": r.get("customer_name", ""),
"quote": r.get("quote", ""),
"objection_type": r.get("objection_type", ""),
"cluster": r.get("cluster", ""),
"severity": r.get("severity", ""),
"confidence": r.get("stage1_confidence", ""),
"customer_group": r.get("customer_group", ""),
"destination": r.get("destination", ""),
"service": r.get("service", ""),
"objection_status": r.get("objection_status", ""),
"first_contact_date": r.get("first_contact_date", ""),
"objection_date": r.get("objection_date", ""),
"main_contact_platform": r.get("main_contact_platform", ""),
"ad_source": r.get("ad_source", ""),
"lead_quality": r.get("lead_quality", ""),
})
return JSONResponse({
"rows": row_records,
"total": total,
"unique_users": unique_users,
"active_staff": unique_users,
"response_rate": response_rate,
"avg_confidence": avg_confidence,
"high_severity_count": high_severity_count,
"most_common_type": _top_label(type_counts),
"most_common_service": _top_label(service_counts),
"most_common_destination": _top_label(destination_counts),
"metric_deltas": metric_deltas,
"type_counts": type_counts,
"cluster_counts": cluster_counts,
"service_counts": service_counts,
"destination_counts": destination_counts,
"consultant_usage": consultant_usage,
"cluster_deltas": cluster_deltas,
"weekly": weekly_counts,
"is_admin": user.get("role") == "admin",
})
class AnalyticsDeleteRequest(BaseModel):
# id-based delete: list of int IDs
ids: Optional[list] = None
# date-range delete: ISO date strings
date_from: str = ""
date_to: str = ""
class AnalyticsStatusRequest(BaseModel):
id: int
objection_status: str
class AnalyticsLeadQualityRequest(BaseModel):
id: int
lead_quality: str
class AnalyticsInteractionEditRequest(BaseModel):
id: int
customer_name: str = ""
quote: str = ""
objection_status: str = "Unsolved"
first_contact_date: str = ""
objection_date: str = ""
main_contact_platform: str = ""
lead_quality: str = ""
service: str = ""
ad_source: str = ""
objection_type: str = ""
cluster: str = ""
severity: str = ""
@app.post("/analytics/status")
async def analytics_status_update(
body: AnalyticsStatusRequest,
request: Request,
user: dict = Depends(auth.require_role("analytics")),
):
status = (body.objection_status or "").strip()
if status not in _OBJECTION_STATUSES:
raise HTTPException(status_code=400, detail="Invalid objection status.")
if body.id <= 0:
raise HTTPException(status_code=400, detail="Invalid interaction ID.")
updated = db.update_interaction_status(body.id, status)
if not updated:
raise HTTPException(status_code=404, detail="Interaction not found.")
db.log_activity(
user["email"], user["name"], "update_objection_status",
details=f"id={body.id} status={status}", page="analytics",
)
return JSONResponse({"ok": True, "id": body.id, "objection_status": status})
@app.post("/analytics/lead-quality")
async def analytics_lead_quality_update(
body: AnalyticsLeadQualityRequest,
request: Request,
user: dict = Depends(auth.require_role("analytics")),
):
lead_quality = (body.lead_quality or "").strip()
if lead_quality not in _LEAD_QUALITIES:
raise HTTPException(status_code=400, detail="Invalid lead quality.")
if body.id <= 0:
raise HTTPException(status_code=400, detail="Invalid interaction ID.")
updated = db.update_interaction_lead_quality(body.id, lead_quality)
if not updated:
raise HTTPException(status_code=404, detail="Interaction not found.")
db.log_activity(
user["email"], user["name"], "update_lead_quality",
details=f"id={body.id} lead_quality={lead_quality}", page="analytics",
)
return JSONResponse({"ok": True, "id": body.id, "lead_quality": lead_quality})
@app.post("/analytics/interaction/edit")
async def analytics_interaction_edit(
body: AnalyticsInteractionEditRequest,
request: Request,
user: dict = Depends(auth.require_role("analytics")),
):
if body.id <= 0:
raise HTTPException(status_code=400, detail="Invalid interaction ID.")
objection_status = _clean_tracking_choice(
body.objection_status,
_OBJECTION_STATUSES,
"objection status",
default="Unsolved",
)
first_contact_date = _clean_tracking_date(body.first_contact_date, "first contact date")
objection_date = _clean_tracking_date(body.objection_date, "objection date")
main_contact_platform = _clean_tracking_choice(
body.main_contact_platform,
_CONTACT_PLATFORMS,
"main contact platform",
)
lead_quality = _clean_tracking_choice(body.lead_quality, _LEAD_QUALITIES, "lead quality")
severity = (body.severity or "").strip()
if severity and severity not in {"Low", "Medium", "High"}:
raise HTTPException(status_code=400, detail="Invalid severity.")
service = (body.service or "").strip()
fields = {
"customer_name": (body.customer_name or "").strip()[:120],
"quote": (body.quote or "").strip(),
"objection_status": objection_status,
"first_contact_date": first_contact_date,
"objection_date": objection_date,
"main_contact_platform": main_contact_platform,
"lead_quality": lead_quality,
"service": service,
"destination": _extract_destination(service),
"ad_source": (body.ad_source or "").strip()[:120],
"objection_type": (body.objection_type or "").strip(),
"cluster": (body.cluster or "").strip(),
"severity": severity,
}
if not fields["quote"]:
raise HTTPException(status_code=400, detail="Exact quote is required.")
updated = db.update_interaction_fields(body.id, fields)
if not updated:
raise HTTPException(status_code=404, detail="Interaction not found.")
db.log_activity(
user["email"], user["name"], "edit_interaction",
details=f"id={body.id}", page="analytics",
)
return JSONResponse({"ok": True, "id": body.id, **fields})
@app.post("/analytics/delete")
async def analytics_delete(
body: AnalyticsDeleteRequest,
request: Request,
user: dict = Depends(auth.require_role("admin_panel")),
):
if body.date_from and body.date_to:
n = db.delete_interactions_by_date_range(body.date_from, body.date_to)
db.log_activity(
user["email"], user["name"], "delete_interactions",
details=f"range={body.date_from}..{body.date_to} n={n}", page="analytics",
)
return JSONResponse({"deleted": n})
elif body.ids:
id_list = [int(i) for i in body.ids if isinstance(i, (int, str)) and str(i).isdigit() or isinstance(i, int)]
if not id_list:
raise HTTPException(status_code=400, detail="No valid IDs provided")
n = db.delete_interactions_by_ids(id_list)
db.log_activity(
user["email"], user["name"], "delete_interactions",
details=f"ids={id_list[:10]} n={n}", page="analytics",
)
return JSONResponse({"deleted": n})
else:
raise HTTPException(status_code=400, detail="Provide either ids or date_from+date_to")
# ---------------------------------------------------------------------------
# ββ Admin βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ---------------------------------------------------------------------------
@app.get("/admin", response_class=HTMLResponse)
async def admin_page(
request: Request,
user: dict = Depends(auth.require_role("admin_panel")),
):
users = db.get_all_users()
corrections = db.get_corrections(limit=500)
for c in corrections:
c.setdefault("created_at", c.get("timestamp", ""))
activity = db.get_activity_log(limit=200)
return _render(
request,
"admin.html",
{"user": user, "users": users,
"corrections": corrections, "activity": activity},
)
@app.post("/admin/users/add")
async def admin_users_add(
request: Request,
user: dict = Depends(auth.require_role("admin_panel")),
email: str = Form(...),
name: str = Form(...),
role: str = Form(...),
):
ok = db.add_user(email.strip().lower(), name.strip(), role)
if ok:
db.log_activity(user["email"], user["name"], "add_user",
details=f"added {email} role={role}", page="admin")
return RedirectResponse(url="/admin?tab=users&success=User+added.", status_code=303)
return RedirectResponse(url="/admin?tab=users&error=Email+already+exists.", status_code=303)
@app.post("/admin/users/update")
async def admin_users_update(
request: Request,
user: dict = Depends(auth.require_role("admin_panel")),
email: str = Form(...),
name: str = Form(""),
role: str = Form(""),
active: str = Form("1"),
password: str = Form(""),
):
if name:
db.update_user_name(email, name.strip())
if role:
db.update_user_role(email, role)
db.update_user_active(email, int(active))
if password:
auth.set_user_password(email, password)
db.log_activity(user["email"], user["name"], "edit_user",
details=f"updated {email}", page="admin")
return RedirectResponse(url="/admin?tab=users&success=User+updated.", status_code=303)
@app.post("/admin/corrections/delete")
async def admin_corrections_delete(
request: Request,
user: dict = Depends(auth.require_role("admin_panel")),
correction_id: int = Form(...),
):
db.delete_correction(correction_id)
db.log_activity(user["email"], user["name"], "delete_correction",
details=f"correction_id={correction_id}", page="admin")
return RedirectResponse(url="/admin?tab=corrections&success=Correction+deleted.", status_code=303)
@app.get("/admin/export/users")
async def admin_export_users(
request: Request,
user: dict = Depends(auth.require_role("admin_panel")),
):
users = db.get_all_users()
output = io.StringIO()
writer = csv.DictWriter(
output,
fieldnames=["id", "email", "name", "role", "active", "created_at", "last_login"],
extrasaction="ignore",
)
writer.writeheader()
writer.writerows(users)
output.seek(0)
return StreamingResponse(
io.BytesIO(output.getvalue().encode("utf-8")),
media_type="text/csv",
headers={"Content-Disposition": "attachment; filename=users.csv"},
)
"""
Explorer Consultant Bot β FastAPI entry point.
Run locally:
cd FastAPI
uvicorn main:app --reload --port 8000
All routes:
GET / β redirect to /home or /login
GET /login β login form
POST /login β validate, set cookie, redirect
POST /setup-password β first-time password creation
GET /logout β clear session + cookie
GET /home β authenticated home
GET /consultants β objection analyzer page
GET /api/services β JSON: services for a given group
GET /api/type-cluster-map β JSON: objection type β cluster list
POST /api/predict β JSON: run DistilBERT prediction
POST /api/correction β save staff correction
GET /browse β response browser
POST /browse/edit β save response edit to database
POST /browse/delete β delete service/type/cluster from Browse
GET /browse/export.csv β CSV download of Browse responses
GET /analytics β analytics dashboard
GET /api/analytics-data β JSON: interactions + stats for charts
POST /analytics/delete β admin: delete interactions
GET /admin β admin panel (3 tabs)
POST /admin/users/add β add new user
POST /admin/users/update β update user role / name / status / password
POST /admin/corrections/delete β delete a correction row
GET /admin/export/users β CSV download of all users
"""
from __future__ import annotations
import csv
import io
import json
import os
import re
import sys
import threading
from collections import Counter
from contextlib import asynccontextmanager
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from typing import Optional
import pandas as pd
from fastapi import Depends, FastAPI, Form, HTTPException, Request, Response
from fastapi.responses import (
HTMLResponse,
JSONResponse,
RedirectResponse,
StreamingResponse,
)
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from core import auth
from core import database as db
# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
BASE_DIR = Path(__file__).parent
REPO_DIR = BASE_DIR.parent
RESPONSES_CSV = REPO_DIR / "data" / "responses.csv"
SERVICES_CSV = REPO_DIR / "Webapp" / "Services.csv"
# ---------------------------------------------------------------------------
# Group display labels
# ---------------------------------------------------------------------------
GROUP_DISPLAY = {"VISA - KH": "VISA - KHMER", "VISA-FOR": "VISA - FOREIGNER"}
GROUP_INTERNAL = {v: k for k, v in GROUP_DISPLAY.items()}
GROUP_LABELS = list(GROUP_DISPLAY.values()) # ["VISA - KHMER", "VISA - FOREIGNER"]
APP_TZ = timezone(timedelta(hours=7))
# ---------------------------------------------------------------------------
# Helpers: load data from CSV files (called at startup + after edits)
# ---------------------------------------------------------------------------
def _load_services() -> dict[str, list[str]]:
"""Return {internal_group: [service_code, ...]} from Services.csv."""
services: dict[str, list[str]] = {}
try:
with open(SERVICES_CSV, encoding="utf-8") as f:
for line in f:
line = line.strip().rstrip(",")
if not line:
continue
parts = line.split(",", 1)
if len(parts) == 2:
group = parts[0].strip()
code = parts[1].strip()
if code: