Spaces:
Sleeping

File size: 3,023 Bytes
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
"""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 sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from dotenv import load_dotenv
load_dotenv()

import json
import urllib.request

import config
from store import get_store
from 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()