Skip to main content

Official Python SDK for SakuraSpeech TTS API

Project description

SakuraSpeech Python SDK

Official Python SDK for the SakuraSpeech TTS API.

Installation

pip install sakuraspeech

Quick Start

from sakuraspeech import SakuraSpeech

client = SakuraSpeech(api_key="sk_live_...")

# Synthesize text to speech
audio = client.tts.synthesize(text="こんにちは、世界!")
audio.save("output.mp3")
print(f"Duration: {audio.duration}s, Size: {audio.size} bytes")

Configuration

client = SakuraSpeech(
    api_key="sk_live_...",
    base_url="https://api.sakuraspeech.jp",  # default
    timeout=60.0,            # seconds
    max_retries=2,           # retry on 429/503/network errors
    default_voice="kanon-sakura",
    default_format="mp3",
)

TTS (Text-to-Speech)

Synthesize

audio = client.tts.synthesize(
    text="こんにちは",
    voice="kanon-sakura",
    emotion="happy",
    speed=1.0,        # 0.5–2.0
    pitch=1.0,        # 0.5–2.0
    volume=1.0,       # 0.0–1.0
    format="mp3",     # mp3, wav, ogg
    sample_rate=44100, # 44100 のみ対応
)
audio.save("output.mp3")
print(audio.content)         # bytes
print(audio.duration)        # float (seconds)
print(audio.characters_used) # int
print(audio.request_id)      # str

Batch Synthesis

# Create a batch job
job = client.tts.batch_create(
    items=[
        {"id": "1", "text": "おはようございます"},
        {"id": "2", "text": "こんばんは", "voice": "kanon-sakura", "emotion": "happy"},
    ],
    format="mp3",
    webhook_url="https://example.com/webhook",
)
print(f"Batch ID: {job.batch_id}, Status: {job.status}")

# Poll until complete
completed = client.tts.batch_poll(job.batch_id, interval=2.0, timeout=300.0)
for result in completed.results:
    print(f"  {result.id}: {result.status}")

Voices

List Preset Voices

voice_list = client.voices.list()
for v in voice_list.voices:
    print(f"{v.id}: {v.name} ({v.gender}) - emotions: {v.emotions}")

Preview a Voice

preview = client.voices.preview("kanon-sakura")
preview.save("preview.wav")

Voice Cloning

# Clone from a file path
result = client.voices.clone(
    audio="reference.wav",
    name="My Custom Voice",
    description="A friendly female voice",
)
print(f"Custom voice ID: {result.custom_voice_id}")

# Use the cloned voice
audio = client.tts.synthesize(
    text="カスタムボイスのテスト",
    voice=f"custom:{result.custom_voice_id}",
)

Manage Custom Voices

# List custom voices
custom_voices = client.voices.custom_list()

# Get specific custom voice
voice = client.voices.custom_get("voice-id")

# Delete a custom voice
client.voices.custom_delete("voice-id")

User Dictionary

# List entries
entries = client.dictionary.list()

# Add entries
result = client.dictionary.add([
    {"word": "東京", "reading": "トウキョウ"},
    {"word": "SakuraSpeech", "reading": "サクラスピーチ", "accent": "4"},
])
print(f"Added {result.added} entries")

# Delete entry
client.dictionary.delete("entry-id")

Usage

usage = client.usage.get()
print(f"Plan: {usage.plan}")
print(f"Characters: {usage.characters.used}/{usage.characters.limit}")
print(f"Requests today: {usage.requests.today}")

Webhooks

# Create a webhook
webhook = client.webhooks.create(
    url="https://example.com/webhook",
    events=["batch.completed"],
)
print(f"Webhook ID: {webhook.id}, Secret: {webhook.secret}")

# List webhooks
webhooks = client.webhooks.list()

# Delete a webhook
client.webhooks.delete("webhook-id")

Async Usage

import asyncio
from sakuraspeech import AsyncSakuraSpeech

async def main():
    async with AsyncSakuraSpeech(api_key="sk_live_...") as client:
        audio = await client.tts.synthesize(text="非同期でこんにちは")
        audio.save("async_output.mp3")

        # Parallel requests
        results = await asyncio.gather(
            client.tts.synthesize(text="文章1"),
            client.tts.synthesize(text="文章2"),
            client.tts.synthesize(text="文章3"),
        )
        for i, r in enumerate(results):
            r.save(f"parallel_{i}.mp3")

asyncio.run(main())

Error Handling

from sakuraspeech import (
    SakuraSpeech,
    AuthenticationError,
    RateLimitError,
    NotFoundError,
    APIError,
)

client = SakuraSpeech(api_key="sk_live_...")

try:
    audio = client.tts.synthesize(text="テスト")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after_seconds}s")
except NotFoundError:
    print("Resource not found")
except APIError as e:
    print(f"API error: {e.code} ({e.status_code}): {e}")

Exception Hierarchy

SakuraSpeechError (base)
├── APIError (4xx/5xx, has code, status_code, request_id)
│   ├── AuthenticationError (401)
│   ├── PermissionError (403)
│   ├── NotFoundError (404)
│   ├── RateLimitError (429, retry_after_seconds)
│   ├── InternalServerError (500)
│   └── ServiceUnavailableError (503)
├── ConnectionError
└── TimeoutError

Requirements

  • Python >= 3.9
  • httpx >= 0.25.0

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sakuraspeech-0.1.0.tar.gz (34.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sakuraspeech-0.1.0-py3-none-any.whl (20.7 kB view details)

Uploaded Python 3

File details

Details for the file sakuraspeech-0.1.0.tar.gz.

File metadata

  • Download URL: sakuraspeech-0.1.0.tar.gz
  • Upload date:
  • Size: 34.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for sakuraspeech-0.1.0.tar.gz
Algorithm Hash digest
SHA256 44512e353ace89708dfcf2814941b7758dcf827d3956f4575c18548430a842f1
MD5 5613c1cb03764241640e10f6ab3b772e
BLAKE2b-256 af40f189a25f81ad2934e17b009d7022c533c32fe66d937dbb7937e3e2b1b493

See more details on using hashes here.

File details

Details for the file sakuraspeech-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: sakuraspeech-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 20.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for sakuraspeech-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 23df689e2e86258f6711eb41ce8d95aae0a02bada255c65e3c000b54b33f7813
MD5 0f9f1e55b7d717092f205f214e04cc53
BLAKE2b-256 caf636c319bcd2ac245300ae88af08a8e235c0e89181a4b4aca78a349575d492

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page