|
| 1 | +# /// script |
| 2 | +# requires-python = ">=3.12" |
| 3 | +# dependencies = [ |
| 4 | +# "aiofile~=3.9.0", |
| 5 | +# "aws-sdk-transcribe-streaming", |
| 6 | +# ] |
| 7 | +# |
| 8 | +# [tool.uv.sources] |
| 9 | +# aws-sdk-transcribe-streaming = { path = "../" } |
| 10 | +# /// |
| 11 | +""" |
| 12 | +Audio file transcription example using AWS Transcribe Streaming. |
| 13 | +
|
| 14 | +This example demonstrates how to: |
| 15 | +- Read audio from a pre-recorded file |
| 16 | +- Stream audio to AWS Transcribe Streaming service with rate limiting |
| 17 | +- Receive and display transcription results as they arrive |
| 18 | +
|
| 19 | +Prerequisites: |
| 20 | +- AWS credentials configured (via environment variables) |
| 21 | +- An audio file (default: test.wav in PCM format) |
| 22 | +- [uv](https://docs.astral.sh/uv/getting-started/installation/) installed |
| 23 | +
|
| 24 | +Usage: |
| 25 | +- `uv run simple_file.py` |
| 26 | +""" |
| 27 | + |
| 28 | +import asyncio |
| 29 | +import time |
| 30 | +from pathlib import Path |
| 31 | + |
| 32 | +import aiofile |
| 33 | +from smithy_aws_core.identity import EnvironmentCredentialsResolver |
| 34 | +from smithy_core.aio.interfaces.eventstream import EventPublisher, EventReceiver |
| 35 | + |
| 36 | +from aws_sdk_transcribe_streaming.client import ( |
| 37 | + StartStreamTranscriptionInput, |
| 38 | + TranscribeStreamingClient, |
| 39 | +) |
| 40 | +from aws_sdk_transcribe_streaming.config import Config |
| 41 | +from aws_sdk_transcribe_streaming.models import ( |
| 42 | + AudioEvent, |
| 43 | + AudioStream, |
| 44 | + AudioStreamAudioEvent, |
| 45 | + TranscriptEvent, |
| 46 | + TranscriptResultStream, |
| 47 | +) |
| 48 | + |
| 49 | +AWS_REGION = "us-west-2" |
| 50 | +ENDPOINT_URI = f"https://transcribestreaming.{AWS_REGION}.amazonaws.com" |
| 51 | + |
| 52 | +SAMPLE_RATE = 16000 |
| 53 | +BYTES_PER_SAMPLE = 2 |
| 54 | +CHANNEL_NUMS = 1 |
| 55 | +AUDIO_PATH = Path(__file__).parent / "test.wav" |
| 56 | +CHUNK_SIZE = 1024 * 8 |
| 57 | + |
| 58 | + |
| 59 | +async def apply_realtime_delay( |
| 60 | + audio_stream: EventPublisher[AudioStream], |
| 61 | + reader, |
| 62 | + bytes_per_sample: int, |
| 63 | + sample_rate: float, |
| 64 | + channel_nums: int, |
| 65 | +) -> None: |
| 66 | + """Applies a delay when reading an audio file stream to simulate a real-time delay.""" |
| 67 | + start_time = time.time() |
| 68 | + elapsed_audio_time = 0.0 |
| 69 | + async for chunk in reader: |
| 70 | + await audio_stream.send( |
| 71 | + AudioStreamAudioEvent(value=AudioEvent(audio_chunk=chunk)) |
| 72 | + ) |
| 73 | + elapsed_audio_time += len(chunk) / ( |
| 74 | + bytes_per_sample * sample_rate * channel_nums |
| 75 | + ) |
| 76 | + # sleep to simulate real-time streaming |
| 77 | + wait_time = start_time + elapsed_audio_time - time.time() |
| 78 | + await asyncio.sleep(wait_time) |
| 79 | + |
| 80 | + |
| 81 | +class TranscriptResultStreamHandler: |
| 82 | + def __init__(self, stream: EventReceiver[TranscriptResultStream]): |
| 83 | + self.stream = stream |
| 84 | + |
| 85 | + async def handle_events(self): |
| 86 | + # Continuously receives events from the stream and delegates |
| 87 | + # to appropriate handlers based on event type. |
| 88 | + async for event in self.stream: |
| 89 | + if isinstance(event.value, TranscriptEvent): |
| 90 | + await self.handle_transcript_event(event.value) |
| 91 | + |
| 92 | + async def handle_transcript_event(self, event: TranscriptEvent): |
| 93 | + # This handler can be implemented to handle transcriptions as needed. |
| 94 | + # Here's an example to get started. |
| 95 | + if not event.transcript or not event.transcript.results: |
| 96 | + return |
| 97 | + |
| 98 | + results = event.transcript.results |
| 99 | + for result in results: |
| 100 | + if result.alternatives: |
| 101 | + for alt in result.alternatives: |
| 102 | + print(alt.transcript) |
| 103 | + |
| 104 | + |
| 105 | +async def write_chunks(audio_stream: EventPublisher[AudioStream]): |
| 106 | + # NOTE: For pre-recorded files longer than 5 minutes, the sent audio |
| 107 | + # chunks should be rate limited to match the realtime bitrate of the |
| 108 | + # audio stream to avoid signing issues. |
| 109 | + async with aiofile.AIOFile(AUDIO_PATH, "rb") as afp: |
| 110 | + reader = aiofile.Reader(afp, chunk_size=CHUNK_SIZE) |
| 111 | + await apply_realtime_delay( |
| 112 | + audio_stream, reader, BYTES_PER_SAMPLE, SAMPLE_RATE, CHANNEL_NUMS |
| 113 | + ) |
| 114 | + |
| 115 | + # Send an empty audio event to signal end of input |
| 116 | + await audio_stream.send(AudioStreamAudioEvent(value=AudioEvent(audio_chunk=b""))) |
| 117 | + # Small delay to ensure empty frame is sent before close |
| 118 | + await asyncio.sleep(0.4) |
| 119 | + await audio_stream.close() |
| 120 | + |
| 121 | + |
| 122 | +async def main(): |
| 123 | + # Initialize the Transcribe Streaming client |
| 124 | + client = TranscribeStreamingClient( |
| 125 | + config=Config( |
| 126 | + endpoint_uri=ENDPOINT_URI, |
| 127 | + region=AWS_REGION, |
| 128 | + aws_credentials_identity_resolver=EnvironmentCredentialsResolver(), |
| 129 | + ) |
| 130 | + ) |
| 131 | + |
| 132 | + # Start a streaming transcription session |
| 133 | + stream = await client.start_stream_transcription( |
| 134 | + input=StartStreamTranscriptionInput( |
| 135 | + language_code="en-US", |
| 136 | + media_sample_rate_hertz=SAMPLE_RATE, |
| 137 | + media_encoding="pcm", |
| 138 | + ) |
| 139 | + ) |
| 140 | + |
| 141 | + # Get the output stream for receiving transcription results |
| 142 | + _, output_stream = await stream.await_output() |
| 143 | + |
| 144 | + # Set up the handler for processing transcription events |
| 145 | + handler = TranscriptResultStreamHandler(output_stream) |
| 146 | + |
| 147 | + print("Transcribing audio from file...") |
| 148 | + print("===============================") |
| 149 | + |
| 150 | + # Run audio streaming and transcription handling concurrently |
| 151 | + await asyncio.gather(write_chunks(stream.input_stream), handler.handle_events()) |
| 152 | + |
| 153 | + |
| 154 | +if __name__ == "__main__": |
| 155 | + asyncio.run(main()) |
0 commit comments