메인 콘텐츠로 건너뛰기

패키지

타입캐스트 Python SDK

소스 코드

타입캐스트 Python SDK 소스 코드

설치

pip를 사용하여 타입캐스트 Python SDK를 설치하세요:
pip install --upgrade typecast-python
패키지는 typecast-python으로 설치되지만, typecast로 임포트합니다.
버전 0.1.5 이상이 설치되어 있는지 확인하세요. pip show typecast-python으로 버전을 확인할 수 있습니다. 이전 버전이 있다면 pip install --upgrade typecast-python을 실행하여 업데이트하세요.

빠른 시작

텍스트를 음성으로 변환하는 간단한 예제입니다:
from typecast import Typecast
from typecast.models import TTSRequest

# 클라이언트 초기화
client = Typecast(api_key="YOUR_API_KEY")

# 텍스트를 음성으로 변환
response = client.text_to_speech(TTSRequest(
    text="Hello there! I'm your friendly text-to-speech agent.",
    model="ssfm-v30",
    voice_id="tc_672c5f5ce59fac2a48faeaee"
))

# 오디오 파일 저장
with open('output.wav', 'wb') as f:
    f.write(response.audio_data)

print(f"Duration: {response.duration}s, Format: {response.format}")

기능

타입캐스트 Python SDK는 텍스트 음성 변환을 위한 강력한 기능을 제공합니다:
  • 다중 음성 모델: ssfm-v30(최신) 및 ssfm-v21 AI 음성 모델 지원
  • 다국어 지원: 영어, 한국어, 스페인어, 일본어, 중국어 등 37개 언어 지원
  • 감정 조절: 감정 프리셋(normal, happy, sad, angry, whisper, toneup, tonedown) 또는 스마트 문맥 인식 추론
  • 오디오 사용자 정의: 볼륨(0-200), 피치(-12 ~ +12 반음), 템포(0.5x ~ 2.0x), 형식(WAV/MP3) 제어
  • 비동기 지원: 고성능 애플리케이션을 위한 내장 비동기 클라이언트
  • 캐릭터 탐색: 모델, 성별, 나이, 사용 사례별 필터링이 가능한 V2 Voices API
  • 타입 힌트: Pydantic 모델을 사용한 완전한 타입 주석

설정

환경 변수를 사용하거나 클라이언트에 직접 전달하여 API 키를 구성할 수 있습니다:
export TYPECAST_API_KEY="your-api-key-here"

고급 사용법

감정 제어 (ssfm-v30)

ssfm-v30은 두 가지 감정 제어 모드를 제공합니다: 프리셋스마트.
AI가 문맥에서 감정을 추론하도록 합니다:
from typecast import Typecast
from typecast.models import TTSRequest, SmartPrompt

client = Typecast()

response = client.text_to_speech(TTSRequest(
    text="Everything is going to be okay.",
    model="ssfm-v30",
    voice_id="tc_672c5f5ce59fac2a48faeaee",
    prompt=SmartPrompt(
        emotion_type="smart",
        previous_text="I just got the best news!",  # 선택적 문맥
        next_text="I can't wait to celebrate!"      # 선택적 문맥
    )
))

음성 조절

볼륨, 피치, 템포 및 출력 형식을 제어합니다:
from typecast import Typecast
from typecast.models import TTSRequest, Output

client = Typecast()

response = client.text_to_speech(TTSRequest(
    text="Customized audio output!",
    model="ssfm-v30",
    voice_id="tc_672c5f5ce59fac2a48faeaee",
    output=Output(
        volume=120,          # 범위: 0 ~ 200 (기본값: 100)
        audio_pitch=2,       # 범위: -12 ~ +12 반음
        audio_tempo=1.2,     # 범위: 0.5x ~ 2.0x
        audio_format="mp3"   # 옵션: wav, mp3
    ),
    seed=42                  # 재현 가능한 결과를 위해
))

캐릭터 탐색 (V2 API)

향상된 메타데이터로 사용 가능한 캐릭터를 나열하고 필터링합니다:
from typecast import Typecast
from typecast.models import VoicesV2Filter, TTSModel, GenderEnum, AgeEnum

client = Typecast()

# 모든 음성 가져오기
voices = client.voices_v2()

# 기준으로 필터링
filtered = client.voices_v2(VoicesV2Filter(
    model=TTSModel.SSFM_V30,
    gender=GenderEnum.FEMALE,
    age=AgeEnum.YOUNG_ADULT
))

# 음성 정보 표시
for voice in voices:
    print(f"ID: {voice.voice_id}, Name: {voice.voice_name}")
    print(f"Gender: {voice.gender}, Age: {voice.age}")
    print(f"Models: {', '.join(m.version.value for m in voice.models)}")
    print(f"Use cases: {voice.use_cases}")

비동기 클라이언트

고성능 애플리케이션의 경우 비동기 클라이언트를 사용하세요:
import asyncio
from typecast import AsyncTypecast
from typecast.models import TTSRequest

async def main():
    async with AsyncTypecast() as client:
        response = await client.text_to_speech(TTSRequest(
            text="Hello from async!",
            model="ssfm-v30",
            voice_id="tc_672c5f5ce59fac2a48faeaee"
        ))

        with open('async_output.wav', 'wb') as f:
            f.write(response.audio_data)

asyncio.run(main())

지원 언어

권장: 타입 안전한 언어 선택을 위해 LanguageCode enum을 사용하세요. ISO 639-3 코드를 문자열로 전달할 수도 있습니다 (예: "eng"). SDK는 ISO 639-3 코드로 37개 언어를 지원합니다:
언어코드언어코드언어코드
영어eng일본어jpn우크라이나어ukr
한국어kor그리스어ell인도네시아어ind
스페인어spa타밀어tam덴마크어dan
독일어deu타갈로그어tgl스웨덴어swe
프랑스어fra핀란드어fin말레이어msa
이탈리아어ita중국어zho체코어ces
폴란드어pol슬로바키아어slk포르투갈어por
네덜란드어nld아랍어ara불가리아어bul
러시아어rus크로아티아어hrv루마니아어ron
벵골어ben힌디어hin헝가리어hun
민난어nan노르웨이어nor펀자브어pan
태국어tha터키어tur베트남어vie
광둥어yue
타입 안전한 언어 선택을 위해 LanguageCode enum을 사용하세요:
from typecast.models import TTSRequest, LanguageCode

response = client.text_to_speech(TTSRequest(
    text="Hello",
    model="ssfm-v30",
    voice_id="tc_672c5f5ce59fac2a48faeaee",
    language=LanguageCode.ENG
))

오류 처리

SDK는 다양한 HTTP 상태 코드에 대한 특정 예외를 제공합니다:
from typecast import (
    Typecast,
    TypecastError,
    BadRequestError,
    UnauthorizedError,
    PaymentRequiredError,
    NotFoundError,
    UnprocessableEntityError,
    RateLimitError,
    InternalServerError,
)

try:
    response = client.text_to_speech(request)
except UnauthorizedError:
    print("Invalid API key")
except PaymentRequiredError:
    print("Insufficient credits")
except RateLimitError:
    print("Rate limit exceeded - please try again later")
except TypecastError as e:
    print(f"Error {e.status_code}: {e.message}")
예외상태 코드설명
BadRequestError400잘못된 요청 파라미터
UnauthorizedError401잘못되거나 누락된 API 키
PaymentRequiredError402크레딧 부족
NotFoundError404리소스를 찾을 수 없음
UnprocessableEntityError422유효성 검사 오류
RateLimitError429요청 한도 초과
InternalServerError500서버 오류