### Quick Start Async Transcription Source: https://github.com/mmua/salute_speech/blob/master/README.md An asynchronous Python example to transcribe an audio file using the `SaluteSpeechClient`. It reads an audio file, sends it for transcription, and prints the resulting text. Requires the `SBER_SPEECH_API_KEY` environment variable. ```python from salute_speech.speech_recognition import SaluteSpeechClient import asyncio import os async def main(): # Initialize the client (from environment variable) client = SaluteSpeechClient(client_credentials=os.getenv("SBER_SPEECH_API_KEY")) # Open and transcribe an audio file with open("audio.mp3", "rb") as audio_file: result = await client.audio.transcriptions.create( file=audio_file, language="ru-RU" ) print(result.text) # Run the async function asyncio.run(main()) ``` -------------------------------- ### Quick CLI Transcription Example Source: https://github.com/mmua/salute_speech/blob/master/README.md Demonstrates how to use the command-line interface for transcribing an audio file. This requires setting an API key environment variable and using ffmpeg for audio preparation. ```bash export SBER_SPEECH_API_KEY=your_key_here ffmpeg -i input.mp3 -ac 1 -ar 16000 audio.wav salute_speech transcribe-audio audio.wav -o transcript.txt ``` -------------------------------- ### Install salute_speech Package Source: https://github.com/mmua/salute_speech/blob/master/README.md Installs the Sber Salute Speech Python client using pip. Ensure you have Python and pip installed on your system. ```bash pip install salute_speech ``` -------------------------------- ### Low-Level API Interaction for Speech Recognition Source: https://context7.com/mmua/salute_speech/llms.txt Illustrates direct interaction with Sber Speech API using the SberSpeechRecognition client for custom workflows. It covers the four main steps: uploading the audio file, starting the recognition task with detailed parameters, polling for task status, and downloading the final result. This provides fine-grained control over the recognition process. ```python from salute_speech.speech_recognition import ( SberSpeechRecognition, SpeechRecognitionConfig ) from time import sleep # Initialize low-level client client = SberSpeechRecognition( client_credentials="YOUR_API_KEY", base_url="https://smartspeech.sber.ru/rest/v1/" ) # Step 1: Upload audio file with open("audio.mp3", "rb") as audio_file: file_id = client.upload_file(audio_file) print(f"Uploaded file ID: {file_id}") # Step 2: Start recognition task task = client.async_recognize( request_file_id=file_id, audio_encoding="MP3", sample_rate=44100, channels_count=2, language="ru-RU", config=SpeechRecognitionConfig(hypotheses_count=1) ) print(f"Task created: {task.id}, status: {task.status}") # Step 3: Poll for completion while True: status = client.get_task_status(task.id) print(f"Status: {status['status']}") if status["status"] == "ERROR": print(f"Task failed: {status.get('error_message')}") break elif status["status"] == "DONE": response_file_id = status["response_file_id"] break sleep(2) # Step 4: Download result result_json = client.download_result(response_file_id) print(f"Result: {result_json}") ``` -------------------------------- ### Programmatic Transcription with Segments Source: https://github.com/mmua/salute_speech/blob/master/README.md Illustrates iterating through transcription segments, which include start and end times, and the transcribed text for each segment. This provides a more detailed output than just the full text. ```python for seg in result.segments or []: print(f"[{seg.start:.2f} - {seg.end:.2f}] {seg.text}") ``` -------------------------------- ### Initialize SaluteSpeechClient Source: https://github.com/mmua/salute_speech/blob/master/README.md Shows how to instantiate the main client class for interacting with the Sber Speech API. Authentication is typically handled via credentials passed during initialization. ```python from salute_speech.speech_recognition import SaluteSpeechClient client = SaluteSpeechClient(client_credentials="your_credentials_here") ``` -------------------------------- ### Basic Usage - Help Command Source: https://github.com/mmua/salute_speech/blob/master/README.md Display the help message for the salute_speech command-line tool to understand available options and commands. ```bash salute_speech --help ``` -------------------------------- ### Bash: Transcribe Audio Using Salute Speech CLI Source: https://context7.com/mmua/salute_speech/llms.txt Demonstrates the command-line interface for rapid audio transcription. This includes setting the API key, preparing audio using ffmpeg, and performing basic transcriptions with various output formats like TXT, VTT, SRT, JSON, and TSV. It also covers advanced options such as language selection, debugging, and channel count validation. ```bash # Set API key environment variable export SBER_SPEECH_API_KEY="your_api_key_here" # Prepare audio (convert to mono 16kHz for best results) ffmpeg -i video.mp4 -ac 1 -ar 16000 audio.wav # Basic transcription to text file salute_speech transcribe-audio audio.wav -o transcript.txt # Transcribe with language selection salute_speech transcribe-audio audio.wav --language en-US -o transcript.txt # Generate WebVTT subtitles salute_speech transcribe-audio audio.wav -o subtitles.vtt # Generate SRT subtitles salute_speech transcribe-audio audio.wav -o subtitles.srt # Output JSON with timestamps salute_speech transcribe-audio audio.wav -o result.json # Export as TSV (tab-separated values) salute_speech transcribe-audio audio.wav -o data.tsv # Specify output format explicitly salute_speech transcribe-audio audio.wav -f json -o output.txt # Debug: dump raw Sber API response salute_speech transcribe-audio audio.wav -o transcript.txt --debug_dump raw_response.json # Validate channel count (warns if mismatch) salute_speech transcribe-audio stereo_audio.mp3 --channels 2 -o output.txt ``` -------------------------------- ### SaluteSpeechClient.audio.transcriptions.create() - Transcribe Audio with Advanced Configuration Source: https://context7.com/mmua/salute_speech/llms.txt This section covers using the `create` method with advanced configuration options via `SpeechRecognitionConfig` for specialized transcription needs. ```APIDOC ## SaluteSpeechClient.audio.transcriptions.create() - Transcribe Audio with Advanced Configuration ### Description Create transcription with custom recognition parameters for specialized use cases using the `SpeechRecognitionConfig` object. ### Method POST (implicitly via `client.audio.transcriptions.create`) ### Endpoint `client.audio.transcriptions.create` ### Parameters #### Path Parameters None #### Query Parameters - **language** (string) - Required - The language of the audio (e.g., "ru-RU", "en-US"). - **poll_interval** (float) - Optional - The interval in seconds to poll for task status. #### Request Body - **file** (file) - Required - The audio file to transcribe. - **config** (object) - Required - An instance of `SpeechRecognitionConfig` containing advanced settings. - **hypotheses_count** (integer) - Optional - Number of alternative transcriptions to generate. - **enable_profanity_filter** (boolean) - Optional - Enables filtering of offensive words. - **max_speech_timeout** (string) - Optional - Maximum duration for a speech segment (e.g., "30s"). - **no_speech_timeout** (string) - Optional - Timeout for silence detection (e.g., "7s"). - **hints** (object) - Optional - Domain-specific terms or phrases to guide recognition (e.g., `{"компания": ["Сбер", "Яндекс"]}`). - **insight_models** (array) - Optional - List of additional insight models to enable. - **debug_dump** (string) - Optional - Path to save raw API response for debugging. ### Request Example ```python import asyncio from salute_speech.speech_recognition import ( SaluteSpeechClient, SpeechRecognitionConfig ) async def transcribe_with_config(): client = SaluteSpeechClient(client_credentials="YOUR_API_KEY") config = SpeechRecognitionConfig( hypotheses_count=3, enable_profanity_filter=True, max_speech_timeout="30s", no_speech_timeout="7s", hints={"компания": ["Сбер", "Яндекс"]}, insight_models=[] ) with open("customer_call.wav", "rb") as audio_file: result = await client.audio.transcriptions.create( file=audio_file, language="ru-RU", poll_interval=2.0, config=config, debug_dump="./debug_results" ) print(f"Transcribed: {result.text}") print(f"Task ID: {result.task_id}") asyncio.run(transcribe_with_config()) ``` ### Response #### Success Response (200) - **text** (string) - The transcribed text. - **task_id** (string) - The ID of the recognition task. #### Response Example ```json { "text": "Customer confirmed the order details.", "task_id": "f0e1d2c3-b4a5-6789-0123-456789abcdef" } ``` ``` -------------------------------- ### Advanced Audio Transcription with Custom Configuration Source: https://context7.com/mmua/salute_speech/llms.txt Shows how to use SaluteSpeechClient with advanced configuration options for specialized transcription needs. This includes setting the number of hypotheses, enabling profanity filters, configuring speech and no-speech timeouts, and providing domain-specific hints. The debug_dump parameter saves the raw API response. ```python import asyncio from salute_speech.speech_recognition import ( SaluteSpeechClient, SpeechRecognitionConfig ) async def transcribe_with_config(): client = SaluteSpeechClient(client_credentials="YOUR_API_KEY") # Configure advanced recognition settings config = SpeechRecognitionConfig( hypotheses_count=3, # Generate 3 transcription variants enable_profanity_filter=True, # Filter offensive words max_speech_timeout="30s", # Max speech segment duration no_speech_timeout="7s", # Silence detection timeout hints={"компания": ["Сбер", "Яндекс"]}, # Domain-specific terms insight_models=[] # Additional models (if enabled) ) with open("customer_call.wav", "rb") as audio_file: result = await client.audio.transcriptions.create( file=audio_file, language="ru-RU", poll_interval=2.0, config=config, debug_dump="./debug_results" # Save raw API response ) print(f"Transcribed: {result.text}") print(f"Task ID: {result.task_id}") asyncio.run(transcribe_with_config()) ``` -------------------------------- ### High-Level Audio Transcription with SaluteSpeechClient Source: https://context7.com/mmua/salute_speech/llms.txt Demonstrates basic audio transcription using the high-level SaluteSpeechClient, which mimics OpenAI's Whisper API. It handles file upload, transcription, and retrieving results including text, duration, language, and segmented timestamps. Requires SBER_SPEECH_API_KEY environment variable. ```python import asyncio import os from salute_speech.speech_recognition import SaluteSpeechClient async def transcribe_audio(): # Initialize client with API credentials client = SaluteSpeechClient( client_credentials=os.getenv("SBER_SPEECH_API_KEY") ) # Transcribe audio file with open("meeting_recording.mp3", "rb") as audio_file: result = await client.audio.transcriptions.create( file=audio_file, language="ru-RU", poll_interval=1.0 ) # Access full transcription text print(f"Full transcript: {result.text}") print(f"Duration: {result.duration} seconds") print(f"Language: {result.language}") # Iterate through segments with timestamps for segment in result.segments or []: print(f"[{segment.start:.2f}s - {segment.end:.2f}s] {segment.text}") # Run async transcription asyncio.run(transcribe_audio()) ``` -------------------------------- ### Error Handling for API Calls Source: https://github.com/mmua/salute_speech/blob/master/README.md Provides a comprehensive `try-except` block demonstrating how to catch various specific exceptions that can occur during API interactions, such as authentication, file upload, or transcription task failures. ```python try: result = await client.audio.transcriptions.create(file=audio_file) except TokenRequestError as e: print(f"Authentication error: {e}") except FileUploadError as e: print(f"Upload failed: {e}") except TaskStatusResponseError as e: print(f"Transcription task failed: {e}") except ValidationError as e: print(f"Audio validation failed: {e}") except InvalidResponseError as e: print(f"Invalid API response: {e}") except APIError as e: print(f"API error: {e}") except SberSpeechError as e: print(f"General API error: {e}") ``` -------------------------------- ### Transcribe Audio to Text Source: https://github.com/mmua/salute_speech/blob/master/README.md Converts an audio file to text using the salute_speech tool. It first prepares the audio using ffmpeg (recommended to convert to mono) and then transcribes it to a text file. ```bash # Prepare audio (recommended: convert to mono) ffmpeg -i video.mp4 -ac 1 -ar 16000 audio.wav # Transcribe to text salute_speech transcribe-audio audio.wav -o transcript.txt ``` -------------------------------- ### Python - Advanced Speech Recognition Configuration Source: https://github.com/mmua/salute_speech/blob/master/README.md Demonstrates how to configure advanced speech recognition parameters using the SpeechRecognitionConfig class in Python. This allows customization of transcription variants, profanity filtering, and timeouts. ```python from salute_speech.speech_recognition import SpeechRecognitionConfig config = SpeechRecognitionConfig( hypotheses_count=3, # Number of transcription variants enable_profanity_filter=True, # Filter out profanity max_speech_timeout="30s", # Maximum timeout for speech segments # speaker_separation_options={...} # Optional: see official docs for available options ) result = await client.audio.transcriptions.create( file=audio_file, language="ru-RU", config=config ) ``` -------------------------------- ### Transcribe Audio to WebVTT Source: https://github.com/mmua/salute_speech/blob/master/README.md Converts an audio file to WebVTT format, suitable for web-based subtitles. The command transcribes the specified audio file and outputs it to a .vtt file. ```bash salute_speech transcribe-audio audio.wav -o transcript.vtt ``` -------------------------------- ### Manage API Tokens Automatically with Caching (Python) Source: https://context7.com/mmua/salute_speech/llms.txt This Python code snippet shows how to use the `TokenManager` from `salute_speech.utils.token` for automatic API token management. It handles token caching and automatic refreshing, simplifying secure API access. Dependencies include `salute_speech.utils.token` and `salute_speech.exceptions.TokenRequestError`. It requires valid client credentials. ```python from salute_speech.utils.token import TokenManager from salute_speech.exceptions import TokenRequestError # Initialize token manager with credentials token_manager = TokenManager(client_credentials="YOUR_CREDENTIALS") try: # Get valid token (automatically refreshes if expired) token = token_manager.get_valid_token() print(f"Access token: {token[:20]}...") # Token is automatically cached and reused # Subsequent calls use cached token until expiration token_again = token_manager.get_valid_token() # Manual token refresh (usually not needed) fresh_token = token_manager._request_token() except TokenRequestError as e: print(f"Token error [{e.status_code}]: {e.message}") # Possible causes: # - Invalid credentials # - Network connectivity issues # - Sber authentication service unavailable ``` -------------------------------- ### Write Transcription Results to Multiple Formats (Python) Source: https://context7.com/mmua/salute_speech/llms.txt This Python code demonstrates how to convert transcription results into various formats like TXT, VTT, SRT, TSV, and JSON using the `get_writer` function. It requires the `salute_speech.utils.result_writer` module and a `TranscriptionResponse` object. The output is written to specified files. ```python import sys from salute_speech.utils.result_writer import ( get_writer, filename_to_format, WriteTXT, WriteVTT, WriteSRT, WriteTSV, WriteJSON ) from salute_speech.speech_recognition import TranscriptionResponse # Assume we have a TranscriptionResponse object result = TranscriptionResponse( duration=125.5, language="ru", text="Полный текст транскрипции", segments=[ {"id": 0, "start": 0.0, "end": 3.5, "text": "Первая фраза"}, {"id": 1, "start": 3.5, "end": 7.2, "text": "Вторая фраза"} ] ) # Write to different formats with open("transcript.txt", "w", encoding="utf-8") as f: writer = get_writer("txt", f) writer(result) with open("subtitles.vtt", "w", encoding="utf-8") as f: writer = get_writer("vtt", f) writer(result) # Output: # WEBVTT # # 00:00.000 --> 00:03.500 # Первая фраза # # 00:03.500 --> 00:07.200 # Вторая фраза with open("subtitles.srt", "w", encoding="utf-8") as f: writer = get_writer("srt", f) writer(result) # Output: # 1 # 00:00:00,000 --> 00:00:03,500 # Первая фраза with open("data.tsv", "w", encoding="utf-8") as f: writer = get_writer("tsv", f) writer(result) # Output: start\tend\ttext # 0\t3500\tПервая фраза with open("result.json", "w", encoding="utf-8") as f: writer = get_writer("json", f) writer(result) # Infer format from filename output_format = filename_to_format("output.vtt") # Returns "vtt" ``` -------------------------------- ### POST /audio/transcriptions Source: https://github.com/mmua/salute_speech/blob/master/README.md Creates a transcription for the given audio file using the Sber Salute Speech API. Supports various audio formats and language codes. ```APIDOC ## POST /audio/transcriptions ### Description Creates a transcription for the given audio file. ### Method POST ### Endpoint /audio/transcriptions ### Parameters #### Query Parameters - **language** (str, optional) - Language code for transcription. Supported: `ru-RU`, `en-US`, `kk-KZ`. Defaults to "ru-RU" - **poll_interval** (float, optional) - Interval between status checks in seconds. Defaults to 1.0 #### Request Body - **file** (BinaryIO) - Required - An audio file opened in binary mode - **config** (SpeechRecognitionConfig, optional) - Advanced recognition tuning passed to the SberSpeech async API - **prompt** (str, optional) - Optional prompt to guide transcription (not yet supported) - **response_format** (str, optional) - Format of the response (not yet supported) ### Request Example ```python async with open("meeting.mp3", "rb") as audio_file: result = await client.audio.transcriptions.create( file=audio_file, language="ru-RU" ) print(result.text) ``` ### Response #### Success Response (200) - **TranscriptionResponse** (object) - Object containing transcription details *TranscriptionResponse Fields:* - **duration** (float) - The duration of the input audio in seconds - **language** (str) - The language of the input audio (e.g., `ru`, `en`) - **text** (str) - The full transcribed text (concatenation of segment texts) - **segments** (List[TranscriptionSegment] | None) - Segments of the transcribed text with timestamps - **status** (str) - Sber-specific job status (e.g., `DONE`) - **task_id** (str) - Sber-specific task identifier #### Response Example ```json { "duration": 123.45, "language": "ru", "text": "This is the transcribed text.", "segments": [ { "id": 0, "start": 0.5, "end": 3.2, "text": "This is the first segment." } ], "status": "DONE", "task_id": "abc123xyz789" } ``` ### Error Handling - **TokenRequestError**: Authentication error. - **FileUploadError**: Upload failed. - **TaskStatusResponseError**: Transcription task failed. - **ValidationError**: Audio validation failed. - **InvalidResponseError**: Invalid API response. - **APIError**: General API error. - **SberSpeechError**: General Sber Speech API error. ``` -------------------------------- ### Set API Key Source: https://github.com/mmua/salute_speech/blob/master/README.md Set your SBER Speech API key as an environment variable before running commands. Replace 'your_key_here' with your actual API key. ```bash export SBER_SPEECH_API_KEY=your_key_here ``` -------------------------------- ### SaluteSpeechClient - High-Level Audio Transcription Source: https://context7.com/mmua/salute_speech/llms.txt This section details the high-level `SaluteSpeechClient` for transcribing audio files. It mimics the OpenAI Whisper API and handles automatic format detection and asynchronous processing. ```APIDOC ## SaluteSpeechClient - High-Level Audio Transcription ### Description OpenAI Whisper-compatible client for transcribing audio files with automatic format detection and async processing. ### Method POST (implicitly via `client.audio.transcriptions.create`) ### Endpoint `client.audio.transcriptions.create` ### Parameters #### Path Parameters None #### Query Parameters - **language** (string) - Required - The language of the audio (e.g., "ru-RU", "en-US"). - **poll_interval** (float) - Optional - The interval in seconds to poll for task status. #### Request Body - **file** (file) - Required - The audio file to transcribe. - **config** (object) - Optional - Advanced recognition settings (see `SpeechRecognitionConfig` below). - **debug_dump** (string) - Optional - Path to save raw API response for debugging. ### Request Example ```python import asyncio import os from salute_speech.speech_recognition import SaluteSpeechClient async def transcribe_audio(): client = SaluteSpeechClient( client_credentials=os.getenv("SBER_SPEECH_API_KEY") ) with open("meeting_recording.mp3", "rb") as audio_file: result = await client.audio.transcriptions.create( file=audio_file, language="ru-RU", poll_interval=1.0 ) print(f"Full transcript: {result.text}") print(f"Duration: {result.duration} seconds") print(f"Language: {result.language}") for segment in result.segments or []: print(f"[{segment.start:.2f}s - {segment.end:.2f}s] {segment.text}") asyncio.run(transcribe_audio()) ``` ### Response #### Success Response (200) - **text** (string) - The full transcribed text. - **duration** (float) - The duration of the audio in seconds. - **language** (string) - The detected or specified language of the transcription. - **segments** (array) - An array of transcription segments, each with start time, end time, and text. - **task_id** (string) - The ID of the recognition task. #### Response Example ```json { "text": "This is the full transcription.", "duration": 15.5, "language": "en-US", "segments": [ { "start": 0.5, "end": 2.3, "text": "This is the first segment." } ], "task_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` -------------------------------- ### SberSpeechRecognition - Low-Level API Client Source: https://context7.com/mmua/salute_speech/llms.txt This section describes the low-level `SberSpeechRecognition` client, offering direct access to the Sber Speech API for building custom workflows. ```APIDOC ## SberSpeechRecognition - Low-Level API Client ### Description Direct access to Sber Speech API for custom workflows and fine-grained control over the transcription process. ### Method POST, GET (for various operations) ### Endpoint Configurable via `base_url` (default: `https://smartspeech.sber.ru/rest/v1/`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (Varies depending on the method: upload, recognize, status check, download) ### Request Example ```python from salute_speech.speech_recognition import ( SberSpeechRecognition, SpeechRecognitionConfig ) from time import sleep client = SberSpeechRecognition( client_credentials="YOUR_API_KEY", base_url="https://smartspeech.sber.ru/rest/v1/" ) # Step 1: Upload audio file with open("audio.mp3", "rb") as audio_file: file_id = client.upload_file(audio_file) print(f"Uploaded file ID: {file_id}") # Step 2: Start recognition task task = client.async_recognize( request_file_id=file_id, audio_encoding="MP3", sample_rate=44100, channels_count=2, language="ru-RU", config=SpeechRecognitionConfig(hypotheses_count=1) ) print(f"Task created: {task.id}, status: {task.status}") # Step 3: Poll for completion while True: status = client.get_task_status(task.id) print(f"Status: {status['status']}") if status["status"] == "ERROR": print(f"Task failed: {status.get('error_message')}") break elif status["status"] == "DONE": response_file_id = status["response_file_id"] break sleep(2) # Step 4: Download result result_json = client.download_result(response_file_id) print(f"Result: {result_json}") ``` ### Response #### Success Response (200) - **upload_file**: `file_id` (string) - **async_recognize**: Task object with `id` (string) and `status` (string) - **get_task_status**: Dictionary containing `status` (string) and optionally `response_file_id` (string) or `error_message` (string). - **download_result**: JSON object containing the transcription results. #### Response Example ```json { "file_id": "unique_file_identifier_123", "id": "task_abcde12345", "status": "DONE", "response_file_id": "result_file_xyz789", "result": { "text": "This is the low-level transcription result." } } ``` ``` -------------------------------- ### Transcribe Audio to JSON Source: https://github.com/mmua/salute_speech/blob/master/README.md Transcribes audio to JSON format, providing detailed timed segments. This is useful for programmatic access to transcription data. ```bash # JSON (timed segments) salute_speech transcribe-audio audio.wav -o transcript.json ``` -------------------------------- ### Python: Robust Error Handling with SaluteSpeechException Hierarchy Source: https://context7.com/mmua/salute_speech/llms.txt Implements structured exception handling for the Salute Speech client, utilizing a hierarchy of custom exceptions to manage various error scenarios. This includes handling authentication failures (TokenRequestError), file upload issues (FileUploadError), audio validation problems (ValidationError), task processing errors (TaskStatusResponseError), invalid API responses (InvalidResponseError), general API errors (APIError), and catch-all Sber Speech errors (SberSpeechError). ```python import asyncio from salute_speech.speech_recognition import SaluteSpeechClient from salute_speech.exceptions import ( SberSpeechError, # Base exception APIError, # API communication errors TokenRequestError, # Authentication failures FileUploadError, # Upload failures TaskStatusResponseError, # Task processing errors ValidationError, # Audio validation errors InvalidResponseError, # Malformed API responses InvalidAudioFormatError # Unsupported audio formats ) async def robust_transcription(): client = SaluteSpeechClient(client_credentials="YOUR_KEY") try: with open("audio.mp3", "rb") as audio_file: result = await client.audio.transcriptions.create( file=audio_file, language="ru-RU" ) print(result.text) except TokenRequestError as e: # Authentication failed: invalid credentials or token expired print(f"Auth error [{e.status_code}]: {e.message}") # Example: "Auth error [401]: Invalid credentials" except FileUploadError as e: # File upload to Sber servers failed print(f"Upload failed [{e.status_code}]: {e.message}") except ValidationError as e: # Audio format validation failed print(f"Audio validation error: {e.message}") # Example: "Too many channels (8) for MP3. Maximum allowed is 2" except TaskStatusResponseError as e: # Recognition task failed on server print(f"Task processing error: {e.message}") # Example: "Task failed: Audio file corrupted" except InvalidResponseError as e: # API returned malformed response print(f"Invalid response: {e.message}") except APIError as e: # Generic API error (network, server error, etc.) print(f"API error [{e.status_code}]: {e.message}") except SberSpeechError as e: # Catch-all for any Sber Speech errors print(f"General error: {e.message}") asyncio.run(robust_transcription()) ``` -------------------------------- ### Transcribe Audio to SRT Source: https://github.com/mmua/salute_speech/blob/master/README.md Transcribes audio into SRT (SubRip) subtitle format. This is a common format for video subtitles and can be directly used with most media players. ```bash # SRT subtitles salute_speech transcribe-audio audio.wav -o subtitles.srt ``` -------------------------------- ### Python: Detect and Validate Audio Parameters with AudioValidator Source: https://context7.com/mmua/salute_speech/llms.txt Utilizes the AudioValidator class to automatically detect and validate audio parameters such as encoding, sample rate, and channel count against Sber's requirements. It handles potential ValidationError exceptions, providing specific error messages for invalid formats, channel counts, or sample rates. ```python from salute_speech.utils.audio import AudioValidator from salute_speech.exceptions import ValidationError # Detect and validate audio parameters try: with open("podcast.flac", "rb") as audio_file: encoding, sample_rate, channels = AudioValidator.detect_and_validate(audio_file) print(f"Encoding: {encoding}") # e.g., "FLAC" print(f"Sample rate: {sample_rate} Hz") # e.g., 48000 print(f"Channels: {channels}") # e.g., 2 except ValidationError as e: print(f"Audio validation failed: {e.message}") # Example errors: # - "Too many channels (8) for MP3. Maximum allowed is 2" # - "Sample rate 192000Hz out of range [8000-96000]Hz for PCM_S16LE" # - "Invalid audio encoding: UNKNOWN_FORMAT" # Manual validation of known parameters try: validated = AudioValidator._validate_params( audio_encoding="PCM_S16LE", sample_rate=16000, channels_count=1 ) print(f"Validated parameters: {validated}") except ValidationError as e: print(f"Validation error: {e}") ``` -------------------------------- ### Debug Dump Raw Result Source: https://github.com/mmua/salute_speech/blob/master/README.md Dumps the raw JSON result from the Sber API for inspection. This is helpful for debugging and understanding the full output from the speech recognition service. ```bash # Dump raw Sber result for inspection salute_speech transcribe-audio audio.wav -o transcript.txt --debug_dump res.json ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.