Metadata-Version: 2.4
Name: talklabs
Version: 2.0.1
Summary: TalkLabs SDK - Ultra-low latency Text-to-Speech with Redis + spaCy streaming (ElevenLabs compatible)
Home-page: https://talklabs.com.br
Author: Francisco Lima
Author-email: Francisco Lima <franciscorllima@gmail.com>, TalkLabs Team <dev@talklabs.com.br>
Maintainer-email: TalkLabs Team <support@talklabs.com.br>
License: MIT License
        
        Copyright (c) 2025 Francisco Lima
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        
Project-URL: Homepage, https://talklabs.com.br
Project-URL: Documentation, https://docs.talklabs.com.br
Project-URL: Repository, https://github.com/talklabs/talklabs-sdk
Project-URL: Bug Tracker, https://github.com/talklabs/talklabs-sdk/issues
Keywords: tts,text-to-speech,speech-synthesis,voice,redis,streaming,elevenlabs,spacy,nlp
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.28.0
Requires-Dist: websockets>=10.0
Provides-Extra: dev
Requires-Dist: fastapi>=0.100.0; extra == "dev"
Requires-Dist: uvicorn[standard]>=0.24.0; extra == "dev"
Requires-Dist: pydantic>=2.0; extra == "dev"
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Provides-Extra: audio
Requires-Dist: pyaudio>=0.2.13; extra == "audio"
Requires-Dist: soundfile>=0.12.0; extra == "audio"
Provides-Extra: all
Requires-Dist: talklabs[audio,dev]; extra == "all"
Dynamic: author
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

# 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

```bash
pip install talklabs
```

## Uso Rápido

### 1. Geração Simples (Síncrona)

```python
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!)

```python
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)

```python
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)

```python
# 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 sintetizar
  - `voice`: 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.0
  - `voice_settings`: Configurações opcionais
  - `incremental`: Se True, envia palavra por palavra - padrão: False
  - `word_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

```python
# 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) - Feminina
- `adam_rocha` - Português (BR) - Masculina
- `maria_silva` - Português (PT) - Feminina
- `joao_santos` - Português (PT) - Masculina

## Arquitetura do Streaming Redis

### Como Funciona

1. **spaCy NLP**: Texto é segmentado em sentenças naturais
2. **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
3. **Producer/Consumer**: TTS processa chunks em paralelo enquanto texto ainda está sendo enviado
4. **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

```python
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

```python
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

```python
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:

```python
# 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:
```bash
curl https://api.talklabs.com.br/health
```

### Latência alta no streaming

1. Use `stream_redis()` ao invés de `generate_stream()`
2. Verifique conexão Redis (deve estar em localhost ou baixa latência)
3. 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.BytesIO` para 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**
