Spaces:
Sleeping
Sleeping
Upload routes/webhooks.py with huggingface_hub
Browse files1 unmodified line23456717 unmodified lines252627282930318 unmodified lines4041424344459 unmodified lines5556575859603 unmodified lines646566676869701 unmodified lineBolna's payload shape varies by configuration, so parsing is defensive:we pick out whatever transcript/extraction/context fields are present."""from __future__ import annotations17 unmodified linesif isinstance(raw, list):return rawif isinstance(raw, str):# "assistant: hi\nuser: hello" style β structured turnsturns = []for line in raw.splitlines():line = line.strip()8 unmodified linesreturn [{"role": "unknown", "text": str(raw)}]@router.post("/bolna")async def bolna_webhook(request: Request):try:9 unmodified linesif isinstance(context, dict):context = context.get("recipient_data") or contextlog = {"session_id": payload.get("id")or payload.get("execution_id")3 unmodified lines"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": payload.get("extracted_data") or payload.get("extraction") or None,}saved = get_store().upsert_call_log(log)return {"success": True, "id": saved.get("id")}1 unmodified line234567891017 unmodified lines2829303132338 unmodified lines424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111129 unmodified lines1221231241251261271281291303 unmodified lines1341351361371381391401411 unmodified lineBolna's payload shape varies by configuration, so parsing is defensive:we pick out whatever transcript/extraction/context fields are present.The nested extracted_data shape is:{Category: {Name: {subjective, objective, confidence, reasoning}}}We flatten the known keys into typed call_logs columns."""from __future__ import annotations17 unmodified linesif isinstance(raw, list):return rawif isinstance(raw, str):turns = []for line in raw.splitlines():line = line.strip()8 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):return val.strip().lower() in ("true", "yes", "1", "y")return Nonedef _parse_extractions(extracted_data: dict) -> dict:"""Parse nested {Category: {Name: {subjective, confidence, ...}}} into schema columns."""if not isinstance(extracted_data, dict):return {}result: dict = {}confidences: list[float] = []for category, names in extracted_data.items():if not isinstance(names, dict):continuecat = category.strip().lower()for name, payload in names.items():if not isinstance(payload, dict):continuenm = name.strip().lower()val = payload.get("subjective") or payload.get("objective") or payload.get("value")conf = payload.get("confidence")if isinstance(conf, (int, float)):confidences.append(float(conf))# Conversation Intelligenceif "conversation" in cat and "summary" in nm:result["summary"] = str(val) if val else None# Customer Intelligenceelif "customer" in cat and "sentiment" in nm:result["sentiment"] = str(val) if val else None# Restaurant Intelligence β upsellelif "restaurant" in cat and "upsell" in nm:result["upsell_accepted"] = _bool(val)# Restaurant Intelligence β special requestselif "restaurant" in cat and "special" in nm:result["special_requests"] = str(val) if val else None# Operations β escalationelif "operation" in cat and "escalation" in nm:result["human_escalation"] = _bool(val)# Call Quality β languageelif ("quality" in cat or "call" in cat) and "language" in nm:result["customer_language"] = str(val) if val else None# Orders β upsell fallback (if not already set)elif "order" in cat and "upsell" in nm and "upsell_accepted" not in result:result["upsell_accepted"] = _bool(val)if confidences:result["confidence_score"] = round(sum(confidences) / len(confidences), 3)return result@router.post("/bolna")async def bolna_webhook(request: Request):try:9 unmodified linesif isinstance(context, dict):context = context.get("recipient_data") or contextextracted_data = payload.get("extracted_data") or payload.get("extraction") or {}extraction_cols = _parse_extractions(extracted_data)log = {"session_id": payload.get("id")or payload.get("execution_id")3 unmodified lines"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": extracted_data if extracted_data else None,**extraction_cols,}saved = get_store().upsert_call_log(log)return {"success": True, "id": saved.get("id")}
routes/webhooks.py+73-2