### Install and Configure SonioxSRT Source: https://github.com/lucferreira-27/sonioxsrt/blob/master/ts/README.md Instructions for installing the package via npm and setting up the required environment variables for API authentication. ```shell npm install sonioxsrt export SONIOX_API_KEY="your_api_key_here" ``` -------------------------------- ### Run TypeScript Tests Source: https://github.com/lucferreira-27/sonioxsrt/blob/master/README.md Installs npm dependencies and runs the Vitest test suite for the SonioxSRT TypeScript package. ```Shell cd ts npm install npm test ``` -------------------------------- ### Run Python Tests Source: https://github.com/lucferreira-27/sonioxsrt/blob/master/README.md Sets up a Python virtual environment, installs development dependencies, and runs the pytest suite for the SonioxSRT Python package. ```Shell cd python python3 -m venv .venv . .venv/bin/activate python -m pip install -r requirements-dev.txt python -m pytest ``` -------------------------------- ### JSON: Transcript Token Format Example Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Illustrates the structure of the transcript output from the Soniox API, including token-level timing, confidence, speaker, and language information. ```json { "id": "837bdffa-5069-4dc0-ad98-72a5916dee77", "text": "Full transcript text...", "tokens": [ { "text": "BBC", "start_ms": 2730, "end_ms": 2790, "confidence": 0.949, "speaker": null, "language": null, "is_audio_event": null }, { "text": " Sound", "start_ms": 2970, "end_ms": 3030, "confidence": 0.938, "speaker": null, "language": null, "is_audio_event": null } ] } ``` -------------------------------- ### Configure Soniox API Key Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Set up the required API key for authentication with the Soniox service using environment variables or a .env file. ```bash export SONIOX_API_KEY= echo "SONIOX_API_KEY=" > .env ``` -------------------------------- ### Python: SubtitleConfig Options Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Demonstrates how to configure subtitle generation behavior using the SubtitleConfig class in Python. It includes parameters for silence duration, display duration, character limits, line counts, and segmentation rules. ```python from sonioxsrt import SubtitleConfig config = SubtitleConfig( gap_ms=1200, # Silence duration to trigger segment break (default: 1200) min_dur_ms=1000, # Minimum subtitle display duration (default: 1000) max_dur_ms=7000, # Maximum subtitle display duration (default: 7000) max_cps=17.0, # Maximum characters per second for readability (default: 17) max_cpl=42, # Maximum characters per line (default: 42) max_lines=2, # Maximum lines per subtitle (default: 2) line_split_delimiters=(".", ","), # Characters for preferred line breaks segment_on_sentence=True, # Break subtitles at sentence boundaries (default: True) split_on_speaker=False, # Break subtitles on speaker changes (default: False) ellipses=False, # Add "..." for continued sentences (default: False) ) ``` -------------------------------- ### Transcribe and Generate Subtitles Programmatically Source: https://github.com/lucferreira-27/sonioxsrt/blob/master/ts/README.md Demonstrates how to convert transcription tokens into SRT segments and write them to a file. It also shows the convenience method for direct file-to-SRT conversion. ```typescript import { SubtitleConfig, tokensToSubtitleSegments, renderSegments, writeSrtFile, srt } from "sonioxsrt"; import transcript from "../samples/response.json" assert { type: "json" }; const tokens = transcript.tokens ?? []; const config = new SubtitleConfig({ splitOnSpeaker: true, segmentOnSentence: true, lineSplitDelimiters: ["."] }); const segments = tokensToSubtitleSegments(tokens, config); const entries = renderSegments(segments, config); writeSrtFile(entries, "subtitles.srt"); // Convenience helper srt("../samples/response.json", "subtitles.srt"); ``` -------------------------------- ### Render and Write SRT File (Python) Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Renders subtitle segments and writes them to an SRT file. It takes processed segments and configuration as input and outputs a standard SRT file. ```Python entries = render_segments(segments, config) write_srt_file(entries, "output.srt") ``` -------------------------------- ### Run Realtime Transcription Session Source: https://github.com/lucferreira-27/sonioxsrt/blob/master/python/README.md Shows how to stream audio to the Soniox realtime WebSocket API and generate an SRT file from the resulting transcript. ```python from sonioxsrt import run_realtime_session result = run_realtime_session( "../samples/audio.mp3", model="stt-rt-preview-v2", language_hints=["en"], enable_language_identification=True, ) print(result.text) # Convert the aggregated realtime tokens into an SRT transcript srt(result.to_transcript(), output_path="realtime.srt") ``` -------------------------------- ### Low-Level Subtitle Processing (Python) Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Perform granular subtitle generation by manually extracting tokens, segmenting them based on custom configuration, and rendering the final SRT output. ```python import json from sonioxsrt import ( extract_tokens, tokens_to_subtitle_segments, render_segments, write_srt_file, SubtitleConfig, ) with open("transcript.json") as f: transcript = json.load(f) tokens = extract_tokens(transcript) config = SubtitleConfig( max_cpl=42, max_lines=2, line_split_delimiters=(".", ","), ) segments = tokens_to_subtitle_segments(tokens, config) print(f"Created {len(segments)} subtitle segments") ``` -------------------------------- ### Real-Time Streaming with Callback (Python) Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Processes transcription updates in real-time using a callback function. This is useful for displaying live captions or progress indicators during streaming. ```Python from sonioxsrt import run_realtime_session, RealTimeUpdate def on_update(update: RealTimeUpdate) -> None: """Called for each transcription update.""" print(f"[{len(update.final_tokens)} final, {len(update.non_final_tokens)} pending]") print(update.text[-200:]) # Show last 200 chars print("---") result = run_realtime_session( "podcast.mp3", model="stt-rt-preview-v2", on_update=on_update, chunk_size=3840, # Audio chunk size in bytes chunk_sleep=0.120, # Delay between chunks (simulates real-time) ) print(f"\nFinal transcript:\n{result.text}") ``` -------------------------------- ### SonioxClient for Manual API Control (Python) Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Utilizes the low-level SonioxClient for direct API access, enabling custom workflows and error handling. It supports file uploads, transcription job creation, status monitoring, and result fetching. ```Python from sonioxsrt import SonioxClient, require_api_key api_key = require_api_key() client = SonioxClient(api_key=api_key, base_url="https://api.soniox.com") try: # Upload file file_id = client.upload_file("audio.mp3") print(f"Uploaded file: {file_id}") # Create transcription job transcription_id = client.create_transcription( model="stt-async-preview", file_id=file_id, extra_options={"language_hints": ["en"]}, ) print(f"Created job: {transcription_id}") # Wait for completion client.wait_for_completion(transcription_id, poll_interval=2.0) # Fetch result transcript = client.fetch_transcript(transcription_id) print(f"Transcription complete: {len(transcript['tokens'])} tokens") finally: # Cleanup client.delete_transcription(transcription_id) client.delete_file(file_id) client.close() ``` -------------------------------- ### CLI: Transcribe Audio Files Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Transcribes audio files from the command line using Python or TypeScript. The CLI automatically loads environment variables from .env files. It supports local files or URLs and offers options to keep remote resources. ```bash # Python CLI cd python python3 -m sonioxsrt.cli.transcribe \ --audio ../samples/audio.mp3 \ --output transcript.json \ --model stt-async-preview \ --poll-interval 1.0 # From URL instead of local file python3 -m sonioxsrt.cli.transcribe \ --audio-url https://example.com/audio.mp3 \ --output transcript.json \ --keep-resources # Don't delete remote transcription ``` ```bash # TypeScript CLI cd ts npm run cli:transcribe -- \ --audio ../samples/audio.mp3 \ --output transcript.json ``` -------------------------------- ### Generate SRT Subtitles from Soniox Transcripts Source: https://github.com/lucferreira-27/sonioxsrt/blob/master/python/README.md Demonstrates how to use the library to convert Soniox transcript tokens or JSON files into SRT subtitle files. It shows both low-level segment processing and the high-level convenience helper. ```python from pathlib import Path from sonioxsrt import ( SubtitleConfig, tokens_to_subtitle_segments, render_segments, write_srt_file, srt, ) # Configure segmentation rules. config = SubtitleConfig(split_on_speaker=True) # Generate segments and write using the lower-level helpers. segments = tokens_to_subtitle_segments(tokens, config) write_srt_file(render_segments(segments, config), "subtitles.srt") # Using the convenience helper with a file path srt("../samples/response.json", output_path="subtitles.srt") ``` -------------------------------- ### Run Realtime Transcription Session Source: https://github.com/lucferreira-27/sonioxsrt/blob/master/ts/README.md Initiates a real-time WebSocket session to transcribe audio files using the Soniox streaming API. ```typescript import { runRealtimeSession } from "sonioxsrt"; const realtime = await runRealtimeSession({ audioPath: "../samples/audio.mp3", model: "stt-rt-preview-v2", languageHints: ["en"], enableLanguageIdentification: true }); console.log(realtime.text); ``` -------------------------------- ### Transcribe and Save to File (Python) Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Perform transcription and save the resulting JSON output directly to a specified file path in one operation. ```python from sonioxsrt import transcribe_to_file transcript = transcribe_to_file( audio_path="interview.wav", output_path="interview_transcript.json", model="stt-async-preview", ) print(f"Saved transcript to interview_transcript.json") ``` -------------------------------- ### Transcribe and Generate SRT (TypeScript) Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Provides functionality to transcribe audio and generate SRT files using idiomatic JavaScript/TypeScript APIs. It supports generating SRT from existing transcripts and with custom subtitle configurations. ```TypeScript import { transcribeAudio, srt, SubtitleConfig, tokensToSubtitleSegments, renderSegments, writeSrtFile, } from "sonioxsrt"; import transcript from "./response.json" assert { type: "json" }; // Generate SRT from existing transcript srt("./response.json", "subtitles.srt"); // With custom configuration const config = new SubtitleConfig({ gapMs: 1200, minDurMs: 1000, maxDurMs: 7000, maxCps: 17, maxCpl: 42, maxLines: 2, segmentOnSentence: true, splitOnSpeaker: true, lineSplitDelimiters: [""], }); const tokens = transcript.tokens ?? []; const segments = tokensToSubtitleSegments(tokens, config); const entries = renderSegments(segments, config); writeSrtFile(entries, "custom_subtitles.srt"); console.log(`Generated ${entries.length} subtitle entries`); ``` -------------------------------- ### TypeScript: Real-Time Audio Streaming Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Streams audio through the real-time WebSocket API using TypeScript. Requires the 'ws' package. It takes an audio file path, model, language hints, and enables language identification and speaker diarization. ```typescript import { runRealtimeSession } from "sonioxsrt"; const result = await runRealtimeSession({ audioPath: "./audio.mp3", model: "stt-rt-preview-v2", languageHints: ["en"], enableLanguageIdentification: true, enableSpeakerDiarization: true, }); console.log("Transcription:", result.text); console.log(`Tokens: ${result.finalTokens.length}`); ``` -------------------------------- ### Real-Time Streaming Transcription (Python) Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Streams audio to the Soniox real-time WebSocket API for live transcription. It requires the 'websockets' package and provides access to transcription results and final SRT output. ```Python from sonioxsrt import run_realtime_session, srt # Stream audio for real-time transcription result = run_realtime_session( "audio.mp3", model="stt-rt-preview-v2", language_hints=["en"], enable_language_identification=True, enable_speaker_diarization=True, ) # Access transcription results print(result.text) print(f"Model: {result.model}") print(f"Final tokens: {len(result.final_tokens)}") # Convert real-time results to SRT srt(result.to_transcript(), output_path="realtime_subtitles.srt") ``` -------------------------------- ### Transcribe Audio URL (Python) Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Transcribe audio directly from a public URL without requiring a local file upload. The API fetches the audio content from the provided source. ```python from sonioxsrt import transcribe_audio_url transcript = transcribe_audio_url( "https://example.com/podcast-episode.mp3", model="stt-async-preview", extra_options={"language_hints": ["en"]}, ) print(f"Transcribed {len(transcript['tokens'])} tokens") print(transcript["text"]) ``` -------------------------------- ### Batch Transcription CLI Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Transcribes audio files or URLs using the command line interface for batch processing. ```APIDOC ## POST /cli/transcribe ### Description Transcribes an audio file or URL and saves the output as a JSON transcript. ### Method POST ### Endpoint /cli/transcribe ### Parameters #### Query Parameters - **audio** (string) - Required - Path to local audio file. - **audio-url** (string) - Optional - URL to remote audio file. - **output** (string) - Required - Path to save the resulting JSON. - **model** (string) - Required - Transcription model identifier. ### Response #### Success Response (200) - **status** (string) - Success message indicating file creation. ``` -------------------------------- ### Transcribe Audio File (Python) Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Upload a local audio file to the Soniox API, poll for completion, and retrieve the transcript. This function manages the full lifecycle including file upload and remote resource cleanup. ```python from sonioxsrt import transcribe_audio_file transcript = transcribe_audio_file( "audio.mp3", model="stt-async-preview", poll_interval=1.0, keep_remote=False, ) print(transcript["text"]) for token in transcript["tokens"]: print(f"{token['text']} [{token['start_ms']}-{token['end_ms']}ms]") ``` -------------------------------- ### Subtitle Generation CLI Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Converts transcript JSON files into formatted SRT subtitle files with advanced layout options. ```APIDOC ## POST /cli/to_srt ### Description Converts a transcript JSON file into an SRT file with configurable constraints like character limits and line breaks. ### Method POST ### Endpoint /cli/to_srt ### Parameters #### Query Parameters - **input** (string) - Required - Path to transcript JSON. - **output** (string) - Required - Path to save SRT file. - **max-cps** (number) - Optional - Max characters per second. - **max-cpl** (number) - Optional - Max characters per line. - **translate-to** (string) - Optional - Target language for LLM translation. ### Response #### Success Response (200) - **status** (string) - Success message indicating SRT file generation. ``` -------------------------------- ### Real-time Transcription with SonioxSRT Source: https://github.com/lucferreira-27/sonioxsrt/blob/master/README.md Streams audio using the Soniox realtime transcription model and returns the transcribed text. Requires the 'websockets' library for Python and the optional 'ws' dependency for TypeScript. The model used is 'stt-rt-preview-v2'. ```Python from sonioxsrt import run_realtime_session # Stream audio using the realtime model (requires `pip install websockets`) session = run_realtime_session("../samples/audio.mp3", model="stt-rt-preview-v2") print(session.text) ``` ```TypeScript import { runRealtimeSession } from "sonioxsrt"; // Realtime transcription (requires the optional `ws` dependency) const session = await runRealtimeSession({ audioPath: "../samples/audio.mp3", model: "stt-rt-preview-v2" }); console.log(session.text); ``` -------------------------------- ### Real-Time Streaming API Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Initiates a real-time transcription session using a WebSocket connection to stream audio and receive text results. ```APIDOC ## POST /realtime/session ### Description Starts a real-time transcription session for streaming audio data. ### Method POST ### Endpoint /realtime/session ### Parameters #### Request Body - **audioPath** (string) - Required - Local path to the audio file. - **model** (string) - Required - The transcription model to use (e.g., stt-rt-preview-v2). - **languageHints** (array) - Optional - List of expected languages. - **enableLanguageIdentification** (boolean) - Optional - Whether to detect language automatically. - **enableSpeakerDiarization** (boolean) - Optional - Whether to identify different speakers. ### Response #### Success Response (200) - **text** (string) - The transcribed text. - **finalTokens** (array) - Detailed token-level timing information. ### Response Example { "text": "Hello world", "finalTokens": [] } ``` -------------------------------- ### CLI: Generate SRT Subtitles Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Converts transcript JSON files to SRT subtitle format with various formatting and translation options. Supports basic conversion, advanced formatting like gap duration, character limits, and line counts, as well as translation using LLMs. ```bash # Basic conversion python3 -m sonioxsrt.cli.to_srt \ --input transcript.json \ --output subtitles.srt # With formatting options python3 -m sonioxsrt.cli.to_srt \ --input transcript.json \ --output subtitles.srt \ --gap-ms 1500 \ --min-dur-ms 1200 \ --max-dur-ms 7000 \ --max-cps 15 \ --max-cpl 38 \ --max-lines 2 \ --segment-on-sentence \ --split-on-speaker \ --line-split-delimiters "." "," \ --ellipses # With translation python3 -m sonioxsrt.cli.to_srt \ --input transcript.json \ --output subtitles_es.srt \ --translate-to Spanish \ --translation-passes 3 \ --llm-model gpt-4o-mini ``` ```bash # TypeScript CLI npm run cli:to-srt -- \ --input transcript.json \ --output subtitles.srt \ --segment-on-sentence \ --line-split-delimiters "." ``` -------------------------------- ### Generate SRT Subtitles (Python) Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Convert a transcript JSON file into an SRT subtitle file using configurable segmentation rules such as character limits, duration constraints, and speaker-based splitting. ```python from pathlib import Path from sonioxsrt import srt, SubtitleConfig srt("transcript.json", output_path="subtitles.srt") config = SubtitleConfig( gap_ms=1200, min_dur_ms=1000, max_dur_ms=7000, max_cps=17.0, max_cpl=42, max_lines=2, segment_on_sentence=True, split_on_speaker=True, ellipses=False, ) output_path = srt( Path("transcript.json"), output_path="subtitles.srt", config=config, ) print(f"Generated subtitles at {output_path}") ``` -------------------------------- ### Translate Subtitles with LLM (Python) Source: https://context7.com/lucferreira-27/sonioxsrt/llms.txt Translates subtitle entries to a target language using an OpenAI-compatible LLM API. It supports both simple single-pass translation and a higher-quality draft-review-refine process. ```Python from sonioxsrt import ( srt, SubtitleConfig, extract_tokens, tokens_to_subtitle_segments, render_segments, translate_entries, translate_entries_with_review, write_srt_file, TranslationStats, ) import json # Load and process transcript with open("transcript.json") as f: transcript = json.load(f) config = SubtitleConfig(max_cpl=42, max_lines=2) tokens = extract_tokens(transcript) segments = tokens_to_subtitle_segments(tokens, config) entries = render_segments(segments, config) # Simple translation (single pass) stats = TranslationStats() translated = translate_entries( entries, target_language="Spanish", config=config, model="gpt-4o-mini", # Or use LLM_MODEL env var stats=stats, ) write_srt_file(translated, "subtitles_es.srt") print(f"Translation used {stats.total_tokens} tokens in {stats.calls} calls") # Higher quality translation (draft + review + refine) translated_reviewed = translate_entries_with_review( entries, target_language="Portuguese", config=config, chunk_size=200, # Process 200 subtitles per batch ) write_srt_file(translated_reviewed, "subtitles_pt.srt") ``` -------------------------------- ### Generate SRT Subtitles with SonioxSRT Source: https://github.com/lucferreira-27/sonioxsrt/blob/master/README.md Converts a Soniox API response JSON file into an SRT subtitle file. This function is available in both Python and TypeScript implementations of the SonioxSRT library. ```Python from pathlib import Path from sonioxsrt import srt # Convert the shared sample transcript into subtitles srt(Path("../samples/response.json"), output_path="subtitles.srt") print("SRT ready at subtitles.srt") ``` ```TypeScript import { srt } from "sonioxsrt"; // Convert the shared sample transcript into subtitles srt("../samples/response.json", "subtitles.srt"); console.log("SRT ready at subtitles.srt"); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.