base_streaming_tts.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """Streaming-TTS format descriptor, handle and turn-scoped suppression helpers (#60671).
  2. Re-exported from ``gateway.platforms.base``; no imports from it (base imports this module).
  3. """
  4. from dataclasses import dataclass, field
  5. from typing import Any
  6. @dataclass
  7. # --------------------------------------------------------------------------- Streaming TTS format
  8. # descriptor and handle (#60671) ---------------------------------------------------------------------------
  9. class AudioFormat:
  10. """Declared PCM format for a streaming-TTS session: every ``write_streaming_tts``
  11. chunk must be raw little-endian PCM at this rate / channels / sample width."""
  12. sample_rate: int = 24000
  13. channels: int = 1
  14. sample_width: int = 2 # bytes per sample (int16 = 2)
  15. @dataclass
  16. class StreamingTTSHandle:
  17. """Opaque handle returned by ``begin_streaming_tts``; adapters may extend it with
  18. platform state. The base fields are consumer bookkeeping / cancellation."""
  19. chat_id: str = ""
  20. audio_format: AudioFormat = field(default_factory=AudioFormat)
  21. # True once the first PCM chunk is written: a later failure then ends cleanly instead of
  22. # falling back to whole-file TTS (don't replay already-audible output).
  23. audible: bool = False
  24. aborted: bool = False # set by abort_streaming_tts; late chunks are dropped
  25. def streaming_tts_turn_key(session_key: str | None, turn_marker: Any = None, *, event: Any = None) -> str | None:
  26. """Per-turn streaming-TTS suppression key — turn-scoped (not chat-scoped) so
  27. overlapping turns in one chat can't suppress each other's fallback paths.
  28. ``turn_marker`` is normally the run generation, else the event's message/update id."""
  29. if not session_key:
  30. return None
  31. if turn_marker is None and event is not None:
  32. turn_marker = getattr(event, "message_id", None) or getattr(event, "platform_update_id", None)
  33. return None if turn_marker is None else f"{session_key}:{turn_marker}"
  34. def streaming_tts_should_skip_whole_file(completed_turns: set[str], session_key: str | None,
  35. turn_marker: Any = None, *, event: Any = None) -> bool:
  36. """Pure, turn-scoped auto-TTS suppression decision (testable without the adapter stack)."""
  37. turn_key = streaming_tts_turn_key(session_key, turn_marker, event=event)
  38. return bool(turn_key and turn_key in completed_turns)