0.1.10 • Published 6 months ago

@duran.ai/tsetsen v0.1.10

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

Tsetsen TTS Node.js SDK

A Node.js SDK for the Tsetsen Text-to-Speech API, providing a simple interface for generating high-quality Mongolian speech from text.

Монгол хэл дээрх гарын авлагыг доор харна уу.

Installation

npm i @duran.ai/tsetsen

Prerequisites

Quick Start

import { Client, RequestStatus } from '@duran.ai/tsetsen';

// Initialize the client with your API key
const client = new Client({
  apiKey: 'your-api-key',
  // Optional: Specify a timeout for requests
  timeout: 60000, // 60 seconds
});

async function main() {
  try {
    // List available Mongolian voices
    const voicesResponse = await client.listVoices({ version: 'beta-v0.1' });
    console.log(`Available Mongolian voices: ${voicesResponse.voices.length}`);
    
    // Select a voice to use
    const selectedVoice = voicesResponse.voices[0];
    console.log(`Using voice: ${selectedVoice.name} (${selectedVoice.id})`);
    
    // Generate Mongolian speech
    const response = await client.generateSpeech({
      text: 'Сайн байна уу! Би Цэцэн хиймэл оюун ухаан системийн дуу хоолой.',
      voiceId: selectedVoice.id,
      version: 'beta-v0.1'
    });
    console.log(`Generation request submitted: ${response.requestId}`);
    
    // Wait for completion with proper error handling
    try {
      const result = await client.waitForCompletion(response.requestId, {
        timeout: 120000,      // 2 minutes timeout for longer texts
        pollInterval: 1000    // Check every second
      });
      
      if (result.status === RequestStatus.COMPLETED) {
        console.log(`Audio URL: ${result.audioUrl}`);
        
        // Display metrics if available
        if (result.metrics) {
          console.log(`Audio length: ${result.metrics.audioLength} seconds`);
          console.log(`Processing time: ${result.metrics.processingTime} ms`);
          console.log(`Credits used: ${result.metrics.creditsUsed}`);
        }
      } else {
        console.log(`Generation failed: ${result.errorMessage}`);
      }
    } catch (error) {
      if (error.code === 'timeout') {
        console.error('Request timed out. The operation might still complete on the server.');
      } else {
        throw error; // rethrow other errors
      }
    }
  } catch (error) {
    console.error('Error:', error.message);
    // Handle specific error types
    if (error.code) {
      console.error(`Error code: ${error.code}`);
    }
  } finally {
    // Always close the client when done
    client.close();
  }
}

main();

Streaming Speech

In addition to the asynchronous speech generation with generateSpeech, the SDK now supports real-time streaming of speech using streamSpeech. This allows you to receive and process audio chunks as they are generated, without waiting for the entire audio to be processed.

Streaming Limitations

  • Streaming is only supported with the beta-v0.2 model version
  • Rate limit: 1 request per minute (free tier)
  • Maximum streaming duration: 5 minutes
  • Audio format: 24,000Hz, 16-bit, mono

Basic Streaming Example

import { Client, RequestStatus } from '@duran.ai/tsetsen';
import * as fs from 'fs';

// Initialize the client
const client = new Client({
  apiKey: 'your-api-key' 
});

// Stream speech with callbacks
const streamController = client.streamSpeech({
  text: 'Сайн байна уу! Энэ бол Цэцэн дуу хоолойны шууд урсгал юм.',
  voiceId: 'voice-id',
  version: 'beta-v0.2', // Required for streaming
  
  // Receive audio chunks as they arrive
  onData: (audioChunk, isFinal) => {
    console.log(`Received chunk: ${audioChunk.length} bytes, final: ${isFinal}`);
    
    // Process audio chunks in real-time
    // For example, you could send to a WebSocket, play it, etc.
  },
  
  // Called when streaming is complete
  onComplete: () => {
    console.log('Streaming completed successfully');
    client.close();
  },
  
  // Called if an error occurs
  onError: (error) => {
    console.error('Streaming error:', error);
    client.close();
  }
});

// You can cancel the stream at any time
// streamController.cancel();

Saving Stream to File

import { Client } from '@duran.ai/tsetsen';

// Initialize the client
const client = new Client({
  apiKey: 'your-api-key'
});

// Stream speech directly to a file
const streamController = client.streamSpeech({
  text: 'Сайн байна уу! Энэ бол Цэцэн дуу хоолойны шууд урсгал юм.',
  voiceId: 'voice-id',
  outputFile: 'output.raw', // Save to file (raw 16-bit PCM format)
  
  onComplete: () => {
    console.log('Audio saved to output.raw');
    client.close();
  },
  
  onError: (error) => {
    console.error('Error:', error);
    client.close();
  }
});

Playing Audio in Real-time

To play the audio in real-time, you can use an audio library like speaker or node-aplay. Here's an example using the speaker package:

import { Client } from '@duran.ai/tsetsen';
import Speaker from 'speaker';

// Install with: npm install speaker

// Initialize the client
const client = new Client({
  apiKey: 'your-api-key'
});

// Set up the speaker
const speaker = new Speaker({
  channels: 1,          // mono
  bitDepth: 16,         // 16-bit samples
  sampleRate: 24000,    // 24,000 Hz sample rate
  signed: true          // signed data (true for PCM16)
});

// Stream speech directly to the speaker
const streamController = client.streamSpeech({
  text: 'Сайн байна уу! Энэ бол Цэцэн дуу хоолойны шууд урсгал юм.',
  voiceId: 'voice-id',
  
  onData: (chunk, isFinal) => {
    if (chunk.length > 0) {
      speaker.write(chunk);
    }
    
    if (isFinal) {
      // End the speaker stream when done
      setTimeout(() => speaker.end(), 1000);
    }
  },
  
  onComplete: () => {
    console.log('Streaming completed');
    client.close();
  },
  
  onError: (error) => {
    console.error('Error:', error);
    speaker.end();
    client.close();
  }
});

Converting Raw Audio

The streaming API provides raw PCM audio data. To convert it to a common format like WAV or MP3, you can use FFmpeg or a library like wav:

import { Client } from '@duran.ai/tsetsen';
import * as wav from 'wav';
import * as fs from 'fs';

// Install with: npm install wav

// Initialize the client
const client = new Client({
  apiKey: 'your-api-key'
});

// Create a WAV file writer
const fileWriter = new wav.FileWriter('output.wav', {
  channels: 1,
  sampleRate: 24000,
  bitDepth: 16
});

// Stream speech to WAV file
const streamController = client.streamSpeech({
  text: 'Сайн байна уу! Энэ бол Цэцэн дуу хоолойны шууд урсгал юм.',
  voiceId: 'voice-id',
  
  onData: (chunk, isFinal) => {
    if (chunk.length > 0) {
      fileWriter.write(chunk);
    }
    
    if (isFinal) {
      fileWriter.end();
    }
  },
  
  onComplete: () => {
    console.log('WAV file created at output.wav');
    client.close();
  },
  
  onError: (error) => {
    console.error('Error:', error);
    fileWriter.end();
    client.close();
  }
});

Notes on Streaming

  • The streaming audio is provided as raw 16-bit PCM data
  • The sample rate is fixed at 24,000 Hz for the current version
  • Audio is mono (single channel)
  • No additional audio headers are included in the chunks
  • Rate limits apply: free tier is limited to 1 request per minute

Features

  • Generate high-quality Mongolian speech from text
  • List available Mongolian voices
  • Check generation status
  • Get user balance
  • Robust error handling and retries
  • TypeScript support

API Reference

Client

The main entry point to the Tsetsen TTS API.

import { Client } from '@duran.ai/tsetsen';

const client = new Client(options);

Constructor Options

OptionTypeDefaultDescription
apiKeystringFrom env varYour Tsetsen API key
timeoutnumber30000Request timeout in milliseconds
securebooleantrueWhether to use TLS for the connection
maxRetriesnumber3Maximum number of retries for failed requests
loggerLoggerConsoleLogger to use

Methods

listVoices(options?): Promise<ListVoicesResponse>

Lists available Mongolian voices for TTS.

const { voices } = await client.listVoices({ 
  version: 'beta-v0.1', // Required: API version
  skipCache: false // Optional: Skip cache
});

// Example voice object
console.log(voices[0]);
// {
//   id: 'voice1',
//   name: 'Voice Name',
//   gender: Gender.MALE,
//   language: 'mn'
// }
generateSpeech(options): Promise<GenerateSpeechResponse>

Generates Mongolian speech from text.

const response = await client.generateSpeech({
  text: 'Сайн байна уу!', // Mongolian text
  voiceId: 'voice-id',
  speed: 1.0, // Optional: Speech speed multiplier (default: 1.0)
  version: 'beta-v0.1' // Required: API version
});

console.log(response);
// {
//   requestId: 'req-123',
//   status: RequestStatus.PENDING
// }
checkStatus(requestId): Promise<CheckStatusResponse>

Checks the status of a speech generation request.

const status = await client.checkStatus('req-123');

console.log(status);
// {
//   requestId: 'req-123',
//   status: RequestStatus.COMPLETED,
//   audioUrl: 'https://example.com/audio.mp3',
//   metrics: {
//     queueTime: 100, // Time in queue (ms)
//     processingTime: 2000, // Processing time (ms)
//     totalTime: 2100, // Total time (ms)
//     audioLength: 3.5, // Audio length (seconds)
//     creditsUsed: 50, // Credits used
//     characterCount: 100 // Number of characters processed
//   }
// }
getUserBalance(): Promise<GetUserBalanceResponse>

Gets the user's credit balance.

const balance = await client.getUserBalance();

console.log(balance);
// {
//   credits: 1000
// }
waitForCompletion(requestId, options?): Promise<CheckStatusResponse>

Waits for a speech generation request to complete.

const result = await client.waitForCompletion('req-123', {
  timeout: 60000, // Optional: Maximum time to wait (ms)
  pollInterval: 1000 // Optional: Time between status checks (ms)
});

console.log(result);
// Same as checkStatus result when complete
close(): void

Closes the client and releases resources. Call this when you're done with the client.

client.close();

Enums

RequestStatus

Status of a TTS request.

enum RequestStatus {
  UNSPECIFIED = 0,
  PENDING = 1,
  PROCESSING = 2,
  COMPLETED = 3,
  FAILED = 4
}

Gender

Gender of a voice.

enum Gender {
  UNSPECIFIED = 0,
  MALE = 1,
  FEMALE = 2
}

Error Handling

The SDK provides specialized error classes for different error conditions.

import { 
  TsetsenError, 
  AuthenticationError,
  ResourceNotFoundError 
} from '@duran.ai/tsetsen';

try {
  await client.generateSpeech({ 
    text: 'Сайн байна уу!',
    voiceId: 'voice-id',
    version: 'beta-v0.1'
  });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Authentication failed:', error.message);
  } else if (error instanceof ResourceNotFoundError) {
    console.error('Resource not found:', error.message);
  } else if (error instanceof TsetsenError) {
    console.error('API error:', error.message, error.code);
    console.error('Details:', error.details);
  } else {
    console.error('Unexpected error:', error);
  }
}

Error classes:

  • TsetsenError: Base error class
  • AuthenticationError: Authentication failed
  • PermissionDeniedError: Permission denied
  • InvalidRequestError: Invalid request parameters
  • RateLimitExceededError: Rate limit exceeded
  • InsufficientCreditsError: Insufficient credits
  • ResourceNotFoundError: Resource not found
  • ServiceUnavailableError: Service unavailable
  • ConnectionError: Connection error
  • TimeoutError: Request timed out
  • ServerError: Server error

Environment Variables

  • TSETSEN_API_KEY: API key for authentication (alternative to passing in constructor)

Testing Your Integration

Here's a simple test to verify your integration is working correctly:

import { Client } from '@duran.ai/tsetsen';

async function testTsetsenIntegration() {
  const client = new Client({
    apiKey: process.env.TSETSEN_API_KEY
  });

  try {
    // Test Voice Listing
    const voices = await client.listVoices({ version: 'beta-v0.1' });
    console.log(`✓ Successfully listed ${voices.voices.length} voices`);

    // Test User Balance
    const balance = await client.getUserBalance();
    console.log(`✓ User has ${balance.credits} credits`);

    console.log('All tests passed!');
  } catch (error) {
    console.error('Integration test failed:', error);
  } finally {
    client.close();
  }
}

testTsetsenIntegration();

Монгол хэл дээрх гарын авлага

Цэцэн Текст-Яриа-Хувиргах (TTS) Node.js SDK нь Монгол хэл дээрх өндөр чанартай яриа үүсгэх энгийн интерфейсийг санал болгодог.

Суулгах

npm install @duran.ai/tsetsen

Шаардлага

  • Node.js 14.x эсвэл түүнээс дээш хувилбар
  • Цэцэн API түлхүүр (developer.tsetsen.ai хаягаар бүртгүүлнэ)

Хурдан эхлэх

import { Client, RequestStatus } from '@duran.ai/tsetsen';

// Initialize the client with your API key
const client = new Client({
  apiKey: 'your-api-key',
  // Optional: Specify a timeout for requests
  timeout: 60000, // 60 seconds
});

async function main() {
  try {
    // List available Mongolian voices
    const voicesResponse = await client.listVoices({ version: 'beta-v0.1' });
    console.log(`Available Mongolian voices: ${voicesResponse.voices.length}`);
    
    // Select a voice to use
    const selectedVoice = voicesResponse.voices[0];
    console.log(`Using voice: ${selectedVoice.name} (${selectedVoice.id})`);
    
    // Generate Mongolian speech
    const response = await client.generateSpeech({
      text: 'Сайн байна уу! Би Цэцэн хиймэл оюун ухаан системийн дуу хоолой.',
      voiceId: selectedVoice.id,
      version: 'beta-v0.1'
    });
    console.log(`Generation request submitted: ${response.requestId}`);
    
    // Wait for completion with proper error handling
    try {
      const result = await client.waitForCompletion(response.requestId, {
        timeout: 120000,      // 2 minutes timeout for longer texts
        pollInterval: 1000    // Check every second
      });
      
      if (result.status === RequestStatus.COMPLETED) {
        console.log(`Audio URL: ${result.audioUrl}`);
        
        // Display metrics if available
        if (result.metrics) {
          console.log(`Audio length: ${result.metrics.audioLength} seconds`);
          console.log(`Processing time: ${result.metrics.processingTime} ms`);
          console.log(`Credits used: ${result.metrics.creditsUsed}`);
        }
      } else {
        console.log(`Generation failed: ${result.errorMessage}`);
      }
    } catch (error) {
      if (error.code === 'timeout') {
        console.error('Request timed out. The operation might still complete on the server.');
      } else {
        throw error; // rethrow other errors
      }
    }
  } catch (error) {
    console.error('Error:', error.message);
    // Handle specific error types
    if (error.code) {
      console.error(`Error code: ${error.code}`);
    }
  } finally {
    // Always close the client when done
    client.close();
  }
}

main();

Яриа Streaming

generateSpeech ашиглан яриаг асинхрон үүсгэхээс гадна SDK нь одоо streamSpeech ашиглан бодит цагийн горимд яриаг streaming хийх боломжтой болсон. Энэ нь бүхэл аудио файл үүсэхийг хүлээх шаардлагагүйгээр, аудио хэсгүүдийг үүсгэх үед нь хүлээн авах, боловсруулах боломжийг олгодог.

Streaming хязгаарлалтууд

  • Streaming зөвхөн beta-v0.2 загвартай ажилладаг
  • Хүсэлтийн хязгаарлалт: Нэг минутанд 1 хүсэлт (үнэгүй эрх)
  • Streaming-ийн хамгийн их үргэлжлэх хугацаа: 5 минут
  • Аудио формат: 24,000Гц, 16-бит, моно

Энгийн Streaming жишээ

import { Client, RequestStatus } from '@duran.ai/tsetsen';
import * as fs from 'fs';

// Client үүсгэх
const client = new Client({
  apiKey: 'таны-api-түлхүүр' 
});

// Коллбэкүүдтэй яриаг streaming хийх
const streamController = client.streamSpeech({
  text: 'Сайн байна уу! Энэ бол Цэцэн дуу хоолойны шууд урсгал юм.',
  voiceId: 'дуу-хоолойн-id',
  version: 'beta-v0.2', // Streaming-д заавал шаардлагатай
  
  // Аудио хэсгүүдийг ирэх үед хүлээн авах
  onData: (audioChunk, isFinal) => {
    console.log(`Хүлээн авсан хэсэг: ${audioChunk.length} байт, төгсгөл: ${isFinal}`);
    
    // Аудио хэсгүүдийг бодит цагийн горимд боловсруулах
    // Жишээ нь: WebSocket руу илгээх, тоглуулах г.м.
  },
  
  // Streaming дуусахад дуудагдана
  onComplete: () => {
    console.log('Streaming амжилттай дууслаа');
    client.close();
  },
  
  // Алдаа гарвал дуудагдана
  onError: (error) => {
    console.error('Streaming алдаа:', error);
    client.close();
  }
});

// Та streaming-ийг дурын үед цуцлах боломжтой
// streamController.cancel();

Streaming-ийг файлд хадгалах

import { Client } from '@duran.ai/tsetsen';

// Client үүсгэх
const client = new Client({
  apiKey: 'таны-api-түлхүүр'
});

// Яриаг шууд файлд streaming хийх
const streamController = client.streamSpeech({
  text: 'Сайн байна уу! Энэ бол Цэцэн дуу хоолойны шууд урсгал юм.',
  voiceId: 'дуу-хоолойн-id',
  outputFile: 'output.raw', // Файлд хадгалах (түүхий 16-бит PCM формат)
  
  onComplete: () => {
    console.log('Аудио output.raw файлд хадгалагдлаа');
    client.close();
  },
  
  onError: (error) => {
    console.error('Алдаа:', error);
    client.close();
  }
});

Аудиог бодит цагийн горимд тоглуулах

Аудиог бодит цагийн горимд тоглуулахын тулд та speaker эсвэл node-aplay гэх мэт аудио сан ашиглаж болно. speaker пакет ашигласан жишээ:

import { Client } from '@duran.ai/tsetsen';
import Speaker from 'speaker';

// Суулгах: npm install speaker

// Client үүсгэх
const client = new Client({
  apiKey: 'таны-api-түлхүүр'
});

// Speaker тохируулах
const speaker = new Speaker({
  channels: 1,          // моно
  bitDepth: 16,         // 16-бит сэмпл
  sampleRate: 24000,    // 24,000 Гц сэмпл давтамж
  signed: true          // signed өгөгдөл (PCM16-д зориулсан)
});

// Яриаг шууд speaker руу streaming хийх
const streamController = client.streamSpeech({
  text: 'Сайн байна уу! Энэ бол Цэцэн дуу хоолойны шууд урсгал юм.',
  voiceId: 'дуу-хоолойн-id',
  
  onData: (chunk, isFinal) => {
    if (chunk.length > 0) {
      speaker.write(chunk);
    }
    
    if (isFinal) {
      // Дууссан үед speaker урсгалыг хаах
      setTimeout(() => speaker.end(), 1000);
    }
  },
  
  onComplete: () => {
    console.log('Streaming дууслаа');
    client.close();
  },
  
  onError: (error) => {
    console.error('Алдаа:', error);
    speaker.end();
    client.close();
  }
});

Түүхий аудиог хөрвүүлэх

Streaming API нь түүхий PCM аудио өгөгдөл өгдөг. Түүнийг WAV эсвэл MP3 гэх мэт түгээмэл форматад хувиргахын тулд та FFmpeg эсвэл wav гэх мэт сан ашиглаж болно:

import { Client } from '@duran.ai/tsetsen';
import * as wav from 'wav';
import * as fs from 'fs';

// Суулгах: npm install wav

// Client үүсгэх
const client = new Client({
  apiKey: 'таны-api-түлхүүр'
});

// WAV файл үүсгэгч үүсгэх
const fileWriter = new wav.FileWriter('output.wav', {
  channels: 1,
  sampleRate: 24000,
  bitDepth: 16
});

// Яриаг WAV файлд streaming хийх
const streamController = client.streamSpeech({
  text: 'Сайн байна уу! Энэ бол Цэцэн дуу хоолойны шууд урсгал юм.',
  voiceId: 'дуу-хоолойн-id',
  
  onData: (chunk, isFinal) => {
    if (chunk.length > 0) {
      fileWriter.write(chunk);
    }
    
    if (isFinal) {
      fileWriter.end();
    }
  },
  
  onComplete: () => {
    console.log('WAV файл output.wav-д үүсгэгдлээ');
    client.close();
  },
  
  onError: (error) => {
    console.error('Алдаа:', error);
    fileWriter.end();
    client.close();
  }
});

Streaming-ийн тухай тэмдэглэлүүд

  • Streaming аудио нь түүхий 16-бит PCM өгөгдөл хэлбэрээр өгөгддөг
  • Сэмпл давтамж нь одоогийн хувилбарт 24,000 Гц-д тогтмол байдаг
  • Аудио нь моно (ганц суваг)
  • Аудио хэсгүүдэд нэмэлт аудио толгой хэсэг (headers) багтаагүй
  • Хүсэлтийн хязгаарлалт үйлчилнэ: үнэгүй эрхийн хувьд нэг минутанд 1 хүсэлтээр хязгаарлагдана

Боломжууд

  • Өндөр чанартай Монгол яриа үүсгэх
  • Боломжтой Монгол дуу хоолойнуудыг жагсаах
  • Үүсгэх хүсэлтийн статусыг шалгах
  • Хэрэглэгчийн балансыг харах
  • Найдвартай алдааны боловсруулалт ба дахин оролдлого
  • TypeScript дэмжлэг

API Лавлагаа

Клиент

Цэцэн TTS API-д хандах үндсэн цэг.

import { Client } from '@duran.ai/tsetsen';

const client = new Client(options);

Конструкторын Тохиргоо

ТохиргооТөрөлҮндсэн утгаТайлбар
apiKeystringОрчны хувьсагчаасТаны Цэцэн API түлхүүр
timeoutnumber30000Хүсэлтийн хүлээх хугацаа (миллисекунд)
securebooleantrueTLS холболт ашиглах эсэх
maxRetriesnumber3Алдаа гарсан үед дахин оролдох хамгийн их тоо
loggerLoggerConsoleЛог бичих механизм

Аргууд

listVoices(options?): Promise<ListVoicesResponse>

Боломжтой Монгол дуу хоолойнуудыг жагсаана.

const { voices } = await client.listVoices({ 
  version: 'beta-v0.1', // Шаардлагатай: API хувилбар
  skipCache: false // Сонголт: Кэшээс алгасах
});

// Дуу хоолойн обьектын жишээ
console.log(voices[0]);
// {
//   id: 'voice1',
//   name: 'Voice Name',
//   gender: Gender.MALE,
//   language: 'mn'
// }
generateSpeech(options): Promise<GenerateSpeechResponse>

Монгол текстээс яриа үүсгэнэ.

const response = await client.generateSpeech({
  text: 'Сайн байна уу!', // Монгол текст
  voiceId: 'voice-id',
  speed: 1.0, // Сонголт: Ярианы хурдны үржүүлэгч (үндсэн: 1.0)
  version: 'beta-v0.1' // Шаардлагатай: API хувилбар
});

console.log(response);
// {
//   requestId: 'req-123',
//   status: RequestStatus.PENDING
// }
checkStatus(requestId): Promise<CheckStatusResponse>

Яриа үүсгэх хүсэлтийн статусыг шалгана.

const status = await client.checkStatus('req-123');

console.log(status);
// {
//   requestId: 'req-123',
//   status: RequestStatus.COMPLETED,
//   audioUrl: 'https://example.com/audio.mp3',
//   metrics: {
//     queueTime: 100, // Дараалалд зарцуулсан хугацаа (мс)
//     processingTime: 2000, // Боловсруулалтын хугацаа (мс)
//     totalTime: 2100, // Нийт хугацаа (мс)
//     audioLength: 3.5, // Аудионы урт (секунд)
//     creditsUsed: 50, // Ашигласан кредит
//     characterCount: 100 // Тэмдэгтийн тоо
//   }
// }
getUserBalance(): Promise<GetUserBalanceResponse>

Хэрэглэгчийн кредит балансыг авна.

const balance = await client.getUserBalance();

console.log(balance);
// {
//   credits: 1000
// }
waitForCompletion(requestId, options?): Promise<CheckStatusResponse>

Яриа үүсгэх хүсэлт дуустал хүлээнэ.

const result = await client.waitForCompletion('req-123', {
  timeout: 60000, // Сонголт: Хүлээх хамгийн их хугацаа (мс)
  pollInterval: 1000 // Сонголт: Статус шалгах хоорондын хугацаа (мс)
});

console.log(result);
// checkStatus үр дүнтэй ижил
close(): void

Клиентийн холболтыг хаана. Ажил дуусахад заавал дуудна.

client.close();

Тоочлолууд (Enums)

RequestStatus

TTS хүсэлтийн статус.

enum RequestStatus {
  UNSPECIFIED = 0,
  PENDING = 1,
  PROCESSING = 2,
  COMPLETED = 3,
  FAILED = 4
}

Gender

Дуу хоолойн хүйс.

enum Gender {
  UNSPECIFIED = 0,
  MALE = 1,
  FEMALE = 2
}

Алдааны боловсруулалт

SDK нь өөр өөр нөхцөлд тохирсон тусгай алдааны ангиудыг санал болгодог.

import { 
  TsetsenError, 
  AuthenticationError,
  ResourceNotFoundError 
} from '@duran.ai/tsetsen';

try {
  await client.generateSpeech({ 
    text: 'Сайн байна уу!',
    voiceId: 'voice-id',
    version: 'beta-v0.1'
  });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Нэвтрэлтийн алдаа:', error.message);
  } else if (error instanceof ResourceNotFoundError) {
    console.error('Нөөц олдсонгүй:', error.message);
  } else if (error instanceof TsetsenError) {
    console.error('API алдаа:', error.message, error.code);
    console.error('Дэлгэрэнгүй:', error.details);
  } else {
    console.error('Тодорхойгүй алдаа:', error);
  }
}

Алдааны ангиуд:

  • TsetsenError: Үндсэн алдааны анги
  • AuthenticationError: Нэвтрэлтийн алдаа
  • PermissionDeniedError: Зөвшөөрөл хасагдсан
  • InvalidRequestError: Буруу хүсэлтийн параметр
  • RateLimitExceededError: Хүсэлтийн тоо хэтэрсэн
  • InsufficientCreditsError: Кредит хүрэлцээгүй
  • ResourceNotFoundError: Нөөц олдсонгүй
  • ServiceUnavailableError: Үйлчилгээ түр ажиллахгүй байна
  • ConnectionError: Холболтын алдаа
  • TimeoutError: Хүсэлт хугацаа хэтэрсэн
  • ServerError: Серверийн алдаа

Орчны хувьсагчид

  • TSETSEN_API_KEY: Нэвтрэх API түлхүүр (конструктор дээр дамжуулахын оронд)

Интеграцийг шалгах

Интеграцийн зөв ажиллагааг шалгах энгийн тест:

import { Client } from '@duran.ai/tsetsen';

async function testTsetsenIntegration() {
  const client = new Client({
    apiKey: process.env.TSETSEN_API_KEY
  });

  try {
    // Дуу хоолой жагсаалтыг шалгах
    const voices = await client.listVoices({ version: 'beta-v0.1' });
    console.log(`✓ Амжилттай ${voices.voices.length} дуу хоолой жагсаалаа`);

    // Хэрэглэгчийн балансыг шалгах
    const balance = await client.getUserBalance();
    console.log(`✓ Хэрэглэгч ${balance.credits} кредиттэй байна`);

    console.log('Бүх тестүүд амжилттай!');
  } catch (error) {
    console.error('Интеграцийн тест амжилтгүй:', error);
  } finally {
    client.close();
  }
}

testTsetsenIntegration();
0.1.10

6 months ago

0.1.8

7 months ago

0.1.7

7 months ago

0.1.6

7 months ago

0.1.5

7 months ago

0.1.4

7 months ago

0.1.3

7 months ago

0.1.2

7 months ago

0.1.1

7 months ago