### Environment Setup and Dependencies Source: https://docs.palabra.ai/docs/streaming_api/realtime_stt Install required Python packages and configure environment variables before running the streaming client. ```bash pip install pyaudio websockets export PALABRA_API_KEY=... # from Step 1 export PALABRA_LANGUAGE=en # source language ``` -------------------------------- ### Install dependencies Source: https://docs.palabra.ai/docs/examples/python Install the required packages using uv or pip. ```bash # Using uv (recommended) uv venv && . .venv/bin/activate && uv sync # Or using pip pip install httpx livekit numpy sounddevice websockets ``` -------------------------------- ### Install LiveKit Client Source: https://docs.palabra.ai/docs/broadcaster/webrtc-input-and-outputs Command to install the necessary LiveKit client dependency. ```bash npm install livekit-client ``` -------------------------------- ### Run the example Source: https://docs.palabra.ai/docs/examples/python Execute the client script. ```bash python nanopalabra.py ``` -------------------------------- ### Example Listener Page URL Source: https://docs.palabra.ai/docs/broadcaster/api-listener-page A concrete example of a fully composed listener page URL. ```text https://app.palabra.ai/broadcast/1ea600ec-6b82-4844-86d4-9926bfa78e20/view?toLanguages=fr,bg,es-mx&fromLangs=en&isWebRTC=true ``` -------------------------------- ### Install Agora RTC SDK Source: https://docs.palabra.ai/docs/partner-integrations/agora Install the required Agora RTC SDK package via npm. ```bash npm install agora-rtc-sdk-ng ``` -------------------------------- ### Approve request cURL example Source: https://docs.palabra.ai/api/approve-a-pending-listener-request-organizer Example cURL request to approve a pending listener request. ```bash curl -L -X POST 'https://api.palabra.ai/saas/v2/event/:event_id/requests/:request_id/approve' \ -H 'Accept: application/json' ``` -------------------------------- ### Create streaming session with cURL Source: https://docs.palabra.ai/api/create-streaming-session Example request to create a session using cURL. ```bash curl -L -X POST 'https://api.palabra.ai/session-storage/session' \ -H 'Content-Type: application/json' \ -H 'Accept: application/json' ``` -------------------------------- ### Create Channel Request Source: https://docs.palabra.ai/api/create-a-new-channel Example cURL request to create a new channel. ```bash curl -L -X POST 'https://api.palabra.ai/saas/channel' \ -H 'Content-Type: application/json' \ -H 'Accept: application/json' ``` -------------------------------- ### Create a Session Request Source: https://docs.palabra.ai/docs/quick-start/webrtc Use these examples to authenticate and initialize a new session with the Palabra API. ```javascript const { data } = await axios.post( "https://api.palabra.ai/session-storage/session", { data: {}, }, { headers: { Authorization: "Bearer ", }, } ); ``` ```bash curl -X POST https://api.palabra.ai/session-storage/session \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "data": {} }' ``` -------------------------------- ### Connect to WebSocket with Python Source: https://docs.palabra.ai/docs/streaming_api/realtime_stt Example using the websockets library to establish a connection to the transcription stream. ```python import websockets url = ( "wss://api.palabra.ai/asr/v1/speech-to-text/stream" f"?token={api_key}&language=en&format=pcm_s16le&sample_rate=16000" ) ws = await websockets.connect(url) ``` -------------------------------- ### Upload glossary file with cURL Source: https://docs.palabra.ai/api/upload-glossary-file Example request for uploading a glossary file using cURL. ```bash curl -L -X POST 'https://api.palabra.ai/saas/glossary/:glossary_id/upload' \ -H 'Content-Type: multipart/form-data' \ -H 'Accept: application/json' ``` -------------------------------- ### Create Streaming Session Source: https://docs.palabra.ai/docs/streaming_api/session Request body and example for creating a new session to obtain connection credentials. ```json { "data": {} } ``` ```http POST /session-storage/session HTTP/1.1 Host: api.palabra.ai Content-Type: application/json Authorization: Bearer { "data": {} } ``` ```json { "ok": true, "data": { "publisher": "", "webrtc_url": "https://api.palabra.ai/stream/", "ws_url": "wss://api.palabra.ai/stream/control/", "intent": "api", "id": "session-id" } } ``` -------------------------------- ### Retrieve Sessions via cURL Source: https://docs.palabra.ai/api/get-user-sessions Example request to fetch user sessions using cURL. ```bash curl -L 'https://api.palabra.ai/session-storage/sessions' \ -H 'Accept: application/json' ``` -------------------------------- ### Fetch user voices with cURL Source: https://docs.palabra.ai/api/get-list-of-user-voices Example request to retrieve the list of voices using cURL. ```bash curl -L 'https://api.palabra.ai/saas/voice' \ -H 'Accept: application/json' ``` -------------------------------- ### Retrieve channel via cURL Source: https://docs.palabra.ai/api/retrieve-a-single-channel-by-id Example request to fetch channel data using cURL. ```bash curl -L 'https://api.palabra.ai/saas/channel/:channel_id' \ -H 'Accept: application/json' ``` -------------------------------- ### Create Glossary cURL Request Source: https://docs.palabra.ai/api/create-a-new-glossary Example cURL command to create a new glossary via a POST request. ```bash curl -L -X POST 'https://api.palabra.ai/saas/glossary' \ -H 'Content-Type: application/json' \ -H 'Accept: application/json' ``` -------------------------------- ### Create Voice Clone cURL Request Source: https://docs.palabra.ai/api/create-new-voice-from-audio-video-file-sample Example cURL command to initiate the voice cloning process. ```bash curl -L -X POST 'https://api.palabra.ai/saas/voice/clone' \ -H 'Content-Type: application/json' \ -H 'Accept: application/json' ``` -------------------------------- ### Retry Channel Creation Request Source: https://docs.palabra.ai/api/retry-channel-creation Example cURL command to execute the retry request. ```bash curl -L -X POST 'https://api.palabra.ai/saas/channel/:channel_id/retry' \ -H 'Accept: application/json' ``` -------------------------------- ### Configure Original Delay via API Source: https://docs.palabra.ai/docs/broadcaster/shift Example of setting the original_delay_seconds parameter in the broadcast creation request to synchronize media. ```bash curl -X POST 'https://api.palabra.ai/broadcasts' \ -H "Authorization: Bearer $PALABRA_API_KEY" \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ --data-raw '{ "title": "My Stream", // ... "original_delay_seconds": 3, }' ``` -------------------------------- ### Retrieve glossary file via cURL Source: https://docs.palabra.ai/api/retrieve-a-single-glossary-file-by-id Example request to retrieve a glossary file using cURL. ```bash curl -L 'https://api.palabra.ai/saas/glossary/:glossary_id/upload' \ -H 'Accept: text/csv' ``` -------------------------------- ### Fetch Voice Details via cURL Source: https://docs.palabra.ai/api/get-specific-voice Example request to retrieve voice information using cURL. ```bash curl -L 'https://api.palabra.ai/saas/voice/m/:voice_id' \ -H 'Accept: application/json' ``` -------------------------------- ### Create Event cURL Request Source: https://docs.palabra.ai/api/create-a-new-event Example cURL command to initiate a POST request to the event creation endpoint. ```bash curl -L -X POST 'https://api.palabra.ai/saas/v2/event' \ -H 'Content-Type: application/json' \ -H 'Accept: application/json' ``` -------------------------------- ### Voice Cloning Request in JavaScript Source: https://docs.palabra.ai/docs/clone-voice-api Example implementation using the Fetch API to submit the cloning request with authentication. ```javascript const payload = { name: "My voice", samples: [ { filename: "20250611_1453_Recording.mp3", mime_type: "audio/mpeg", display_name: "My voice", description: "Description of my voice", denoise: false, lang_code: "en" } ], description: "Description of my voice", labels: { gender: null, age_group: null, mood: null } }; const response = await fetch('https://api.palabra.ai/saas/voice/clone', { method: 'POST', headers: { 'Authorization': 'Bearer ' }, body: JSON.stringify(payload) }); if (!response.ok) { const errorText = await response.text().catch(() => response.statusText); throw new Error(`Failed to clone voice: ${response.status} ${errorText}`); } ``` -------------------------------- ### Configure Broadcast Task Audio Mixing Source: https://docs.palabra.ai/docs/broadcaster/audio-mixing Example of setting original audio volume and ducking parameters when creating a broadcast task. ```curl curl -X POST 'https://api.palabra.ai/broadcasts' \ -H "Authorization: Bearer $PALABRA_API_KEY" \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ --data-raw '{ "title": "My Stream", // ... "original_base_volume": 1, "original_ducked_volume": 0.2, "fade_factor": 0.07, // ... }' ``` -------------------------------- ### GET /glossaries Source: https://docs.palabra.ai/api/retrieve-user-created-glossaries Retrieve a list of user-created glossaries, optionally paginated and sorted by creation date. ```APIDOC ## GET /glossaries ### Description Retrieve a list of user-created glossaries. Supports pagination and sorting. If a `token` is provided, `sort` and `page_size` parameters are not allowed. ### Method GET ### Endpoint /glossaries ### Parameters #### Query Parameters - **sort** (string) - Optional - Sort order: `asc` | `desc` - **page_size** (integer) - Optional - Number of items per page [1;100] - **token** (string) - Optional - Pagination token. Note: `sort` and `page_size` parameters are not allowed with the pagination `token` parameter. ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the request was successful. - **data** (object) - The list of items in the page. - **items** (array) - List of glossaries. - **glossary_id** (uuid4) - Glossary ID - **user_id** (string) - User ID - **name** (string) - Glossary name - **is_enabled** (boolean) - Glossary status - **glossary_type** (string) - Possible values: [`asr_hot`, `asr`, `translation`] - **source_lang** (string) - Source language code - **target_lang** (string) - Target language code - **utc_created_at** (date-time) - Glossary created time in UTC - **utc_updated_at** (date-time) - Glossary updated time in UTC - **page_size** (integer) - The number of max items count in the page - **count** (integer) - The number of items in the page - **next** (string) - The next page token ``` -------------------------------- ### API Response Structure for WebRTC Input Source: https://docs.palabra.ai/docs/broadcaster/webrtc-input-and-outputs Example of the JSON response from the Palabra API when the webrtc_push protocol is selected. ```json { "ok": true, "data": { "id": "c1236d4d-73eb-409d-b8f5-3780fb0d8a10", // ... "input": { "protocol": "webrtc_push", "url": "", "token": "" }, } } ``` -------------------------------- ### Export event stats via cURL Source: https://docs.palabra.ai/api/download-stats-language-breakdown-as-csv Example request to export event statistics using cURL. ```bash curl -L 'https://api.palabra.ai/saas/v2/event/:event_id/stats/export' \ -H 'Accept: application/json' ``` -------------------------------- ### Retrieve Built-in Voices Source: https://docs.palabra.ai/docs/auth/using_api_keys Examples for fetching built-in voices from the Palabra API using various programming languages. ```bash curl -L 'https://api.palabra.ai/saas/voice/builtin' \ -H 'Accept: application/json' \ -H 'Authorization: Bearer ' ``` ```python import requests url = 'https://api.palabra.ai/saas/voice/builtin' headers = { 'Accept': 'application/json', 'Authorization': 'Bearer ', } response = requests.get(url, headers=headers) # Print the response status code and content print(response.status_code) print(response.json()) ``` ```go package main import ( "fmt" "net/http" "io/ioutil" ) func main() { url := "https://api.palabra.ai/saas/voice/builtin" req, err := http.NewRequest("GET", url, nil) if err != nil { fmt.Println("Error creating request:", err) return } // Set headers req.Header.Set("Accept", "application/json") req.Header.Set("Authorization", "Bearer ") // Perform the request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Println("Error making request:", err) return } defer resp.Body.Close() // Read and print the response body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error reading response body:", err) return } fmt.Println("Status Code:", resp.StatusCode) fmt.Println("Response Body:", string(body)) } ``` ```javascript const axios = require('axios'); const url = 'https://api.palabra.ai/saas/voice/builtin'; const headers = { 'Accept': 'application/json', 'Authorization': 'Bearer ' }; axios.get(url, { headers }) .then(response => { console.log('Status Code:', response.status); console.log('Response Data:', response.data); }) .catch(error => { console.error('Error making request:', error); }); ``` -------------------------------- ### Install Centrifuge dependency Source: https://docs.palabra.ai/docs/partner-integrations/agora Install the required centrifuge package via npm. ```bash npm install centrifuge ``` -------------------------------- ### Configure or update a translation task Source: https://docs.palabra.ai/docs/streaming_api/management Use this message to start, resume, or update translation settings in real-time. ```json { "message_type": "set_task", "data": { "input_stream": { /* Depends on transport — see "Streaming audio configuration" above */ }, "output_stream": { /* Depends on transport — see "Streaming audio configuration" above */ }, "pipeline": { "transcription": { "source_language": "string", "detectable_languages": ["string"], "segment_confirmation_silence_threshold": "float", "only_confirm_by_silence": "bool", "sentence_splitter": { "enabled": "bool" }, "verification": { "auto_transcription_correction": "bool", "transcription_correction_style": "string" } }, // Translation and speech generation settings for one or more target languages "translations": [ { "target_language": "string", "translate_partial_transcriptions": "bool", "speech_generation": { "voice_cloning": "bool", "voice_id": "string", "voice_timbre_detection": { "enabled": "bool", "high_timbre_voices": [], "low_timbre_voices": [] } } } // You can add more targets ], "translation_queue_configs": { "global": { "desired_queue_level_ms": "int", "max_queue_level_ms": "int", "auto_tempo": "bool" }, "es": { "desired_queue_level_ms": "int", "max_queue_level_ms": "int" } }, // Select response types to receive "allowed_message_types": [ "translated_transcription", "partial_transcription", "partial_translated_transcription", "validated_transcription" ] } } } ``` -------------------------------- ### Run a complete Palabra WebSocket client Source: https://docs.palabra.ai/docs/quick-start/websockets A minimal implementation demonstrating connection, configuration, and concurrent audio streaming. ```python import asyncio import os import signal async def main(): signal.signal(signal.SIGINT, lambda s, f: os._exit(0)) print("šŸš€ Palabra WebSocket Client") # Step 1: Your API Key api_key = os.getenv("PALABRA_API_KEY") # Step 2: Connect to WebSocket (a session is created automatically) websocket = await connect_websocket(api_key) # Step 3: Configure translation and wait for it to apply await configure_translation(websocket, "en", ["es"]) await asyncio.sleep(3) # see the tip below for a deterministic check # Steps 4 & 5: Stream the microphone and play translated audio receive_task = asyncio.create_task(receive_and_play(websocket)) stream_task = asyncio.create_task(stream_microphone(websocket)) print("\nšŸŽ§ Listening... Press Ctrl+C to stop\n") try: await asyncio.gather(receive_task, stream_task) except KeyboardInterrupt: print("\nšŸ›‘ Shutdown complete") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### GET wss://stream.palabra.ai/asr/v1/speech-to-text/stream Source: https://docs.palabra.ai/docs/streaming_api/realtime_stt Establishes a WebSocket connection for real-time audio transcription. The session is created automatically upon successful authentication. ```APIDOC ## GET wss://stream.palabra.ai/asr/v1/speech-to-text/stream ### Description Establishes a WebSocket connection for real-time audio transcription. The server validates the provided API key and creates a streaming session for the lifetime of the connection. ### Method GET (WebSocket Upgrade) ### Endpoint wss://stream.palabra.ai/asr/v1/speech-to-text/stream ### Parameters #### Query Parameters - **token** (string) - Required - Your API Key - **format** (string) - Required - Audio format - **sample_rate** (integer) - Conditional - Sample rate in Hz. Required for all raw PCM formats; for pcm_s16le required only when the rate is not 16000 - **language** (string) - Optional - Source language code. Defaults to auto - **translate_languages** (string) - Optional - Comma-separated target languages, e.g. es,de,fr - **enable_filler_filter** (boolean) - Optional - Whether to enable the filler filter. true by default for all languages except ja ``` -------------------------------- ### Initialize and Join Agora Channel Source: https://docs.palabra.ai/docs/partner-integrations/agora Configure the Agora client, set up event listeners for remote tracks, and join the channel to publish local audio. ```javascript import AgoraRTC from 'agora-rtc-sdk-ng'; // Create the Agora Client instance client = AgoraRTC.createClient({ mode: 'rtc', codec: 'vp8' }); // Set up the `user-published` event listener to play new track from channel client.on('user-published', async (user, mediaType) => { await client?.subscribe(user, mediaType); if (mediaType === 'audio') { user.audioTrack?.play(); } }); // Set up the `user-unpublished` event listener to get rid of HTML players no longer used client.on('user-unpublished', (user) => { const remotePlayerContainer = document.getElementById(user.uid); remotePlayerContainer?.remove(); }); // Join the Agora channel await client.join( agoraAppID, channelTokenData.channel, channelTokenData.token, Number(channelTokenData.uid) ); // Publish your local mic audio track to Agora Channel const localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack(); await client.publish([localAudioTrack]); ``` -------------------------------- ### GET /broadcasts Source: https://docs.palabra.ai/docs/broadcaster/api Returns broadcasts owned by the authenticated user. ```APIDOC ## GET /broadcasts ### Description Returns broadcasts owned by the authenticated user. ### Method GET ### Endpoint /broadcasts ### Request Example ``` curl -X GET "https://api.palabra.ai/broadcasts" \ -H "Authorization: Bearer $PALABRA_API_KEY" \ -H 'Accept: application/json' ``` ### Response #### Success Response (200) - **ok** (boolean) - Status of the request - **data** (array) - List of broadcast tasks ``` -------------------------------- ### GET /saas/glossary/:glossary_id Source: https://docs.palabra.ai/api/retrieve-a-single-glossary-by-id Retrieve a single glossary by its ID. ```APIDOC ## GET /saas/glossary/:glossary_id ### Description Retrieve a single glossary by its ID. ### Method GET ### Endpoint /saas/glossary/:glossary_id ### Parameters #### Path Parameters - **glossary_id** (uuid4) - Required - The unique identifier of the glossary. ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the request was successful. - **data** (object) - The glossary object containing details such as glossary_id, user_id, name, is_enabled, glossary_type, source_lang, target_lang, utc_created_at, and utc_updated_at. #### Error Response (Default) - **ok** (boolean) - Indicates if the request was successful. - **errors** (array) - A list of error objects containing type, status, title, detail, instance, and error_code. ``` -------------------------------- ### set_task Source: https://docs.palabra.ai/docs/streaming_api/management Creates a new task or modifies the current one. This can be used to start a translation, resume a paused task, or update settings in real-time. ```APIDOC ## set_task ### Description Create a new task or modify the current one. Sent for the first time after creating a session to start translation, after pause_task to resume, or during an ongoing translation to update settings. ### Request Body - **message_type** (string) - Required - Must be "set_task" - **data** (object) - Required - Contains configuration for input_stream, output_stream, pipeline (transcription, translations, translation_queue_configs, allowed_message_types) ``` -------------------------------- ### GET /session-storage/sessions Source: https://docs.palabra.ai/api/get-user-sessions Retrieves a list of sessions for the authenticated user. ```APIDOC ## GET /session-storage/sessions ### Description Retrieves a list of sessions for the authenticated user. ### Method GET ### Endpoint https://api.palabra.ai/session-storage/sessions ### Parameters #### Query Parameters - **page_size** (integer) - Optional - Number of items to return. - **page_token** (string) - Optional - Token for pagination. ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the request was successful. - **data** (object[]) - A list of user sessions. - **id** (string) - Session identifier. - **created_at** (date-time) - Session creation timestamp. - **updated_at** (date-time) - Session last update timestamp. - **expires_at** (date-time) - Session expiration timestamp. - **intent** (string) - Intent of the session (e.g., api, broadcaster, desktop, event, agora, captions, bot_conversational, bot_presentation). - **aggregation_id** (string) - Aggregation ID for grouping sessions in billing display. - **organization** (string) - Casdoor organization that owns the session. ``` -------------------------------- ### GET /saas/channel/:channel_id Source: https://docs.palabra.ai/api/retrieve-a-single-channel-by-id Retrieves the details of a specific channel by its ID. ```APIDOC ## GET /saas/channel/:channel_id ### Description Retrieves the details of a specific channel by its unique identifier. This endpoint returns the channel configuration, status, and associated broadcast information. ### Method GET ### Endpoint /saas/channel/:channel_id ### Parameters #### Path Parameters - **channel_id** (uuid4) - Required - The unique identifier of the channel. ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the request was successful. - **data** (object) - The channel and broadcast details including id, title, status, input, outputs, and translation_pipeline. #### Error Response (Default) - **ok** (boolean) - Indicates if the request was successful. - **errors** (array) - A list of error objects containing type, status, title, detail, instance, and error_code. ``` -------------------------------- ### Connect with Session Token in Python Source: https://docs.palabra.ai/docs/quick-start/websockets Connects to a pre-existing session using a provided URL and publisher token. ```python import websockets async def connect_websocket_with_session(ws_url: str, publisher_token: str): full_url = f"{ws_url}?token={publisher_token}" websocket = await websockets.connect(full_url, ping_interval=10, ping_timeout=30) print("šŸ”Œ Connected to WebSocket") return websocket ``` -------------------------------- ### GET /events/{event_id} Source: https://docs.palabra.ai/api/retrieve-a-single-event-by-id Retrieves the details of a single event by its ID. ```APIDOC ## GET /events/{event_id} ### Description Retrieve a single event by its unique ID. ### Method GET ### Endpoint /events/{event_id} ### Parameters #### Path Parameters - **event_id** (uuid4) - Required - The unique identifier of the event. ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the request was successful. - **data** (object) - The event object containing details such as title, description, event_type, location, timezone, utc_start_dt, utc_end_dt, is_recurring, cover_image_key, cover_image_url, qr_code_url, lifecycle_status, finished_at, access_code, input_languages, output_languages, target_languages, listener_language_mode, utc_created_at, utc_updated_at, and stages. #### Error Response (Default) - **ok** (boolean) - Indicates if the request was successful. - **errors** (array) - List of error objects containing type, status, title, detail, instance, and error_code. ``` -------------------------------- ### Stream text to speech from an LLM using Python Source: https://docs.palabra.ai/docs/streaming_api/realtime_tts Demonstrates initializing a WebSocket session, sending text chunks with per-sentence speed overrides, and collecting the resulting audio stream. ```python import asyncio, json, base64, websockets WS_TTS_URL = "wss://stream.palabra.ai/tts-api/v1/text-to-speech/stream" API_KEY = "" # create one at https://platform.palabra.ai/api-keys SENTENCES = [ ( "The sun was setting over the mountains,", "casting long golden shadows across the valley below.", ), ( "Birds were returning to their nests,", "filling the air with their evening songs.", ), ( "A gentle breeze moved through the tall grass,", "creating waves that rippled toward the horizon.", ), ] async def main(): url = f"{WS_TTS_URL}?token={API_KEY}" async with websockets.connect(url) as ws: # 1. Initialise the session await ws.send(json.dumps({ "type": "init", "language": "en", "model": "auto", "voice_options": { "voice_id": "default_low", "speed": 1.0, "deaccent_strength": 1.0, }, "output": { "format": "pcm", "sample_rate": 24000, } })) # 2. Send each sentence chunk by chunk, is_eos=True on the last chunk of each sentence sent = 0 for i, sentence in enumerate(SENTENCES): for k, chunk in enumerate(sentence): msg = { "type": "text", "text": chunk, "is_eos": k == len(sentence) - 1, } if k == 0: # override speed only at the start of each sentence msg["voice_options"] = {"speed": min(0.5 + i / 10, 1.0)} await ws.send(json.dumps(msg)) sent += 1 # 3. Collect audio until every generation has signalled last_chunk audio = bytearray() done = 0 async for raw in ws: data = json.loads(raw) if data.get("message_type") == "audio_chunk": chunk = data["data"] audio.extend(base64.b64decode(chunk["audio"])) print(f"Chunk: {chunk['size']} bytes, total: {len(audio)}") if chunk.get("last_chunk"): done += 1 if done == sent: # all sentences finished break elif data.get("message_type") == "error": print(f"Error: {data['data']['code']} — {data['data']['desc']}") break print(f"Total: {len(audio)} bytes") with open("output.pcm", "wb") as f: f.write(audio) # Play: ffplay -f s16le -ar 24000 -ac 1 output.pcm asyncio.run(main()) ``` -------------------------------- ### GET /saas/glossary/:glossary_id/upload Source: https://docs.palabra.ai/api/retrieve-a-single-glossary-file-by-id Retrieves a single glossary CSV file by its ID. ```APIDOC ## GET /saas/glossary/:glossary_id/upload ### Description Retrieve a single glossary CSV file by its ID. ### Method GET ### Endpoint /saas/glossary/:glossary_id/upload ### Parameters #### Path Parameters - **glossary_id** (uuid4) - Required - The unique identifier of the glossary. ### Response #### Success Response (200) - **file** (text/csv) - The glossary upload file. #### Error Response (default) - **ok** (boolean) - Indicates if the request was successful. - **errors** (object[]) - List of error details including status, title, detail, instance, and error_code. ``` -------------------------------- ### Initialize JavaScript Palabra Client Source: https://docs.palabra.ai/ Configures the Palabra client with authentication credentials and audio track handling for web applications. ```javascript import { PalabraClient, getLocalAudioTrack } from '@palabra-ai/translator'; const client = new PalabraClient({ auth: { clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }, translateFrom: 'en', // Source language code translateTo: 'es', // Target language code handleOriginalTrack: getLocalAudioTrack, // Func returning a MediaStreamTrack }); ``` -------------------------------- ### GET /saas/voice/hidden Source: https://docs.palabra.ai/api/get-list-of-hidden-user-voices-skip-external-voice-true Retrieve a list of hidden voices (created with skip_external_voice=true) for the user. ```APIDOC ## GET /saas/voice/hidden ### Description Retrieve a list of hidden voices (created with skip_external_voice=true) for the user. ### Method GET ### Endpoint /saas/voice/hidden ### Parameters #### Query Parameters - **sort** (string) - Optional - Sort order: `asc` | `desc` - **page_size** (integer) - Optional - Number of items per page [1;100] - **token** (string) - Optional - Pagination token. Note: `sort` and `page_size` parameters are not allowed with the pagination `token` parameter. ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the request was successful or not. - **data** (object) - The list of items in the page. - **items** (array) - The list of items in the page. - **voice_id** (string) - Voice ID - **user_id** (string) - User ID - **utc_created_at** (date-time) - UTC created at - **utc_updated_at** (date-time) - UTC updated at - **voice_type** (string) - VoiceType (Possible values: `instantly_cloned`, `instantly_cloned_builtin`) - **processing_status** (string) - VoiceProcessingStatus (Possible values: `created`, `pending`, `ready`, `failed`) - **name** (string) - Name - **page_size** (integer) - The number of max items count in the page - **count** (integer) - The number of items in the page - **next** (string) - The next page token ``` -------------------------------- ### Update Channel via cURL Source: https://docs.palabra.ai/api/update-a-channel Example request to update a channel using cURL. ```bash curl -L -X PATCH 'https://api.palabra.ai/saas/channel/:channel_id' \ -H 'Content-Type: application/json' \ -H 'Accept: application/json' ``` -------------------------------- ### Real-time translation with Python SDK Source: https://docs.palabra.ai/ Demonstrates streaming audio to the Palabra translation service and handling incoming transcript and audio events. ```python import asyncio import time from palabra_ai import Palabra, Transcript, Audio CHUNK_MS = 320 # ~320 ms of PCM (s16le, 24 kHz, mono) async def main(): palabra = Palabra() async with palabra.translation(source="en", targets=["es"]) as session: async def send_audio(): next_send = time.monotonic() while chunk := await audio_buffer.get(): # your audio source await session.send_audio(chunk) next_send += CHUNK_MS / 1000 await asyncio.sleep(max(0, next_send - time.monotonic())) await session.end(eos_timeout=4) sender = asyncio.create_task(send_audio()) async for event in session: match event: case Transcript(): print(event) case Audio(): play(event.pcm) await sender asyncio.run(main()) ``` -------------------------------- ### init Source: https://docs.palabra.ai/docs/streaming_api/realtime_tts Initializes the TTS session. This message must be sent once immediately after connecting. ```APIDOC ## init ### Description Initializes the TTS session. This message must be sent once immediately after connecting. ### Request Body - **type** (string) - Required - Must be "init" - **language** (string) - Required - BCP-47 language code (e.g., "en", "ru") - **model** (string) - Optional - TTS model ID, defaults to "auto" - **voice_options** (object) - Required - Voice configuration - **voice_id** (string) - Required - Voice identifier (e.g., "default_low", "default_high") - **speed** (float) - Optional - Speed multiplier (0.0–2.0), defaults to 1.0 - **deaccent_strength** (float) - Optional - Reduces foreign accent (0.0–1.0), defaults to 1.0 - **output** (object) - Optional - Output audio settings - **format** (string) - Optional - Format: "pcm", "mp3", "wav", defaults to "mp3" - **sample_rate** (integer) - Optional - Sample rate (8000–48000), defaults to 24000 ### Request Example { "type": "init", "language": "en", "model": "auto", "voice_options": { "voice_id": "default_low", "speed": 1.0, "deaccent_strength": 1.0 }, "output": { "format": "pcm", "sample_rate": 24000 } } ``` -------------------------------- ### POST https://api.palabra.ai/saas/glossary Source: https://docs.palabra.ai/docs/create-a-glossary-using-api Submit glossary metadata to initialize a new glossary record. ```APIDOC ## POST https://api.palabra.ai/saas/glossary ### Description Submit glossary metadata to create a new glossary entry in the system. ### Method POST ### Endpoint https://api.palabra.ai/saas/glossary ### Request Body - **name** (string) - Required - A user-defined name for the glossary. - **is_enabled** (boolean) - Required - Whether the glossary should be active immediately. - **glossary_type** (string) - Required - Specifies the type: 'translation' or 'asr'. - **source_lang** (string) - Required - The language code for the source language. - **target_lang** (string) - Conditionally Required - The language code for the target language (required if glossary_type is 'translation'). ### Request Example { "name": "Glossary#2", "is_enabled": true, "glossary_type": "translation", "source_lang": "en", "target_lang": "fr" } ### Response #### Success Response (200) - **glossary_id** (string) - The unique identifier for the created glossary. - **user_id** (string) - The ID of the user. - **name** (string) - The name of the glossary. - **is_enabled** (boolean) - Status of the glossary. - **glossary_type** (string) - Type of the glossary. - **source_lang** (string) - Source language code. - **target_lang** (string) - Target language code. - **utc_created_at** (string) - Timestamp of creation. ``` -------------------------------- ### Delete glossary cURL request Source: https://docs.palabra.ai/api/delete-a-glossary-by-id Example of how to perform the delete operation using cURL. ```bash curl -L -X DELETE 'https://api.palabra.ai/saas/glossary/:glossary_id' \ -H 'Accept: application/json' ``` -------------------------------- ### Delete event cURL request Source: https://docs.palabra.ai/api/delete-an-event-by-id Example of how to perform the delete operation using cURL. ```bash curl -L -X DELETE 'https://api.palabra.ai/saas/v2/event/:event_id' \ -H 'Accept: application/json' ``` -------------------------------- ### Delete voice via cURL Source: https://docs.palabra.ai/api/delete-specific-voice-by-id Example request to delete a voice using cURL. ```bash curl -L -X DELETE 'https://api.palabra.ai/saas/voice/m/:voice_id' \ -H 'Accept: application/json' ``` -------------------------------- ### Create a Session Response Source: https://docs.palabra.ai/docs/quick-start/webrtc The expected JSON response containing the publisher token and WebRTC URL. ```json { "publisher": "eyJhbGciOiJIU...Gxr2gjWSA4", "webrtc_url": "https://streaming-0.palabra.ai/livekit/", "ws_url": "wss://streaming-0.palabra.ai/streaming-api/v1/speech-to-speech/stream", "id": "7f99b553-4697...7d450728" } ``` -------------------------------- ### Get Session by ID Source: https://docs.palabra.ai/docs/streaming_api/session Retrieve details for a specific session using its unique identifier. ```http GET /session-storage/sessions/{session_id} HTTP/1.1 Host: api.palabra.ai Authorization: Bearer ``` ```json { "data": { "id": "58347ae0-8a5d-41cf-96d9-166b550b3335.b0327ccf.3c0742bc", "created_at": "2024-10-21T14:13:18Z", "updated_at": "2024-10-21T14:13:18Z", "expires_at": "2024-11-20T14:13:18Z" } } ``` -------------------------------- ### GET /broadcasts/{id}/webrtc-token Source: https://docs.palabra.ai/docs/broadcaster/api Returns WebRTC room credentials for the broadcast listeners. ```APIDOC ## GET /broadcasts/{id}/webrtc-token ### Description Returns WebRTC room credentials for the broadcast listeners. In case of WebRTC output, use the credentials to subscribe to translated tracks. ### Method GET ### Endpoint /broadcasts/{id}/webrtc-token?room={id} ### Parameters #### Path Parameters - **id** (string) - Required - The broadcast ID #### Query Parameters - **room** (string) - Required - The broadcast ID used as the room identifier ### Request Example ``` curl -X GET "https://api.palabra.ai/broadcasts//webrtc-token?room=" \ -H 'Accept: application/json' ``` ### Response #### Success Response (200) - **ok** (boolean) - Status of the request - **data** (object) - Contains url and token for WebRTC connection ``` -------------------------------- ### Retrieve glossary by ID endpoint Source: https://docs.palabra.ai/api/retrieve-a-single-glossary-by-id The HTTP GET request path for fetching a glossary. ```http GET /saas/glossary/:glossary_id ``` -------------------------------- ### GET /events Source: https://docs.palabra.ai/api/retrieve-user-created-events Retrieves a list of user-created events based on optional query parameters. ```APIDOC ## GET /events ### Description Retrieve a list of user-created events. Supports pagination, status filtering, and full-text search. ### Method GET ### Endpoint /events ### Parameters #### Query Parameters - **pagination_token** (string) - Optional - Pagination token - **status** (string) - Optional - Filter by event lifecycle status - **q** (string) - Optional - Full-text search over title and description ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the request was successful - **data** (object) - Contains the list of events - **events** (array) - List of user-created events - **event_id** (uuid) - Event ID - **title** (string) - Event title - **description** (string) - Event description - **event_type** (string) - Event type (in-person, online) - **location** (string) - Event location - **timezone** (string) - Event IANA timezone - **utc_start_dt** (date-time) - Event start date and time in UTC - **utc_end_dt** (date-time) - Event end date and time in UTC - **is_recurring** (boolean) - Indicates if the event is recurring - **cover_image_key** (string) - Event cover image S3 key - **cover_image_url** (string) - Event cover image URL - **qr_code_url** (uri) - Event QR code URL - **lifecycle_status** (string) - Event lifecycle status (setup_required, upcoming, ready, live, finished) - **finished_at** (date-time) - Event completion time in UTC - **access_code** (string) - Event access code - **input_languages** (array) - Event input languages - **output_languages** (array) - Event output languages - **target_languages** (array) - Organizer-configured default translation languages - **listener_language_mode** (string) - Listener language mode (off, approval, auto) - **utc_created_at** (date-time) - Event creation time in UTC - **utc_updated_at** (date-time) - Event last update time in UTC - **pagination_token** (string) - Pagination token for the next page ``` -------------------------------- ### WebRTC Input Configuration Source: https://docs.palabra.ai/docs/broadcaster/input-and-outputs Request structure for initiating a WebRTC push input. ```json {"protocol": "webrtc_push"} ``` -------------------------------- ### Publish Media Tracks to WebRTC Source: https://docs.palabra.ai/docs/broadcaster/webrtc-input-and-outputs Steps to capture local media, wrap tracks, and publish them to the room with required codec and bitrate configurations. ```javascript import { LocalAudioTrack, LocalVideoTrack, } from "livekit-client"; // 1. Get both audio + video from the Device const media = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1 }, video: true }); // 2. Split tracks const [rawAudioTrack] = media.getAudioTracks(); const [rawVideoTrack] = media.getVideoTracks(); // 3. Wrap them in LiveKit track classes const localAudioTrack = new LocalAudioTrack(rawAudioTrack); const localVideoTrack = new LocalVideoTrack(rawVideoTrack); // 4. Publish audio to the Livekit WebRTC room const publishAudioTrack = async (room, track) => { try { await room.localParticipant.publishTrack(track, { dtx: false, // Important to keep DTX:false red: false, audioPreset: { maxBitrate: 32000, priority: "high" } }); } catch (e) { console.error("Error while publishing audio track:", e); throw e; } }; // 5. Publish video to the Livekit WebRTC room const publishVideoTrack = async (room, track) => { try { await room.localParticipant.publishTrack(track, { videoCodec: "h264" // Important to keep videoCodec:"h264" }); } catch (e) { console.error("Error while publishing video track:", e); throw e; } }; // 6. Usage example await publishAudioTrack(room, localAudioTrack); await publishVideoTrack(room, localVideoTrack); ``` -------------------------------- ### GET /saas/voice/m/:voice_id Source: https://docs.palabra.ai/api/get-specific-voice Retrieves the details of a specific voice identified by the provided voice_id. ```APIDOC ## GET /saas/voice/m/:voice_id ### Description Retrieves the details of a specific voice identified by the provided voice_id. ### Method GET ### Endpoint https://api.palabra.ai/saas/voice/m/:voice_id ### Parameters #### Path Parameters - **voice_id** (string) - Required - The unique identifier of the voice. ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the request was successful. - **data** (object) - Contains voice details including voice_id, user_id, utc_created_at, utc_updated_at, voice_type, processing_status, processing_result, model, labels, name, description, has_external_voice, attributes, is_favorite, and tts_sample. ```