JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 11
  • Score
    100M100P100Q66630F
  • License MIT

Node.js SDK for the Tsetsen, Mongolian Text-to-Speech API

Package Exports

  • @duran.ai/tsetsen
  • @duran.ai/tsetsen/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@duran.ai/tsetsen) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

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();

Note: Streaming audio is not supported yet but will be added very soon.

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

Option Type Default Description
apiKey string From env var Your Tsetsen API key
timeout number 30000 Request timeout in milliseconds
secure boolean true Whether to use TLS for the connection
maxRetries number 3 Maximum number of retries for failed requests
logger Logger Console Logger 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();

Анхааруулга: Стриминг аудио одоогоор дэмжигдээгүй байгаа боловч удахгүй нэмэгдэх болно.

Боломжууд

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

API Лавлагаа

Клиент

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

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

const client = new Client(options);

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

Тохиргоо Төрөл Үндсэн утга Тайлбар
apiKey string Орчны хувьсагчаас Таны Цэцэн API түлхүүр
timeout number 30000 Хүсэлтийн хүлээх хугацаа (миллисекунд)
secure boolean true TLS холболт ашиглах эсэх
maxRetries number 3 Алдаа гарсан үед дахин оролдох хамгийн их тоо
logger Logger Console Лог бичих механизм

Аргууд

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();