From 5bcece56f3c62d0d2ec7d6a5b6acac01adcf5c80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aleix=20Conchillo=20Flaqu=C3=A9?= Date: Tue, 2 Jul 2024 10:11:16 -0700 Subject: [PATCH] services(cartesia): make sure we close the client on exit --- src/pipecat/services/cartesia.py | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/src/pipecat/services/cartesia.py b/src/pipecat/services/cartesia.py index d1aa8b762..c3b6b905b 100644 --- a/src/pipecat/services/cartesia.py +++ b/src/pipecat/services/cartesia.py @@ -8,7 +8,7 @@ from cartesia import AsyncCartesia from typing import AsyncGenerator -from pipecat.frames.frames import AudioRawFrame, Frame +from pipecat.frames.frames import AudioRawFrame, CancelFrame, EndFrame, Frame, StartFrame from pipecat.services.ai_services import TTSService from loguru import logger @@ -28,22 +28,33 @@ class CartesiaTTSService(TTSService): super().__init__(**kwargs) self._api_key = api_key + self._voice_id = voice_id self._model_id = model_id self._output_format = { "container": "raw", "encoding": encoding, "sample_rate": sample_rate, } - - try: - self._client = AsyncCartesia(api_key=self._api_key) - self._voice = self._client.voices.get(id=voice_id) - except Exception as e: - logger.exception(f"{self} initialization error: {e}") + self._client = None def can_generate_metrics(self) -> bool: return True + async def start(self, frame: StartFrame): + try: + self._client = AsyncCartesia(api_key=self._api_key) + self._voice = self._client.voices.get(id=self._voice_id) + except Exception as e: + logger.exception(f"{self} initialization error: {e}") + + async def stop(self, frame: EndFrame): + if self._client: + await self._client.close() + + async def cancel(self, frame: CancelFrame): + if self._client: + await self._client.close() + async def run_tts(self, text: str) -> AsyncGenerator[Frame, None]: logger.debug(f"Generating TTS: [{text}]")