Batch Speech-to-Text Translate (STTT) API Tutorial Using Saaras Model

Overview

This guide demonstrates how to use Sarvam AI’s Batch Speech-to-Text Translate (STTT) API for translating audio files at scale. You’ll learn both synchronous and asynchronous usage patterns, understand key parameters, and see how to upload files, poll for job completion, and download results.

1. Installation

Install the Sarvam AI Python SDK:

1!pip install -U sarvamai

2. API Key Setup

  1. Get your API key: Sign up at the Sarvam AI Dashboard to obtain your API key.
  2. Set your API key: Replace "YOUR_API_KEY_HERE" in the code below with your actual key.
1API_KEY = "YOUR_API_KEY_HERE"

3. STT Parameters

Sets up the job configuration for the STT batch process.

Parameters:

  • model: Translation model to use (e.g., “saaras:v2.5”)
  • with_diarization: If True, enables speaker diarization
  • num_speakers: Number of speakers (used with diarization)
  • prompt: Optional prompt to guide translation style/context

4. Synchronous STTT Batch Example

1from pathlib import Path
2from sarvamai import SarvamAI
3
4API_KEY = "YOUR_API_KEY_HERE"
5audio_files = ["/path/to/your/audio.mp3"] # Update with your file path
6output_dir = Path("/output")
7output_dir.mkdir(exist_ok=True)
8
9def run_sttt_sync():
10 client = SarvamAI(api_subscription_key=API_KEY)
11
12 job = client.speech_to_text_translate_job.create_job(
13 model="saaras:v2.5",
14 with_diarization=True,
15 num_speakers=2,
16 prompt="Official meeting"
17 )
18
19 print(f"Job created: {job._job_id}")
20 job.upload_files(file_paths=audio_files, timeout=120.0)
21 job.start()
22 print("Translation started...")
23 job.wait_until_complete(poll_interval=5, timeout=60)
24
25 if job.is_failed():
26 raise RuntimeError("Translation failed")
27
28 job.download_outputs(output_dir=str(output_dir))
29 print(f"Translation completed. Output saved to: {output_dir}")
30
31run_sttt_sync()

5. Asynchronous STT Batch Example

1import asyncio
2from pathlib import Path
3from sarvamai import AsyncSarvamAI
4
5API_KEY = "YOUR_API_KEY_HERE"
6audio_files = ["/path/to/your/audio.mp3"] # Update with your file path
7output_dir = Path("/output")
8output_dir.mkdir(exist_ok=True)
9
10async def run_sttt_async_job():
11 client = AsyncSarvamAI(api_subscription_key=API_KEY)
12
13 job = await client.speech_to_text_translate_job.create_job(
14 model="saaras:v2.5",
15 with_diarization=True,
16 num_speakers=2,
17 prompt="Official meeting"
18 )
19
20 print(f"Job created: {job._job_id}")
21 await job.upload_files(file_paths=audio_files, timeout=120.0)
22 await job.start()
23 print("Translation started...")
24 await job.wait_until_complete(poll_interval=5, timeout=60)
25
26 if await job.is_failed():
27 raise RuntimeError("Translation failed")
28
29 await job.download_outputs(output_dir=str(output_dir))
30 print(f"Translation completed. Output saved to: {output_dir}")
31
32# For Jupyter environments:
33import nest_asyncio
34nest_asyncio.apply()
35await run_sttt_async_job()

6. Tips & Best Practices

  • Audio Quality: Use clear audio for best results.
  • Diarization: Set with_diarization=True and specify num_speakers for multi-speaker audio.
  • Polling: Adjust poll_interval and timeout based on expected job duration and file size.
  • Output: Results are saved in the specified output_dir.
  • API Key Security: Keep your API key confidential.

7. Error Handling

You may encounter these errors while using the API:

  • 403 Forbidden (invalid_api_key_error)

  • 429 Too Many Requests (insufficient_quota_error)

    • Cause: Exceeded API quota.
    • Solution: Check your usage, upgrade if needed, or implement exponential backoff when retrying.
  • 500 Internal Server Error (internal_server_error)

    • Cause: Issue on our servers.
    • Solution: Try again later. If persistent, contact support.
  • 400 Bad Request (invalid_request_error)

    • Cause: Incorrect request formatting.
    • Solution: Verify your request structure, and parameters.
  • 422 Unprocessable Entity Request (unprocessable_entity_error)

    • Cause: Unable to detect the language of the input text.
    • Solution: Explicitly pass the source_language_code parameter with a supported language.

8. Additional Resources

For more details, refer to the our official documentation and we are always there to support and help you on our Discord Server:

9. Final Notes

  • Keep your API key secure.
  • Use clear audio for best results.
  • Check audio quality and supported formats.
  • Increase timeout for large files or slow networks.

Keep Building! 🚀