File size: 17,271 Bytes
534b431
 
 
 
 
 
 
 
dfedf76
 
 
 
 
 
 
534b431
 
 
dfedf76
 
534b431
 
 
 
 
dfedf76
534b431
 
 
 
 
 
dfedf76
534b431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfedf76
 
 
 
 
 
 
534b431
 
 
 
dfedf76
534b431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfedf76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
534b431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfedf76
534b431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfedf76
 
534b431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfedf76
534b431
 
 
 
 
 
 
 
 
 
dfedf76
 
 
534b431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfedf76
 
534b431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfedf76
 
534b431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfedf76
534b431
 
 
 
 
 
 
dfedf76
 
 
534b431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Main cascade handler orchestrating ASR β†’ LLM β†’ TTS pipeline."""

from __future__ import annotations
import asyncio
import logging
import threading
from typing import TYPE_CHECKING, Any, Dict, List, Union

from lyon_chatbox.cascade import pipeline
from lyon_chatbox.cascade.asr import ASRProvider, StreamingASRProvider
from lyon_chatbox.cascade.llm import LLMProvider
from lyon_chatbox.cascade.tts import TTSProvider
from lyon_chatbox.cascade.config import get_config
from lyon_chatbox.cascade.pipeline import PROMPT_LOG, PipelineContext
from lyon_chatbox.tools.core_tools import (
    ToolDependencies,
    get_tool_specs,
)
from lyon_chatbox.cascade.turn_result import TurnItem, TurnResult, PipelineResult
from lyon_chatbox.cascade.provider_factory import (
    init_asr_provider,
    init_llm_provider,
    init_tts_provider,
    init_transcript_analysis,
)
from lyon_chatbox.cascade.transcript_analysis import (
    NoOpTranscriptManager,
    TranscriptAnalysisManager,
)


if TYPE_CHECKING:
    from lyon_chatbox.cascade.speech_output import SpeechOutput


logger = logging.getLogger(__name__)


def convert_tool_specs_to_chat_format(realtime_specs: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
    """Convert tool specs from Realtime API format to Chat Completions API format."""
    chat_specs = []
    for spec in realtime_specs:
        if spec["type"] == "function":
            chat_spec = {
                "type": "function",
                "function": {
                    "name": spec["name"],
                    "description": spec["description"],
                    "parameters": spec["parameters"],
                },
            }
            chat_specs.append(chat_spec)
    return chat_specs


class CascadeHandler:
    """Main handler for cascade pipeline mode."""

    def __init__(self, deps: ToolDependencies):
        """Initialize cascade handler."""
        self.deps = deps

        # Speech output backend (set by console or Gradio frontend)
        self.speech_output: SpeechOutput | None = None

        # Providers are initialized lazily so the UI can launch before users
        # enter API keys or choose installable/local provider options.
        self.asr: ASRProvider | None = None
        self.llm: LLMProvider | None = None
        self.tts: TTSProvider | None = None
        self.is_streaming_asr = False
        self.initialization_error: str | None = None

        # Conversation state
        self.conversation_history: List[Dict[str, Any]] = []
        self.processing_lock = asyncio.Lock()
        self.initialization_lock = threading.Lock()
        self.running = False

        # Event loop for async operations
        self.loop: asyncio.AbstractEventLoop | None = None
        self.loop_thread: threading.Thread | None = None

        # Track last partial transcript to avoid log spam
        self._last_partial_transcript = ""

        # Dynamic tool gating based on available capabilities
        exclusion_list: list[str] = []
        if deps.vision_manager is None:
            exclusion_list.append("describe_camera_image")

        # Get tool specs and convert to Chat Completions format
        # Note : get_tool_specs() returns Realtime API format, so we need Chat Completions format
        self.tool_specs = convert_tool_specs_to_chat_format(get_tool_specs(exclusion_list=exclusion_list))

        # Side-channel storage for see_image_through_camera frames (JPEG bytes, indexed)
        self._captured_frames: list[bytes] = []

        # Transcript analysis (NoOp if no reactions configured)
        self.transcript_manager: TranscriptAnalysisManager | NoOpTranscriptManager = (
            init_transcript_analysis(deps)
        )

        # Cost tracking
        self.cumulative_cost: float = 0.0
        self._turn_cost: float = 0.0

        # Turn result tracking
        self._current_turn_items: list[TurnItem] = []
        self._turn_results: list[TurnResult] = []

        logger.info("Cascade handler created; providers will initialize on first use")

    @property
    def is_initialized(self) -> bool:
        """Whether cascade providers are ready."""
        return self.asr is not None and self.llm is not None and self.tts is not None

    def ensure_initialized(self) -> None:
        """Initialize cascade providers on demand.

        Raises the original setup error to the caller so Gradio can render it
        in the UI instead of crashing the whole app at launch.
        """
        if self.is_initialized:
            return

        with self.initialization_lock:
            if self.is_initialized:
                return

            try:
                self.asr = init_asr_provider()
                self.llm = init_llm_provider()
                self.tts = init_tts_provider()
                self.is_streaming_asr = get_config().is_asr_streaming()
                self.transcript_manager = init_transcript_analysis(self.deps)
                self.initialization_error = None
                logger.info(f"Cascade providers initialized (streaming_asr={self.is_streaming_asr})")

                if self.running and self.loop and self.llm is not None:
                    logger.info("Pre-warming LLM connection...")
                    asyncio.run_coroutine_threadsafe(self.llm.warmup(), self.loop)
            except Exception as e:
                self.initialization_error = str(e)
                logger.exception("Cascade provider initialization failed: %s", e)
                raise

    # ─────────────────────────────────────────────────────────────────────────────
    # Transcript Analysis Helpers (fire-and-forget, never block pipeline)
    # ─────────────────────────────────────────────────────────────────────────────

    def _get_stable_text(self, partial: str) -> str:
        """Get stable text for analysis (if ASR supports it)."""
        if hasattr(self.asr, "get_stable_text"):
            stable = self.asr.get_stable_text()
            if stable and stable != partial:
                logger.debug(f"πŸ“Œ Using stable text for analysis: '{stable[:60]}...'")
                return stable  # type: ignore[no-any-return]
        return partial

    async def _on_transcript_partial(self, text: str) -> None:
        """Notify partial transcript for real-time reactions (streaming only)."""
        await self.transcript_manager.analyze_partial(text)

    def _on_transcript_final(self, text: str) -> None:
        """Notify final transcript (fire-and-forget, parallel with LLM)."""
        task = asyncio.create_task(self.transcript_manager.analyze_final(text))
        if hasattr(self.transcript_manager, '_pending_tasks'):
            self.transcript_manager._pending_tasks.append(task)

    def _on_turn_complete(self) -> None:
        """Reset transcript analysis between conversation turns."""
        self.transcript_manager.reset()

    @property
    def turn_results(self) -> list[TurnResult]:
        """Completed conversation turns (read by UI poller)."""
        return self._turn_results

    def _aggregate_cost(self, provider: Union[ASRProvider, LLMProvider, TTSProvider], provider_name: str) -> None:
        """Aggregate cost from a provider if it tracks costs."""
        if hasattr(provider, "last_cost") and provider.last_cost > 0:
            cost = provider.last_cost
            self.cumulative_cost += cost
            self._turn_cost += cost
            logger.info(f"Cost ({provider_name}): ${cost:.4f} | Cumulative: ${self.cumulative_cost:.4f}")
            provider.last_cost = 0.0  # Reset for next call

    async def _run_pipeline_after_transcription(self, transcript: str) -> TurnResult:
        """Run the shared post-ASR pipeline: validate β†’ history β†’ LLM β†’ TTS β†’ result.

        Called by both manual and streaming paths after transcription is obtained.
        Caller must hold self.processing_lock.
        """
        from lyon_chatbox.cascade.timing import tracker

        if not transcript.strip():
            logger.warning("Empty transcript, ignoring")
            if self.deps.movement_manager:
                self.deps.movement_manager.set_listening(False)
            return TurnResult()

        # Add user message to history
        self.conversation_history.append({"role": "user", "content": transcript})

        # Update robot state - done listening
        if self.deps.movement_manager:
            self.deps.movement_manager.set_listening(False)

        # Analyze final transcript (parallel with LLM, fire-and-forget)
        self._on_transcript_final(transcript)

        # LLM: Text β†’ Response + Tool Calls
        assert self.llm is not None
        assert self.tts is not None
        logger.info("Generating LLM response...")
        tracker.mark("llm_start")
        ctx = PipelineContext(
            llm=self.llm, tts=self.tts, speech_output=self.speech_output,
            conversation_history=self.conversation_history,
            tool_specs=self.tool_specs,
            deps=self.deps,
            result=PipelineResult(),
        )
        result = await pipeline.process_llm_response(ctx)
        tracker.mark("llm_complete")

        # Apply pipeline outputs to handler state
        self._current_turn_items.extend(result.turn_items)
        self._captured_frames.extend(result.captured_frames)
        self._turn_cost += result.cost
        self.cumulative_cost += result.cost

        # Reset transcript analysis for next turn
        self._on_turn_complete()

        # Build and store TurnResult
        turn = TurnResult(
            transcript=transcript,
            items=list(self._current_turn_items),
            cost=self._turn_cost,
        )
        self._turn_results.append(turn)
        return turn

    async def process_audio_manual(self, audio_bytes: bytes) -> TurnResult:
        """Process recorded audio through the cascade pipeline.

        Called manually from Gradio UI.

        Args:
            audio_bytes: WAV audio bytes from Gradio recording

        Returns:
            TurnResult with transcript, displayable items, and cost

        """
        from lyon_chatbox.cascade.timing import tracker

        # Note: tracker.reset() is called in gradio_ui._stop_recording()
        # to capture user_stop_click in the same timeline

        # Reset per-turn state
        self._current_turn_items = []
        self._turn_cost = 0.0

        async with self.processing_lock:
            try:
                self.ensure_initialized()
                assert self.asr is not None

                # Update robot state - user is speaking
                if self.deps.movement_manager:
                    self.deps.movement_manager.set_listening(True)

                # ASR: Audio β†’ Text
                logger.info("Transcribing...")
                tracker.mark("transcribing_start")
                transcript = await self.asr.transcribe(audio_bytes, language="en")
                tracker.mark("asr_complete", {"transcript_len": len(transcript)})
                self._aggregate_cost(self.asr, "ASR")
                logger.info(f"User said: {transcript}")

                return await self._run_pipeline_after_transcription(transcript)

            except Exception as e:
                logger.exception(f"Error processing audio: {e}")
                if self.deps.movement_manager:
                    self.deps.movement_manager.set_listening(False)
                raise

    async def process_audio_streaming_start(self) -> None:
        """Initialize streaming ASR session.

        Called from Gradio UI when user starts recording with a streaming ASR provider.
        """
        self.ensure_initialized()
        assert self.asr is not None
        if isinstance(self.asr, StreamingASRProvider):
            logger.info("Starting streaming ASR session")
            await self.asr.start_stream()

            # Update robot state - user is about to speak
            if self.deps.movement_manager:
                self.deps.movement_manager.set_listening(True)
        else:
            logger.warning("ASR provider does not support streaming")

    async def process_audio_streaming_chunk(self, chunk: bytes) -> str | None:
        """Send audio chunk to streaming ASR and get partial transcript.

        Called from Gradio UI during recording to stream audio in real-time.

        Args:
            chunk: Audio chunk bytes (WAV format)

        Returns:
            Partial transcript if available, None otherwise

        """
        self.ensure_initialized()
        assert self.asr is not None
        if isinstance(self.asr, StreamingASRProvider):
            await self.asr.send_audio_chunk(chunk)
            partial = await self.asr.get_partial_transcript()

            # Log partial transcript (debounced to reduce spam)
            if partial and partial != self._last_partial_transcript:
                logger.info(f"🎀 Partial: {partial}")
                self._last_partial_transcript = partial

            # Analyze partial transcript (debounced, fire-and-forget)
            if partial:
                # Use stable text for entity extraction to avoid noisy draft tokens
                stable_text = self._get_stable_text(partial)
                await self._on_transcript_partial(stable_text)

            return partial
        return None

    async def process_audio_streaming_end(self) -> TurnResult:
        """Finalize streaming session, get final transcript, and run LLM pipeline.

        Called from Gradio UI when user stops recording with a streaming ASR provider.

        Returns:
            TurnResult with transcript, displayable items, and cost

        """
        from lyon_chatbox.cascade.timing import tracker

        # Reset per-turn state
        self._current_turn_items = []
        self._turn_cost = 0.0

        async with self.processing_lock:
            try:
                self.ensure_initialized()
                assert self.asr is not None

                # Get final transcript from streaming ASR
                if isinstance(self.asr, StreamingASRProvider):
                    logger.info("Finalizing streaming ASR session")
                    tracker.mark("transcribing_start")
                    transcript = await self.asr.end_stream()
                    tracker.mark("asr_complete", {"transcript_len": len(transcript)})
                    self._aggregate_cost(self.asr, "ASR")
                else:
                    logger.warning("ASR provider does not support streaming, this shouldn't happen")
                    return TurnResult()

                logger.info(f"User said: {transcript}")

                turn = await self._run_pipeline_after_transcription(transcript)

                # Reset partial transcript tracking (streaming-specific)
                self._last_partial_transcript = ""

                return turn

            except Exception as e:
                logger.exception(f"Error processing streaming audio: {e}")
                if self.deps.movement_manager:
                    self.deps.movement_manager.set_listening(False)
                raise

    def _run_event_loop(self, ready: threading.Event) -> None:
        """Run the asyncio event loop in a background thread."""
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)
        self.loop.call_soon(ready.set)
        logger.debug("Event loop started in background thread")
        try:
            self.loop.run_forever()
        finally:
            self.loop.close()

    def start(self) -> None:
        """Start the cascade handler (Gradio mode)."""
        if self.running:
            logger.warning("Cascade handler already running")
            return

        logger.info("Starting cascade handler (Gradio mode)...")
        self.running = True

        # Reset prompt log for this run
        PROMPT_LOG.write_text("", encoding="utf-8")

        # Start event loop in background thread for async operations
        loop_ready = threading.Event()
        self.loop_thread = threading.Thread(target=self._run_event_loop, args=(loop_ready,), daemon=True)
        self.loop_thread.start()
        loop_ready.wait(timeout=5)

        logger.info("Cascade handler started")

    def stop(self) -> None:
        """Stop the cascade handler."""
        if not self.running:
            return

        logger.info("Stopping cascade handler...")
        self.running = False

        # Stop event loop
        if self.loop and self.loop.is_running():
            self.loop.call_soon_threadsafe(self.loop.stop)

        if self.loop_thread:
            self.loop_thread.join(timeout=5)

        logger.info("Cascade handler stopped")

    def clear_state(self) -> None:
        """Reset all conversation and turn state (called from UI clear button)."""
        self.conversation_history.clear()
        self._captured_frames.clear()
        self._current_turn_items.clear()
        self._turn_results.clear()