|
| 1 | +from __future__ import annotations |
| 2 | + |
1 | 3 | import base64 |
| 4 | +import os |
2 | 5 | from collections.abc import AsyncIterator |
3 | | -from typing import override |
| 6 | +from typing import TYPE_CHECKING, override |
4 | 7 |
|
5 | 8 | from agentle.tts.audio_format import AudioFormat |
6 | 9 | from agentle.tts.output_format_type import OutputFormatType |
7 | 10 | from agentle.tts.speech_config import SpeechConfig |
8 | 11 | from agentle.tts.speech_result import SpeechResult |
9 | 12 | from agentle.tts.tts_provider import TtsProvider |
10 | | -from agentle.utils.needs import needs |
| 13 | +from agentle.tts.voice_settings import VoiceSettings |
| 14 | +from agentle.utils.needs import check_modules |
| 15 | + |
| 16 | +if TYPE_CHECKING: |
| 17 | + from elevenlabs import AsyncElevenLabs |
11 | 18 |
|
12 | 19 |
|
13 | 20 | class ElevenLabsTtsProvider(TtsProvider): |
| 21 | + _client: AsyncElevenLabs |
| 22 | + |
| 23 | + def __init__(self, api_key: str | None = None) -> None: |
| 24 | + super().__init__() |
| 25 | + check_modules("elevenlabs") |
| 26 | + from elevenlabs import AsyncElevenLabs |
| 27 | + |
| 28 | + self._client = AsyncElevenLabs( |
| 29 | + api_key=api_key or os.getenv("ELEVENLABS_API_KEY") |
| 30 | + ) |
| 31 | + |
14 | 32 | @override |
15 | | - @needs("elevenlabs") |
16 | | - async def synthesize(self, text: str, config: SpeechConfig) -> SpeechResult: |
| 33 | + async def synthesize_async(self, text: str, config: SpeechConfig) -> SpeechResult: |
17 | 34 | from elevenlabs import AsyncElevenLabs |
18 | 35 | from elevenlabs.types.voice_settings import ( |
19 | 36 | VoiceSettings as ElevenLabsVoiceSettings, |
@@ -65,3 +82,27 @@ def _get_mime_type(self, output_format: OutputFormatType) -> AudioFormat: |
65 | 82 | return "audio/opus" |
66 | 83 | else: |
67 | 84 | return "application/octet-stream" # fallback |
| 85 | + |
| 86 | + |
| 87 | +if __name__ == "__main__": |
| 88 | + from dotenv import load_dotenv |
| 89 | + |
| 90 | + load_dotenv(override=True) |
| 91 | + tts_provider = ElevenLabsTtsProvider() |
| 92 | + audio = tts_provider.synthesize( |
| 93 | + "Oi, eu sou a Júlia. Assistente pessoal da Dany Braga do estúdio de fotografia. Em que posso ajudar você hoje?", |
| 94 | + config=SpeechConfig( |
| 95 | + voice_id="lWq4KDY8znfkV0DrK8Vb", |
| 96 | + model_id="eleven_v3", |
| 97 | + language_code="pt", |
| 98 | + voice_settings=VoiceSettings( |
| 99 | + stability=0.0, |
| 100 | + use_speaker_boost=None, |
| 101 | + similarity_boost=None, |
| 102 | + style=None, |
| 103 | + speed=None, |
| 104 | + ), |
| 105 | + ), |
| 106 | + ) |
| 107 | + with open("audio.mp3", "wb") as file: |
| 108 | + file.write(base64.b64decode(audio.audio)) |
0 commit comments