Spaces:
Sleeping
Sleeping
Download routes/copilot.py from brocode12/bell-backend: direct link, hf CLI and curl.
- Browser
- Download file 4.42 kB
-
https://huggingface.co/spaces/brocode12/bell-backend/resolve/main/routes/copilot.py
- Command line
-
hf download hf://spaces/brocode12/bell-backend/routes/copilot.py
-
curl -L -o copilot.py https://huggingface.co/spaces/brocode12/bell-backend/resolve/main/routes/copilot.py
4.42 kB
| """Operations Copilot analytics endpoint. | |
| GET /api/copilot?admin_key= — scorecards + per-call rows + reservation count | |
| GET /api/call-summary — public; latest call_log for a table (post-call card) | |
| """ | |
| from __future__ import annotations | |
| import time | |
| from collections import Counter | |
| from datetime import datetime, timezone | |
| from typing import Optional | |
| from fastapi import APIRouter, Query | |
| import config | |
| from store import get_store | |
| router = APIRouter(prefix="/api", tags=["copilot"]) | |
| _cache: dict = {"data": None, "ts": 0} | |
| CACHE_TTL = 60 # seconds | |
| def _build_analytics() -> dict: | |
| store = get_store() | |
| call_logs = store.list_call_logs(limit=200) | |
| orders = store.list_orders() | |
| total_calls = len(call_logs) | |
| successful_orders = sum(1 for o in orders if o.get("status") not in ("", None)) | |
| order_totals = [o.get("total_amount", 0) or 0 for o in orders if o.get("total_amount")] | |
| avg_order_value = round(sum(order_totals) / len(order_totals), 2) if order_totals else 0 | |
| total_revenue = sum(order_totals) | |
| # Orders placed today | |
| today = datetime.now(timezone.utc).date().isoformat() | |
| orders_today = sum(1 for o in orders if (o.get("created_at") or "").startswith(today)) | |
| # Extraction-derived metrics | |
| upsell_count = sum(1 for c in call_logs if c.get("upsell_accepted") is True) | |
| escalation_count = sum(1 for c in call_logs if c.get("human_escalation") is True) | |
| calls_with_extractions = sum(1 for c in call_logs if c.get("extractions") is not None) | |
| sentiment_counts: Counter = Counter() | |
| language_counts: Counter = Counter() | |
| for c in call_logs: | |
| if c.get("sentiment"): | |
| sentiment_counts[c["sentiment"].lower()] += 1 | |
| if c.get("customer_language"): | |
| language_counts[c["customer_language"].lower()] += 1 | |
| top_language = language_counts.most_common(1)[0][0].title() if language_counts else "—" | |
| extraction_coverage = round(calls_with_extractions / total_calls * 100, 1) if total_calls else 0 | |
| # Most recent call for system health | |
| last_webhook_ts = call_logs[0].get("created_at") if call_logs else None | |
| pending_reservations = len(store.list_reservations(status="pending")) | |
| return { | |
| "scorecards": { | |
| "total_calls": total_calls, | |
| "successful_orders": successful_orders, | |
| "avg_order_value": avg_order_value, | |
| "total_revenue": total_revenue, | |
| "orders_today": orders_today, | |
| "upsell_count": upsell_count, | |
| "upsell_rate": round(upsell_count / total_calls * 100, 1) if total_calls else 0, | |
| "escalation_count": escalation_count, | |
| "escalation_rate": round(escalation_count / total_calls * 100, 1) if total_calls else 0, | |
| "top_language": top_language, | |
| "sentiment_counts": dict(sentiment_counts), | |
| "language_counts": dict(language_counts), | |
| }, | |
| "system_health": { | |
| "extraction_coverage_pct": extraction_coverage, | |
| "calls_with_extractions": calls_with_extractions, | |
| "last_webhook_ts": last_webhook_ts, | |
| "bolna_agent_id": config.BOLNA_AGENT_ID or None, | |
| "webhook_configured": bool(config.BOLNA_AGENT_ID), | |
| }, | |
| "pending_reservations": pending_reservations, | |
| "calls": call_logs, | |
| } | |
| async def copilot(admin_key: str = Query(default="")): | |
| if config.ADMIN_KEY and admin_key != config.ADMIN_KEY: | |
| return {"success": False, "message": "Invalid admin key."} | |
| now = time.time() | |
| if _cache["data"] is None or now - _cache["ts"] > CACHE_TTL: | |
| _cache["data"] = _build_analytics() | |
| _cache["ts"] = now | |
| return {"success": True, **_cache["data"]} | |
| async def call_summary( | |
| table_number: str = Query(...), | |
| outlet_location: str = Query(default=config.DEFAULT_OUTLET), | |
| ): | |
| log = get_store().latest_call_log(table_number, outlet_location) | |
| if not log: | |
| return {"success": False, "found": False} | |
| return { | |
| "success": True, | |
| "found": True, | |
| "summary": log.get("summary"), | |
| "sentiment": log.get("sentiment"), | |
| "customer_language": log.get("customer_language"), | |
| "special_requests": log.get("special_requests"), | |
| "upsell_accepted": log.get("upsell_accepted"), | |
| "confidence_score": log.get("confidence_score"), | |
| } | |