Spaces:
Sleeping
Sleeping
fix: self-extraction from transcript + backfill endpoint
Browse filesFiles changed (2)
- routes/webhooks.py+313-44
- scripts/backfill_extractions.pyAdded+93
12345673456789101112131415161718191520212223242526212728293031323334353637383921 unmodified lines616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222522232242251 unmodified line22722822960612302312326423323423510 unmodified lines24624724881828384858687882492502519125225394952542552563 unmodified lines2602612621051062632642656 unmodified lines2722732741192752761222772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203211273223233243253263273281341351361373293303313324 unmodified lines337338339148340341342343344345346154155347157158348349160161350351352353354164355356357358359360361362363364365366367368369370371372373374168169375376377378379380381382383384385178386387181388183389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453"""Bolna post-call webhook → call_logs audit trail.
Bolna's payload shape varies by configuration, so parsing is defensive.Extraction data may arrive under several keys depending on Bolna version: - extracted_data {Category: {Name: {subjective, confidence, ...}}} - custom_analytics [{name, category, subjective, confidence, ...}] ← list - custom_analytics {Category: {Name: {subjective, ...}}} ← nested dictBolna's extraction LLM is not activated for this agent (extraction taskmissing from agent pipeline). We implement self-extraction directly fromthe 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 asyncioimport jsonimport reimport sysfrom typing import Any
import httpxfrom fastapi import APIRouter, Requestfrom fastapi import APIRouter, BackgroundTasks, Request
import configfrom store import get_store
router = APIRouter(prefix="/api/webhooks", tags=["webhooks"])
# Last raw payload for debugging via GET /api/webhooks/debug_last_payload: dict = {}
BOLNA_EXEC_URL = "https://api.bolna.ai/executions/{execution_id}"POLL_INTERVAL = 15POLL_MAX_ATTEMPTS = 4
# ---------------------------------------------------------------------------# Transcript parsing# ---------------------------------------------------------------------------
def _parse_transcript(payload: dict): raw = (21 unmodified lines 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: """Coerce Bolna string booleans to Python bool.""" if isinstance(val, bool): return val if isinstance(val, str):1 unmodified line return None
def _parse_one_extraction(cat: str, nm: str, val, conf, result: dict, confidences: list): """Map a single category/name/value into result columns."""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:10 unmodified lines result["upsell_accepted"] = _bool(val)
def _parse_extractions(raw) -> dict: """Parse Bolna extraction data into schema columns.
Handles three formats Bolna may send: 1. dict {Category: {Name: {subjective, confidence}}} ← extracted_data 2. list [{name, category, subjective, confidence, ...}] ← custom_analytics list 3. dict same nested format under custom_analytics key """def _parse_bolna_extractions(raw: Any) -> dict: if not raw: return {}
result: dict = {} confidences: list[float] = []
# Format 2: list of flat objects [{name, category, subjective, ...}] if isinstance(raw, list): for item in raw: if not isinstance(item, dict):3 unmodified lines 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)
# Format 1 / Format 3: nested dict {Category: {Name: {subjective, ...}}} elif isinstance(raw, dict): for category, names in raw.items(): if not isinstance(names, dict):6 unmodified lines 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# ---------------------------------------------------------------------------
@router.post("/bolna")async def bolna_webhook(request: Request):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."}
# Log raw payload keys to stderr so HF Space logs show us what Bolna sends safe_preview = {k: (v if not isinstance(v, (list, dict)) else f"<{type(v).__name__} len={len(v)}>") for k, v in payload.items()} print(f"[webhook] keys={list(payload.keys())} preview={json.dumps(safe_preview)}", file=sys.stderr) print(f"[webhook] keys={list(payload.keys())}", file=sys.stderr) _last_payload = payload
context = (4 unmodified lines if isinstance(context, dict): context = context.get("recipient_data") or context
# Bolna may send extraction results under any of these keys # 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") or payload.get("analysis") or {} ) extraction_cols = _parse_extractions(raw_extraction) print(f"[webhook] extraction_cols={extraction_cols}", file=sys.stderr) bolna_summary = payload.get("summary")
log = { "session_id": payload.get("id") transcript = _parse_transcript(payload) session_id = ( payload.get("id") or payload.get("execution_id") or payload.get("call_id") or payload.get("call_sid"), 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": _parse_transcript(payload), "extractions": raw_extraction if raw_extraction else None, "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")}
@router.get("/debug")async def webhook_debug(): """Return the last raw webhook payload for debugging extraction structure.""" return { "keys": list(_last_payload.keys()), "custom_analytics": _last_payload.get("custom_analytics"), "extracted_data": _last_payload.get("extracted_data"), "extraction": _last_payload.get("extraction"), "agent_extraction": _last_payload.get("agent_extraction"), "custom_analytics": _last_payload.get("custom_analytics"), "summary": _last_payload.get("summary"), }
@router.post("/backfill")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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""Backfill extraction analytics for all existing Bolna call executions.
Run once: python3 scripts/backfill_extractions.py
Fetches all executions from Bolna, runs self-extraction on each transcript,and upserts the results into call_logs."""import sysimport ossys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from dotenv import load_dotenvload_dotenv()
import jsonimport urllib.request
import configfrom store import get_storefrom routes.webhooks import ( _parse_transcript, _extract_from_transcript, _parse_bolna_extractions,)
EXEC_LIST_URL = f"https://api.bolna.ai/v2/agent/{config.BOLNA_AGENT_ID}/executions?limit=50"EXEC_URL = "https://api.bolna.ai/executions/{id}"HEADERS = {"Authorization": f"Bearer {config.BOLNA_API_KEY}"}
def fetch(url): req = urllib.request.Request(url, headers=HEADERS) with urllib.request.urlopen(req, timeout=15) as r: return json.loads(r.read())
def main(): store = get_store() print(f"Store mode: {store.mode}")
data = fetch(EXEC_LIST_URL) items = data.get("data", []) print(f"Found {len(items)} executions")
updated = 0 for ex in items: eid = ex["id"] transcript_raw = ex.get("transcript") if not transcript_raw or len(str(transcript_raw)) < 50: print(f" {eid[:8]} skip (no transcript)") continue
# Check if Bolna has extraction data raw_extraction = ( ex.get("extracted_data") or ex.get("agent_extraction") or ex.get("custom_extractions") ) bolna_summary = ex.get("summary")
transcript = transcript_raw if isinstance(transcript_raw, list) else [{"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 source = "bolna" else: cols = _extract_from_transcript(transcript, ex) source = "self"
context = ex.get("context_details") or {} if isinstance(context, dict): context = context.get("recipient_data") or context
log = { "session_id": eid, "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, } store.upsert_call_log(log) print(f" {eid[:8]} [{source}] lang={cols.get('customer_language')} sentiment={cols.get('sentiment')} summary={bool(cols.get('summary'))}") updated += 1
print(f"\nBackfilled {updated} call logs.")
if __name__ == "__main__": main()routes/webhooks.py+313-44
scripts/backfill_extractions.pyAdded+93