"""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()