Spaces:
Sleeping

File size: 17,025 Bytes
a812c01
 
5f3a567
 
 
 
 
 
a812c01
 
 
 
5f3a567
6f87d2d
5f3a567
6f87d2d
5f3a567
6f87d2d
5f3a567
 
a812c01
5f3a567
a812c01
 
 
 
6f87d2d
 
5f3a567
 
 
 
 
 
 
 
a812c01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f3a567
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d760511
 
 
 
 
 
 
 
5f3a567
6f87d2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f3a567
6f87d2d
d760511
 
 
6f87d2d
 
 
d760511
6f87d2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d760511
 
 
 
 
5f3a567
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a812c01
5f3a567
6f87d2d
a812c01
 
 
 
 
5f3a567
6f87d2d
 
a812c01
 
 
 
 
 
 
 
5f3a567
6f87d2d
 
5f3a567
6f87d2d
 
 
 
5f3a567
d760511
5f3a567
 
 
a812c01
 
5f3a567
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a812c01
 
 
5f3a567
 
d760511
a812c01
 
5f3a567
a812c01
6f87d2d
 
 
 
 
 
 
5f3a567
 
 
6f87d2d
5f3a567
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
"""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
# ---------------------------------------------------------------------------

@router.post("/bolna")
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")}


@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 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}