Spaces:
Sleeping
Sleeping
Download routes/webhooks.py from brocode12/bell-backend: direct link, hf CLI and curl.
- Browser
- Download file 17 kB
-
https://huggingface.co/spaces/brocode12/bell-backend/resolve/main/routes/webhooks.py
- Command line
-
hf download hf://spaces/brocode12/bell-backend/routes/webhooks.py
-
curl -L -o webhooks.py https://huggingface.co/spaces/brocode12/bell-backend/resolve/main/routes/webhooks.py
17 kB
| """Bolna post-call webhook → call_logs audit trail. | |
| Bolna's extraction LLM is not activated for this agent (extraction task | |
| missing from agent pipeline). We implement self-extraction directly from | |
| the transcript using keyword/pattern analysis — no external API needed. | |
| After initial save, we also spawn a background task to poll Bolna's | |
| /executions/{id} in case Bolna does eventually populate extracted_data. | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import json | |
| import re | |
| import sys | |
| from typing import Any | |
| import httpx | |
| from fastapi import APIRouter, BackgroundTasks, Request | |
| import config | |
| from store import get_store | |
| router = APIRouter(prefix="/api/webhooks", tags=["webhooks"]) | |
| _last_payload: dict = {} | |
| BOLNA_EXEC_URL = "https://api.bolna.ai/executions/{execution_id}" | |
| POLL_INTERVAL = 15 | |
| POLL_MAX_ATTEMPTS = 4 | |
| # --------------------------------------------------------------------------- | |
| # Transcript parsing | |
| # --------------------------------------------------------------------------- | |
| def _parse_transcript(payload: dict): | |
| raw = ( | |
| payload.get("transcript") | |
| or payload.get("transcription") | |
| or (payload.get("telephony_data") or {}).get("transcript") | |
| or (payload.get("data") or {}).get("transcript") | |
| ) | |
| if raw is None: | |
| return None | |
| if isinstance(raw, list): | |
| return raw | |
| if isinstance(raw, str): | |
| turns = [] | |
| for line in raw.splitlines(): | |
| line = line.strip() | |
| if not line: | |
| continue | |
| role, _, text = line.partition(":") | |
| if text and role.lower() in ("assistant", "user", "agent", "customer", "bell", "human"): | |
| turns.append({"role": role.strip().lower(), "text": text.strip()}) | |
| else: | |
| turns.append({"role": "unknown", "text": line}) | |
| return turns | |
| return [{"role": "unknown", "text": str(raw)}] | |
| def _transcript_text(transcript) -> str: | |
| """Flatten transcript to plain text for analysis.""" | |
| if not transcript: | |
| return "" | |
| if isinstance(transcript, str): | |
| return transcript | |
| if isinstance(transcript, list): | |
| return " ".join(t.get("text", "") for t in transcript if isinstance(t, dict)) | |
| return str(transcript) | |
| # --------------------------------------------------------------------------- | |
| # Self-extraction: rule-based analytics from transcript text | |
| # --------------------------------------------------------------------------- | |
| _HINDI_WORDS = re.compile(r"[ऀ-ॿ]") | |
| _KANNADA_WORDS = re.compile(r"[ಀ-]") | |
| _TAMIL_WORDS = re.compile(r"[-]") | |
| _TELUGU_WORDS = re.compile(r"[ఀ-౿]") | |
| _HINDI_ROMAN = re.compile( | |
| r"\b(haan|nahi|kya|aap|kaise|mujhe|chahiye|theek|shukriya|dhanyavaad|bilkul|" | |
| r"bataiye|bata|karo|kijiye|ek|do|teen|char|paanch|rupe|rupay|yaar|bhai|didi|" | |
| r"accha|achi|thoda|bahut|kuch|matlab|matlab|dekho|suno|boliye)\b", | |
| re.IGNORECASE, | |
| ) | |
| _ORDER_PLACED = re.compile( | |
| r"\b(order(ed|ing)?|placed|confirm|yes[,.]?\s+please|i'?ll\s+(have|take|get)|" | |
| r"can\s+i\s+(have|get|order)|add\s+to\s+(my\s+)?order|done|great(\s+choice)?)\b", | |
| re.IGNORECASE, | |
| ) | |
| _UPSELL_TRIGGER = re.compile( | |
| r"\b(also\s+(try|recommend|suggest)|would\s+you\s+like|how\s+about\s+(some|a)|" | |
| r"pair\s+(well|nicely)|complement|starter|dessert|appetizer|mocktail|beer|" | |
| r"craft\s+beer|beverage|drink)\b", | |
| re.IGNORECASE, | |
| ) | |
| _UPSELL_ACCEPTED = re.compile( | |
| r"\b(yes[,.]?\s*(please|sure|okay|ok|sounds?\s+good|add\s+that|great)|" | |
| r"sure[,.]?\s*(why\s+not|add)|i'?ll\s+take\s+that|add\s+it)\b", | |
| re.IGNORECASE, | |
| ) | |
| _ESCALATION = re.compile( | |
| r"\b(speak\s+(to|with)\s+a?\s*(human|manager|staff|person|someone)|" | |
| r"call\s+(me\s+back|back)|not\s+happy|complain|complaint|wrong\s+order|" | |
| r"error|mistake|problem|issue|help\s+me)\b", | |
| re.IGNORECASE, | |
| ) | |
| _POSITIVE = re.compile( | |
| r"\b(thank|thanks|great|perfect|wonderful|amazing|excellent|love\s+it|" | |
| r"awesome|fantastic|happy|pleased|satisfied|enjoy|good)\b", | |
| re.IGNORECASE, | |
| ) | |
| _NEGATIVE = re.compile( | |
| r"\b(not\s+(good|happy|satisfied|working)|bad|terrible|awful|wrong|" | |
| r"disappointed|issue|problem|error|cancel|refund)\b", | |
| re.IGNORECASE, | |
| ) | |
| def _detect_language(text: str) -> str: | |
| if _KANNADA_WORDS.search(text): | |
| return "Kannada" | |
| if _TAMIL_WORDS.search(text): | |
| return "Tamil" | |
| if _TELUGU_WORDS.search(text): | |
| return "Telugu" | |
| if _HINDI_WORDS.search(text) or len(_HINDI_ROMAN.findall(text)) >= 2: | |
| return "Hindi" | |
| return "English" | |
| def _turns_from_text(text: str) -> tuple[list[str], list[str]]: | |
| """Parse 'role: text\\n' transcript into (agent_lines, user_lines).""" | |
| agent_lines, user_lines = [], [] | |
| for line in text.splitlines(): | |
| line = line.strip() | |
| if not line: | |
| continue | |
| role, _, msg = line.partition(":") | |
| msg = msg.strip() | |
| if not msg: | |
| continue | |
| r = role.strip().lower() | |
| if r in ("assistant", "agent", "bell"): | |
| agent_lines.append(msg) | |
| elif r in ("user", "customer", "human"): | |
| user_lines.append(msg) | |
| return agent_lines, user_lines | |
| def _extract_from_transcript(transcript, payload: dict) -> dict: | |
| """Derive analytics fields from the transcript when Bolna doesn't provide them.""" | |
| text = _transcript_text(transcript) | |
| if not text or len(text) < 30: | |
| return {} | |
| result: dict = {} | |
| confidences: list[float] = [] | |
| # Language | |
| result["customer_language"] = _detect_language(text) | |
| confidences.append(0.85) | |
| # Sentiment | |
| pos = len(_POSITIVE.findall(text)) | |
| neg = len(_NEGATIVE.findall(text)) | |
| if pos > neg + 1: | |
| result["sentiment"] = "Positive" | |
| confidences.append(0.75) | |
| elif neg > pos: | |
| result["sentiment"] = "Negative" | |
| confidences.append(0.70) | |
| else: | |
| result["sentiment"] = "Neutral" | |
| confidences.append(0.65) | |
| # Upsell | |
| if _UPSELL_TRIGGER.search(text) and _UPSELL_ACCEPTED.search(text): | |
| result["upsell_accepted"] = True | |
| confidences.append(0.70) | |
| elif _UPSELL_TRIGGER.search(text): | |
| result["upsell_accepted"] = False | |
| confidences.append(0.60) | |
| # Escalation | |
| if _ESCALATION.search(text): | |
| result["human_escalation"] = True | |
| confidences.append(0.80) | |
| # Summary — parse from "role: text" lines or structured turns | |
| if isinstance(transcript, list): | |
| agent_lines = [t.get("text", "") for t in transcript if isinstance(t, dict) | |
| and t.get("role") in ("assistant", "agent", "bell")] | |
| user_lines = [t.get("text", "") for t in transcript if isinstance(t, dict) | |
| and t.get("role") in ("user", "customer", "human")] | |
| else: | |
| agent_lines, user_lines = _turns_from_text(text) | |
| summary_parts = [] | |
| if agent_lines: | |
| summary_parts.append(f"Bell: {agent_lines[0][:120]}") | |
| if user_lines: | |
| summary_parts.append(f"Customer: {user_lines[-1][:120]}") | |
| if summary_parts: | |
| result["summary"] = " | ".join(summary_parts) | |
| confidences.append(0.70) | |
| if confidences: | |
| result["confidence_score"] = round(sum(confidences) / len(confidences), 3) | |
| return result | |
| # --------------------------------------------------------------------------- | |
| # Bolna extracted_data parser (used if Bolna ever sends it) | |
| # --------------------------------------------------------------------------- | |
| def _bool(val) -> bool | None: | |
| if isinstance(val, bool): | |
| return val | |
| if isinstance(val, str): | |
| return val.strip().lower() in ("true", "yes", "1", "y") | |
| return None | |
| def _parse_one_extraction(cat: str, nm: str, val: Any, conf: Any, result: dict, confidences: list): | |
| if isinstance(conf, (int, float)): | |
| confidences.append(float(conf)) | |
| if "conversation" in cat and "summary" in nm: | |
| result["summary"] = str(val) if val else None | |
| elif "customer" in cat and "sentiment" in nm: | |
| result["sentiment"] = str(val) if val else None | |
| elif "restaurant" in cat and "upsell" in nm: | |
| result["upsell_accepted"] = _bool(val) | |
| elif "restaurant" in cat and "special" in nm: | |
| result["special_requests"] = str(val) if val else None | |
| elif "operation" in cat and "escalation" in nm: | |
| result["human_escalation"] = _bool(val) | |
| elif ("quality" in cat or "call" in cat) and "language" in nm: | |
| result["customer_language"] = str(val) if val else None | |
| elif "order" in cat and "upsell" in nm and "upsell_accepted" not in result: | |
| result["upsell_accepted"] = _bool(val) | |
| def _parse_bolna_extractions(raw: Any) -> dict: | |
| if not raw: | |
| return {} | |
| result: dict = {} | |
| confidences: list[float] = [] | |
| if isinstance(raw, list): | |
| for item in raw: | |
| if not isinstance(item, dict): | |
| continue | |
| cat = (item.get("category") or "").strip().lower() | |
| nm = (item.get("name") or "").strip().lower() | |
| val = item.get("subjective") or item.get("objective") or item.get("value") | |
| conf = item.get("confidence") | |
| _parse_one_extraction(cat, nm, val, conf, result, confidences) | |
| elif isinstance(raw, dict): | |
| for category, names in raw.items(): | |
| if not isinstance(names, dict): | |
| continue | |
| cat = category.strip().lower() | |
| for name, payload in names.items(): | |
| if not isinstance(payload, dict): | |
| continue | |
| nm = name.strip().lower() | |
| val = payload.get("subjective") or payload.get("objective") or payload.get("value") | |
| conf = payload.get("confidence") | |
| _parse_one_extraction(cat, nm, val, conf, result, confidences) | |
| if confidences: | |
| result["confidence_score"] = round(sum(confidences) / len(confidences), 3) | |
| return result | |
| # --------------------------------------------------------------------------- | |
| # Background: poll Bolna for extraction data (in case it runs async) | |
| # --------------------------------------------------------------------------- | |
| async def _poll_and_update_extraction(session_id: str) -> None: | |
| headers = {"Authorization": f"Bearer {config.BOLNA_API_KEY}"} | |
| url = BOLNA_EXEC_URL.format(execution_id=session_id) | |
| async with httpx.AsyncClient(timeout=15) as client: | |
| for attempt in range(POLL_MAX_ATTEMPTS): | |
| await asyncio.sleep(POLL_INTERVAL) | |
| try: | |
| resp = await client.get(url, headers=headers) | |
| if resp.status_code != 200: | |
| continue | |
| data = resp.json() | |
| raw = ( | |
| data.get("extracted_data") | |
| or data.get("agent_extraction") | |
| or data.get("custom_extractions") | |
| ) | |
| bolna_summary = data.get("summary") | |
| if raw or bolna_summary: | |
| cols = _parse_bolna_extractions(raw) | |
| if bolna_summary and not cols.get("summary"): | |
| cols["summary"] = bolna_summary | |
| get_store().upsert_call_log({ | |
| "session_id": session_id, | |
| "extractions": raw, | |
| **cols, | |
| }) | |
| print(f"[extraction-poll] {session_id} updated={list(cols.keys())}", file=sys.stderr) | |
| return | |
| except Exception as exc: | |
| print(f"[extraction-poll] {session_id} error={exc}", file=sys.stderr) | |
| print(f"[extraction-poll] {session_id} gave up", file=sys.stderr) | |
| # --------------------------------------------------------------------------- | |
| # Webhook endpoint | |
| # --------------------------------------------------------------------------- | |
| async def bolna_webhook(request: Request, background_tasks: BackgroundTasks): | |
| global _last_payload | |
| try: | |
| payload = await request.json() | |
| except Exception: | |
| return {"success": False, "message": "Invalid JSON payload."} | |
| print(f"[webhook] keys={list(payload.keys())}", file=sys.stderr) | |
| _last_payload = payload | |
| context = ( | |
| payload.get("context_details") | |
| or payload.get("user_data") | |
| or (payload.get("context_data") or {}) | |
| ) | |
| if isinstance(context, dict): | |
| context = context.get("recipient_data") or context | |
| # Check if Bolna sent extraction data with the webhook | |
| raw_extraction = ( | |
| payload.get("extracted_data") | |
| or payload.get("agent_extraction") | |
| or payload.get("custom_analytics") | |
| or payload.get("extraction") | |
| or payload.get("analytics") | |
| ) | |
| bolna_summary = payload.get("summary") | |
| transcript = _parse_transcript(payload) | |
| session_id = ( | |
| payload.get("id") | |
| or payload.get("execution_id") | |
| or payload.get("call_id") | |
| or payload.get("call_sid") | |
| ) | |
| if raw_extraction or bolna_summary: | |
| # Bolna sent extractions — parse them | |
| extraction_cols = _parse_bolna_extractions(raw_extraction) | |
| if bolna_summary and not extraction_cols.get("summary"): | |
| extraction_cols["summary"] = bolna_summary | |
| else: | |
| # Bolna sent no extractions — derive from transcript | |
| extraction_cols = _extract_from_transcript(transcript, payload) | |
| # Also schedule background poll in case Bolna populates it later | |
| if session_id and config.BOLNA_API_KEY: | |
| background_tasks.add_task(_poll_and_update_extraction, session_id) | |
| log = { | |
| "session_id": session_id, | |
| "table_number": str(context.get("table_number")) if isinstance(context, dict) and context.get("table_number") else None, | |
| "outlet_location": context.get("outlet_location") if isinstance(context, dict) else None, | |
| "channel": "phone" if payload.get("telephony_data") else "web", | |
| "transcript": transcript, | |
| "extractions": raw_extraction or extraction_cols or None, | |
| **extraction_cols, | |
| } | |
| saved = get_store().upsert_call_log(log) | |
| print(f"[webhook] saved session={session_id} cols={list(extraction_cols.keys())}", file=sys.stderr) | |
| return {"success": True, "id": saved.get("id")} | |
| async def webhook_debug(): | |
| return { | |
| "keys": list(_last_payload.keys()), | |
| "extracted_data": _last_payload.get("extracted_data"), | |
| "agent_extraction": _last_payload.get("agent_extraction"), | |
| "custom_analytics": _last_payload.get("custom_analytics"), | |
| "summary": _last_payload.get("summary"), | |
| } | |
| async def backfill_extractions(admin_key: str = ""): | |
| """One-time backfill: fetch all Bolna executions and populate extraction analytics. | |
| Protected by admin key. | |
| """ | |
| import config as cfg | |
| if cfg.ADMIN_KEY and admin_key != cfg.ADMIN_KEY: | |
| return {"success": False, "message": "Unauthorized"} | |
| if not cfg.BOLNA_API_KEY or not cfg.BOLNA_AGENT_ID: | |
| return {"success": False, "message": "Bolna not configured"} | |
| store = get_store() | |
| url = f"https://api.bolna.ai/v2/agent/{cfg.BOLNA_AGENT_ID}/executions?limit=50" | |
| headers = {"Authorization": f"Bearer {cfg.BOLNA_API_KEY}"} | |
| try: | |
| async with httpx.AsyncClient(timeout=20) as client: | |
| resp = await client.get(url, headers=headers) | |
| items = resp.json().get("data", []) | |
| except Exception as exc: | |
| return {"success": False, "message": str(exc)} | |
| updated = 0 | |
| for ex in items: | |
| transcript_raw = ex.get("transcript") | |
| if not transcript_raw or len(str(transcript_raw)) < 50: | |
| continue | |
| raw_extraction = ( | |
| ex.get("extracted_data") | |
| or ex.get("agent_extraction") | |
| or ex.get("custom_extractions") | |
| ) | |
| bolna_summary = ex.get("summary") | |
| transcript = _parse_transcript(ex) or [{"role": "unknown", "text": str(transcript_raw)}] | |
| if raw_extraction or bolna_summary: | |
| cols = _parse_bolna_extractions(raw_extraction) | |
| if bolna_summary and not cols.get("summary"): | |
| cols["summary"] = bolna_summary | |
| else: | |
| cols = _extract_from_transcript(transcript, ex) | |
| context = ex.get("context_details") or {} | |
| if isinstance(context, dict): | |
| context = context.get("recipient_data") or context | |
| store.upsert_call_log({ | |
| "session_id": ex["id"], | |
| "table_number": str(context.get("table_number")) if isinstance(context, dict) and context.get("table_number") else None, | |
| "outlet_location": context.get("outlet_location") if isinstance(context, dict) else None, | |
| "channel": "phone" if ex.get("telephony_data") else "web", | |
| "transcript": transcript, | |
| "extractions": raw_extraction or cols or None, | |
| **cols, | |
| }) | |
| updated += 1 | |
| return {"success": True, "backfilled": updated} | |