Skip to main content

Documentation Index

Fetch the complete documentation index at: https://sunbirdai.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

This guide provides production-ready Python examples for interacting with the Sunbird AI API.

Setup

First, install the requests library:
pip install requests

Basic Translation

import os
import requests
from typing import Dict, Any

# Load API token from environment
API_TOKEN = os.getenv("SUNBIRD_API_TOKEN")
BASE_URL = "https://api.sunbird.ai"

def translate_text(text: str, source: str, target: str) -> Dict[str, Any]:
    """
    Translate text between languages.
    
    Args:
        text: Text to translate
        source: Source language code (e.g., 'eng')
        target: Target language code (e.g., 'lug')
    
    Returns:
        Translation response dictionary
    """
    url = f"{BASE_URL}/tasks/nllb_translate"
    headers = {
        "Authorization": f"Bearer {API_TOKEN}",
        "Content-Type": "application/json"
    }
    payload = {
        "text": text,
        "source_language": source,
        "target_language": target
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.HTTPError as e:
        print(f"HTTP Error: {e}")
        print(f"Response: {e.response.text}")
        raise
    except Exception as e:
        print(f"Error: {e}")
        raise

# Example usage
if __name__ == "__main__":
    result = translate_text(
        text="Hello, how are you?",
        source="eng",
        target="lug"
    )
    print(f"Translation: {result['output']['translated_text']}")

Speech to Text with File Upload

def transcribe_audio(file_path: str) -> Dict[str, Any]:
    url = f"{BASE_URL}/tasks/stt"
    headers = {
        "Authorization": f"Bearer {API_TOKEN}"
    }
    
    with open(file_path, 'rb') as f:
        files = {'audio': f}
        response = requests.post(url, files=files, headers=headers)
        response.raise_for_status()
        return response.json()

Text to Speech

def generate_speech(text: str, speaker_id: int, output_file: str):
    url = f"{BASE_URL}/tasks/tts"
    headers = {
        "Authorization": f"Bearer {API_TOKEN}",
        "Content-Type": "application/json"
    }
    payload = {
        "text": text,
        "speaker_id": speaker_id
    }
    
    response = requests.post(url, json=payload, headers=headers)
    response.raise_for_status()
    
    data = response.json()
    audio_url = data['output']['audio_url']
    
    # Download the audio
    audio_response = requests.get(audio_url)
    with open(output_file, 'wb') as f:
        f.write(audio_response.content)
    print(f"Audio saved to {output_file}")