TalkLabs SDK - Ultra-low latency Text-to-Speech with Redis + spaCy streaming (ElevenLabs compatible)
Project description
TalkLabs Python SDK
SDK oficial da TalkLabs — compatível com a API ElevenLabs + Ultra-Low Latency Streaming com Redis e spaCy.
🚀 Novo em v2.0: Streaming com latência de ~200-500ms até o primeiro chunk de áudio!
Características
- ✅ Compatível com ElevenLabs: Drop-in replacement para APIs existentes
- ⚡ Ultra-Low Latency: ~200-500ms até primeiro áudio (vs 5-10s tradicional)
- 🧠 Processamento Inteligente: Segmentação natural com spaCy NLP
- 📡 Streaming Redis: Producer/Consumer paralelo com 3 níveis de prioridade
- 🎧 Real-time Playback: Chunks de áudio prontos para reprodução imediata
- 🔄 Incremental Streaming: Envio palavra-por-palavra para máxima responsividade
Instalação
pip install talklabs
Uso Rápido
1. Geração Simples (Síncrona)
from talklabs import TalkLabsClient
client = TalkLabsClient(api_key="tlk_live_xxxxx")
audio = client.generate(
text="Olá! Bem-vindo ao TalkLabs.",
voice="yasmin_alves"
)
with open("output.wav", "wb") as f:
f.write(audio)
2. 🚀 Ultra-Low Latency Streaming (NOVO!)
import asyncio
from talklabs import TalkLabsClient
async def stream_example():
client = TalkLabsClient(api_key="tlk_live_xxxxx")
# Streaming com Redis + spaCy (latência ~200-500ms)
async for audio_chunk in client.stream_redis(
text="Este é um teste de ultra baixa latência com Redis e spaCy!",
voice="yasmin_alves",
language="pt"
):
# Reproduzir audio_chunk imediatamente
# Ex: play_audio(audio_chunk) ou salvar em arquivo
print(f"Chunk recebido: {len(audio_chunk)} bytes")
asyncio.run(stream_example())
3. Streaming Incremental (Palavra por Palavra)
async def incremental_streaming():
client = TalkLabsClient(api_key="tlk_live_xxxxx")
# Simula digitação em tempo real
async for audio_chunk in client.stream_redis(
text="Olá mundo! Este texto é enviado palavra por palavra.",
voice="yasmin_alves",
incremental=True, # Envia palavra por palavra
word_delay=0.1 # 100ms entre palavras
):
print(f"Audio chunk: {len(audio_chunk)} bytes")
asyncio.run(incremental_streaming())
4. Streaming HTTP (Fallback)
# Streaming tradicional via HTTP
for chunk in client.generate_stream(
text="Streaming HTTP incremental",
voice="yasmin_alves"
):
# Processa chunks
pass
API Reference
TalkLabsClient
Métodos Principais
generate(text, voice, **kwargs) → bytes
- Geração síncrona completa
- Retorna áudio WAV completo
stream_redis(text, voice, **kwargs) → AsyncIterator[bytes] ⚡ NOVO!
- Ultra-low latency streaming (~200-500ms)
- Usa Redis + spaCy para processamento inteligente
- Retorna chunks de áudio conforme são gerados
- Parâmetros:
text: Texto para sintetizarvoice: ID da voz (ex: "yasmin_alves", "adam_rocha")language: Idioma ("pt", "en", "es", etc) - padrão: "pt"speed: Velocidade (0.5-2.0) - padrão: 1.0voice_settings: Configurações opcionaisincremental: Se True, envia palavra por palavra - padrão: Falseword_delay: Delay entre palavras no modo incremental - padrão: 0.1s
generate_stream(text, voice, **kwargs) → Iterator[bytes]
- Streaming HTTP tradicional
- Fallback para quando WebSocket não está disponível
stream_input(text_iterator, voice, **kwargs) → AsyncIterator[bytes]
- Streaming bidirecional WebSocket
- Aceita iterador assíncrono de texto
Vozes Disponíveis
# Listar todas as vozes
voices = client.get_voices()
for voice in voices:
print(f"{voice['voice_id']}: {voice['name']}")
Vozes Populares:
yasmin_alves- Português (BR) - Femininaadam_rocha- Português (BR) - Masculinamaria_silva- Português (PT) - Femininajoao_santos- Português (PT) - Masculina
Arquitetura do Streaming Redis
Como Funciona
- spaCy NLP: Texto é segmentado em sentenças naturais
- Redis Queue: Chunks são enfileirados com prioridades:
- P1 (Alta): Primeira sentença - processada imediatamente
- P2 (Média): Sentenças intermediárias
- P3 (Baixa): Última sentença
- Producer/Consumer: TTS processa chunks em paralelo enquanto texto ainda está sendo enviado
- Streaming Real-time: Áudio retorna conforme é gerado
Benefícios
- ⚡ Latência 95% menor: ~200-500ms vs 5-10s
- 🎯 Primeira Palavra Rápida: Usuário ouve resposta quase instantânea
- 📊 Escalável: Redis permite múltiplas sessões simultâneas
- 🧠 Inteligente: spaCy garante quebras naturais de sentença
Exemplos Avançados
Salvar Chunks Progressivamente
async def save_streaming():
client = TalkLabsClient(api_key="tlk_live_xxxxx")
with open("output_streaming.wav", "wb") as f:
async for chunk in client.stream_redis(
text="Este áudio será salvo em tempo real.",
voice="yasmin_alves"
):
f.write(chunk)
print("Áudio salvo!")
asyncio.run(save_streaming())
Reprodução em Tempo Real com pyaudio
import pyaudio
import asyncio
from talklabs import TalkLabsClient
async def play_realtime():
client = TalkLabsClient(api_key="tlk_live_xxxxx")
# Inicializar pyaudio
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=24000, output=True)
try:
async for chunk in client.stream_redis(
text="Olá! Este áudio está sendo reproduzido em tempo real.",
voice="yasmin_alves"
):
# Reproduzir imediatamente
stream.write(chunk)
finally:
stream.stop_stream()
stream.close()
p.terminate()
asyncio.run(play_realtime())
Configurações Avançadas de Voz
from talklabs import TalkLabsClient, VoiceSettings
client = TalkLabsClient(api_key="tlk_live_xxxxx")
settings = VoiceSettings(
stability=0.85, # Estabilidade da voz (0-1)
similarity_boost=0.75, # Similaridade com voz original
style=0.0, # Estilo expressivo (0-1)
use_speaker_boost=True # Boost de clareza
)
audio = client.generate(
text="Teste com configurações customizadas",
voice="yasmin_alves",
voice_settings=settings,
speed=1.2 # 20% mais rápido
)
Compatibilidade com ElevenLabs
Este SDK é 100% compatível com o SDK da ElevenLabs. Basta trocar:
# ElevenLabs
from elevenlabs import ElevenLabs
client = ElevenLabs(api_key="...")
# TalkLabs (drop-in replacement)
from talklabs import TalkLabsClient
client = TalkLabsClient(api_key="tlk_live_...")
Configuração
Base URL
- Produção:
https://api.talklabs.com.br - Local:
http://localhost:5000(desenvolvimento)
Endpoints
- HTTP:
/v1/text-to-speech/{voice_id} - WebSocket:
/v1/text-to-speech/{voice_id}/stream-redis⚡ NOVO!
Troubleshooting
Erro: "Connection refused"
Verifique se a API está rodando:
curl https://api.talklabs.com.br/health
Latência alta no streaming
- Use
stream_redis()ao invés degenerate_stream() - Verifique conexão Redis (deve estar em localhost ou baixa latência)
- Certifique-se que spaCy está carregado (
pt_core_news_sm)
Chunks de áudio corrompidos
- Certifique-se de salvar/reproduzir como WAV 24kHz mono
- Use
io.BytesIOpara buffer temporário se necessário
Licença
MIT License - veja LICENSE para detalhes.
Suporte
- Website: https://talklabs.com.br
- Documentação: https://docs.talklabs.com.br
- Email: support@talklabs.com.br
Desenvolvido com ❤️ pela equipe TalkLabs
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file talklabs-2.0.0.tar.gz.
File metadata
- Download URL: talklabs-2.0.0.tar.gz
- Upload date:
- Size: 11.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d554afcd11c4beb065194c4f32ab5c01162d579c70a4f78d2a44b113739ee432
|
|
| MD5 |
146dd38cacd9ce36bdbd35815322282e
|
|
| BLAKE2b-256 |
f455bcb7bf9548e075087cc627a2bcbe54bf326d5b13e9f1d6dba6d338e80f03
|
File details
Details for the file talklabs-2.0.0-py3-none-any.whl.
File metadata
- Download URL: talklabs-2.0.0-py3-none-any.whl
- Upload date:
- Size: 5.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3ffeb162937b2b1817b610871713a799295c4ff36843d2650d2c16b23e4d418a
|
|
| MD5 |
0be5ba02ebc87d6c49f119e103279982
|
|
| BLAKE2b-256 |
866f4996879565352aba857dcd68431d3530e4030c64896a2859e40174ad6123
|