"""One live call: listens, understands, and plays your recorded answers.""" from __future__ import annotations import asyncio import logging import time from typing import Protocol import httpx from . import db from .audio import CHUNK_BYTES, CHUNK_MS, chunks from .config import Settings from .intent import IntentMatcher, _norm from .monitor import BOT, CALLER, hub from .vad import UtteranceSegmenter log = logging.getLogger("session") class Transport(Protocol): async def send_pcm(self, pcm: bytes) -> None: ... async def clear(self) -> None: ... async def hangup(self) -> None: ... async def transfer_to_me(self) -> bool: ... class CallSession: def __init__(self, call_id: str, caller: str, called: str, provider: str, settings: Settings, stt, matcher: IntentMatcher, clips: dict[str, bytes], transport: Transport, mode: str = "bot"): self.mode = mode # "bot" (whitelisted caller) or "voicemail" (anyone else) self.call_id = call_id self.caller = caller self.called = called self.provider = provider self.s = settings self.stt = stt self.matcher = matcher self.clips = clips self.t = transport self.vad = UtteranceSegmenter() self.started = time.monotonic() self.last_activity = self.started # last caller speech or bot audio self.last_silence_prompt = 0.0 self.last_played: dict[str, float] = {} self.transcript: list[str] = [] self.paused = False # pause bot (e.g. while you listen in) self._play_task: asyncio.Task | None = None self._watchdog: asyncio.Task | None = None self._utt_lock = asyncio.Lock() self.ended = False # ---------- lifecycle ---------- async def start(self): db.start_call(self.call_id, self.provider, self.caller, self.called) hub.live_sessions[self.call_id] = self self._emit("call_started", detail=f"{self.mode} | from {self.caller}") self._watchdog = asyncio.create_task(self._watch()) if self.mode == "voicemail": if self.s.unknown_caller_clip: await self.play(self.s.unknown_caller_clip, "unknown_caller") return if self.s.greeting_clip: await self.play(self.s.greeting_clip, "greeting") async def stop(self, reason: str): if self.ended: return self.ended = True for t in (self._play_task, self._watchdog): if t and not t.done(): t.cancel() db.end_call(self.call_id, reason) self._emit("call_ended", detail=reason) hub.live_sessions.pop(self.call_id, None) if self.s.webhook_url: asyncio.create_task(self._webhook()) async def _webhook(self): """POST {call, events} to webhook_url once the call is over (best effort, one retry).""" call = db.query("SELECT * FROM calls WHERE id=?", (self.call_id,)) body = {"call": call[0] if call else {"id": self.call_id}, "events": db.query("SELECT * FROM events WHERE call_id=? ORDER BY ts", (self.call_id,))} for attempt in range(2): try: async with httpx.AsyncClient(timeout=10) as c: r = await c.post(self.s.webhook_url, json=body) r.raise_for_status() return except Exception as e: log.warning("webhook attempt %d failed: %s", attempt + 1, e) await asyncio.sleep(5) # ---------- audio in ---------- async def on_audio(self, pcm: bytes): hub.audio(self.call_id, CALLER, pcm) for ev in self.vad.feed(pcm): if ev.kind == "speech_start": self.last_activity = time.monotonic() if self.s.allow_barge_in and self.is_playing(): await self.stop_playback("barge-in") elif ev.kind == "utterance": self.last_activity = time.monotonic() asyncio.create_task(self._handle_utterance(ev.audio)) async def _handle_utterance(self, audio: bytes): secs = len(audio) / 16000 async with self._utt_lock: # keep answers in order text = await self.stt.transcribe(audio) db.bump(self.call_id, stt_seconds=secs) if text: await self._respond(text) async def on_text(self, text: str): """Typed line from the browser test page - same logic, skips speech-to-text.""" self.last_activity = time.monotonic() async with self._utt_lock: await self._respond(text.strip()) async def _respond(self, text: str): if not text: return self.transcript.append(text) if self.mode == "voicemail": self._emit("voicemail", text=text) return match = await self.matcher.match(text, self.transcript[:-1]) self._emit("caller_said", text=text, intent=match.intent.name if match.intent else "", detail=f"{match.method} {match.score:.0f}") if self.paused or self.ended: return if match.intent: now = time.monotonic() if now - self.last_played.get(match.intent.name, -1e9) < self.s.same_clip_cooldown_sec: self._emit("skipped", intent=match.intent.name, detail="cooldown") return self.last_played[match.intent.name] = now await self.play(match.intent.clip, match.intent.name) if match.intent.end_call_after: await self._wait_playback() await asyncio.sleep(0.5) await self.t.hangup() elif self.s.fallback_clip and _norm(text): # not for noise transcribed as "." await self.play(self.s.fallback_clip, "fallback") # ---------- audio out ---------- def is_playing(self) -> bool: return bool(self._play_task and not self._play_task.done()) async def play(self, clip_path: str, label: str): pcm = self.clips.get(clip_path) if pcm is None: log.error("clip missing: %s", clip_path) return await self.stop_playback(None) db.bump(self.call_id, clips=1) self._emit("bot_played", intent=label, detail=f"{len(pcm) / 16000:.1f}s") self._play_task = asyncio.create_task(self._stream(pcm)) async def _stream(self, pcm: bytes): """Send audio paced at real time (with ~400 ms lead) so barge-in can cut it instantly.""" t0 = time.monotonic() sent_ms = 0 try: for c in chunks(pcm, CHUNK_BYTES): ahead = sent_ms / 1000 - (time.monotonic() - t0) if ahead > 0.4: await asyncio.sleep(ahead - 0.4) await self.t.send_pcm(c) hub.audio(self.call_id, BOT, c) sent_ms += CHUNK_MS self.last_activity = time.monotonic() # wait until the provider has actually played it remaining = sent_ms / 1000 - (time.monotonic() - t0) if remaining > 0: await asyncio.sleep(remaining) self.last_activity = time.monotonic() except asyncio.CancelledError: pass async def _wait_playback(self): if self._play_task: try: await self._play_task except asyncio.CancelledError: pass async def stop_playback(self, why: str | None): if self.is_playing(): self._play_task.cancel() await self.t.clear() if why: self._emit("bot_interrupted", detail=why) # ---------- dashboard controls ---------- async def transfer_to_me(self) -> bool: self.paused = True await self.stop_playback("transfer") ok = await self.t.transfer_to_me() self._emit("transfer", detail="ok" if ok else "failed") return ok async def hangup(self): await self.t.hangup() async def manual_play(self, intent_name: str): i = self.matcher.by_name.get(intent_name) if i: await self.play(i.clip, f"{i.name} (manual)") # ---------- silence / duration watchdog ---------- async def _watch(self): try: while not self.ended: await asyncio.sleep(1) now = time.monotonic() limit = 120 if self.mode == "voicemail" else self.s.max_call_minutes * 60 if now - self.started > limit: self._emit("max_duration", detail=f"{limit // 60} min") await self.t.hangup() return if self.mode == "voicemail": # hang up after 8 s of silence once they've had a chance to speak if self.transcript and not self.is_playing() and now - self.last_activity > 8: await self.t.hangup() return continue if (self.s.silence_prompt_clip and not self.paused and not self.is_playing() and now - self.last_activity > self.s.silence_prompt_after_sec and now - self.last_silence_prompt > self.s.silence_prompt_repeat_sec): self.last_silence_prompt = now await self.play(self.s.silence_prompt_clip, "silence_prompt") except asyncio.CancelledError: pass def _emit(self, kind: str, text: str = "", intent: str = "", detail: str = ""): ev = db.add_event(self.call_id, kind, text, intent, detail) ev["caller"] = self.caller hub.event(self.call_id, ev)