Spaces:
Sleeping
Sleeping
fix: self-extraction from transcript + backfill endpoint
Browse filesFiles changed (2)
- routes/webhooks.py+313-44
- scripts/backfill_extractions.pyAdded+93
123456789101112131415161718192021222324252621 unmodified lines48495051525354551 unmodified line575859606162636465666710 unmodified lines7879808182838485868788899091929394959697983 unmodified lines1021031041051061071081096 unmodified lines1161171181191201211221231241251261271281291301311321331341351361371381391404 unmodified lines145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184"""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 dict"""from __future__ import annotationsimport jsonimport sysfrom fastapi import APIRouter, Requestfrom store import get_storerouter = APIRouter(prefix="/api/webhooks", tags=["webhooks"])# Last raw payload for debugging via GET /api/webhooks/debug_last_payload: dict = {}def _parse_transcript(payload: dict):raw = (21 unmodified linesreturn [{"role": "unknown", "text": str(raw)}]def _bool(val) -> bool | None:"""Coerce Bolna string booleans to Python bool."""if isinstance(val, bool):return valif isinstance(val, str):1 unmodified linereturn Nonedef _parse_one_extraction(cat: str, nm: str, val, conf, result: dict, confidences: list):"""Map a single category/name/value into result columns."""if isinstance(conf, (int, float)):confidences.append(float(conf))if "conversation" in cat and "summary" in nm:result["summary"] = str(val) if val else Noneelif "customer" in cat and "sentiment" in nm:10 unmodified linesresult["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_data2. list [{name, category, subjective, confidence, ...}] ← custom_analytics list3. dict same nested format under custom_analytics key"""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 linesval = 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 linesval = 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@router.post("/bolna")async def bolna_webhook(request: Request):global _last_payloadtry: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 sendssafe_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)_last_payload = payloadcontext = (4 unmodified linesif isinstance(context, dict):context = context.get("recipient_data") or context# Bolna may send extraction results under any of these keysraw_extraction = (payload.get("extracted_data")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)log = {"session_id": payload.get("id")or payload.get("execution_id")or payload.get("call_id")or payload.get("call_sid"),"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,**extraction_cols,}saved = get_store().upsert_call_log(log)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"),}12345678910111213141516171819202122232425262728293031323334353637383921 unmodified lines6162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242251 unmodified line22722822923023123223323423510 unmodified lines2462472482492502512522532542552563 unmodified lines2602612622632642656 unmodified lines2722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313324 unmodified lines337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453"""Bolna post-call webhook → call_logs audit trail.Bolna'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 annotationsimport asyncioimport jsonimport reimport sysfrom typing import Anyimport httpxfrom fastapi import APIRouter, BackgroundTasks, Requestimport configfrom store import get_storerouter = APIRouter(prefix="/api/webhooks", tags=["webhooks"])_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 linesreturn [{"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 transcriptif 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:continuerole, _, msg = line.partition(":")msg = msg.strip()if not msg:continuer = 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_linesdef _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] = []# Languageresult["customer_language"] = _detect_language(text)confidences.append(0.85)# Sentimentpos = 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)# Upsellif _UPSELL_TRIGGER.search(text) and _UPSELL_ACCEPTED.search(text):result["upsell_accepted"] = Trueconfidences.append(0.70)elif _UPSELL_TRIGGER.search(text):result["upsell_accepted"] = Falseconfidences.append(0.60)# Escalationif _ESCALATION.search(text):result["human_escalation"] = Trueconfidences.append(0.80)# Summary — parse from "role: text" lines or structured turnsif 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 valif isinstance(val, str):1 unmodified linereturn Nonedef _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 Noneelif "customer" in cat and "sentiment" in nm:10 unmodified linesresult["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):3 unmodified linesval = 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):6 unmodified linesval = 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:continuedata = 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_summaryget_store().upsert_call_log({"session_id": session_id,"extractions": raw,**cols,})print(f"[extraction-poll] {session_id} updated={list(cols.keys())}", file=sys.stderr)returnexcept 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, background_tasks: BackgroundTasks):global _last_payloadtry: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 = payloadcontext = (4 unmodified linesif isinstance(context, dict):context = context.get("recipient_data") or context# Check if Bolna sent extraction data with the webhookraw_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 themextraction_cols = _parse_bolna_extractions(raw_extraction)if bolna_summary and not extraction_cols.get("summary"):extraction_cols["summary"] = bolna_summaryelse:# Bolna sent no extractions — derive from transcriptextraction_cols = _extract_from_transcript(transcript, payload)# Also schedule background poll in case Bolna populates it laterif 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")}@router.get("/debug")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"),}@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 cfgif 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 = 0for ex in items:transcript_raw = ex.get("transcript")if not transcript_raw or len(str(transcript_raw)) < 50:continueraw_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_summaryelse:cols = _extract_from_transcript(transcript, ex)context = ex.get("context_details") or {}if isinstance(context, dict):context = context.get("recipient_data") or contextstore.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 += 1return {"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