diff --git a/.doc_gen/metadata/transcribe-streaming_metadata.yaml b/.doc_gen/metadata/transcribe-streaming_metadata.yaml index d12d40c3ae8..752ffafa33e 100644 --- a/.doc_gen/metadata/transcribe-streaming_metadata.yaml +++ b/.doc_gen/metadata/transcribe-streaming_metadata.yaml @@ -1,11 +1,11 @@ # zexi 0.4.3 -transcribe_streaming_StartStreamTranscription: +transcribe-streaming_StartStreamTranscription: languages: Java: versions: - sdk_version: 2 - github: javav2/example_code/transcribe + github: javav2/example_code/transcribe-streaming sdkguide: excerpts: - description: @@ -14,19 +14,19 @@ transcribe_streaming_StartStreamTranscription: C++: versions: - sdk_version: 1 - github: cpp/example_code/transcribe + github: cpp/example_code/transcribe-streaming excerpts: - description: snippet_tags: - transcribe.cpp.stream_transcription_async.code services: transcribe-streaming: {StartStreamTranscription} -transcribe_streaming_StartMedicalStreamTranscription: +transcribe-streaming_StartMedicalStreamTranscription: languages: Java: versions: - sdk_version: 2 - github: javav2/example_code/transcribe + github: javav2/example_code/transcribe-streaming sdkguide: excerpts: - description: diff --git a/cpp/example_code/transcribe/.media/transcribe-test-file.wav b/cpp/example_code/transcribe-streaming/.media/transcribe-test-file.wav similarity index 100% rename from cpp/example_code/transcribe/.media/transcribe-test-file.wav rename to cpp/example_code/transcribe-streaming/.media/transcribe-test-file.wav diff --git a/cpp/example_code/transcribe/CMakeLists.txt b/cpp/example_code/transcribe-streaming/CMakeLists.txt similarity index 100% rename from cpp/example_code/transcribe/CMakeLists.txt rename to cpp/example_code/transcribe-streaming/CMakeLists.txt diff --git a/cpp/example_code/transcribe/README.md b/cpp/example_code/transcribe-streaming/README.md similarity index 84% rename from cpp/example_code/transcribe/README.md rename to cpp/example_code/transcribe-streaming/README.md index 2d235431fb9..0f9dab3a97e 100644 --- a/cpp/example_code/transcribe/README.md +++ b/cpp/example_code/transcribe-streaming/README.md @@ -1,13 +1,13 @@ -# Amazon Transcribe code examples for the SDK for C++ +# Amazon Transcribe Streaming code examples for the SDK for C++ ## Overview -Shows how to use the AWS SDK for C++ to work with Amazon Transcribe. +Shows how to use the AWS SDK for C++ to work with Amazon Transcribe Streaming. -_Amazon Transcribe provides transcription services for your audio files and audio streams._ +_Amazon Transcribe Streaming produces real-time transcriptions for your media content._ ## ⚠ Important @@ -88,9 +88,9 @@ folder. ## Additional resources -- [Amazon Transcribe Developer Guide](https://docs.aws.amazon.com/transcribe/latest/dg/what-is.html) -- [Amazon Transcribe API Reference](https://docs.aws.amazon.com/transcribe/latest/APIReference/Welcome.html) -- [SDK for C++ Amazon Transcribe reference](https://sdk.amazonaws.com/cpp/api/LATEST/aws-cpp-sdk-transcribe/html/annotated.html) +- [Amazon Transcribe Streaming Developer Guide](https://docs.aws.amazon.com/transcribe/latest/dg/streaming.html) +- [Amazon Transcribe Streaming API Reference](https://docs.aws.amazon.com/transcribe/latest/APIReference/Welcome.html) +- [SDK for C++ Amazon Transcribe Streaming reference](https://sdk.amazonaws.com/cpp/api/LATEST/aws-cpp-sdk-transcribe/html/annotated.html) diff --git a/cpp/example_code/transcribe/get_transcript.cpp b/cpp/example_code/transcribe-streaming/get_transcript.cpp similarity index 100% rename from cpp/example_code/transcribe/get_transcript.cpp rename to cpp/example_code/transcribe-streaming/get_transcript.cpp diff --git a/javav2/example_code/transcribe-streaming/README.md b/javav2/example_code/transcribe-streaming/README.md new file mode 100644 index 00000000000..b68221aa797 --- /dev/null +++ b/javav2/example_code/transcribe-streaming/README.md @@ -0,0 +1,79 @@ +# Amazon Transcribe Streaming code examples for the SDK for Java 2.x + +## Overview + +Shows how to use the AWS SDK for Java 2.x to work with Amazon Transcribe Streaming. + + + + +_Amazon Transcribe Streaming produces real-time transcriptions for your media content._ + +## ⚠ Important + +* Running this code might result in charges to your AWS account. For more details, see [AWS Pricing](https://aws.amazon.com/pricing/) and [Free Tier](https://aws.amazon.com/free/). +* Running the tests might result in charges to your AWS account. +* We recommend that you grant your code least privilege. At most, grant only the minimum permissions required to perform the task. For more information, see [Grant least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege). +* This code is not tested in every AWS Region. For more information, see [AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services). + + + + +## Code examples + +### Prerequisites + +For prerequisites, see the [README](../../README.md#Prerequisites) in the `javav2` folder. + + + + + +### Single actions + +Code excerpts that show you how to call individual service functions. + +- [StartMedicalStreamTranscription](src/main/java/com/amazonaws/transcribestreaming/TranscribeMedicalStreamingDemoApp.java#L25) +- [StartStreamTranscription](src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoApp.java#L26) + + + + + +## Run the examples + +### Instructions + + + + + + + +### Tests + +⚠ Running tests might result in charges to your AWS account. + + +To find instructions for running these tests, see the [README](../../README.md#Tests) +in the `javav2` folder. + + + + + + +## Additional resources + +- [Amazon Transcribe Streaming Developer Guide](https://docs.aws.amazon.com/transcribe/latest/dg/streaming.html) +- [Amazon Transcribe Streaming API Reference](https://docs.aws.amazon.com/transcribe/latest/APIReference/Welcome.html) +- [SDK for Java 2.x Amazon Transcribe Streaming reference](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/transcribe/package-summary.html) + + + + +--- + +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: Apache-2.0 \ No newline at end of file diff --git a/javav2/example_code/transcribe-streaming/pom.xml b/javav2/example_code/transcribe-streaming/pom.xml new file mode 100644 index 00000000000..8846037ad2f --- /dev/null +++ b/javav2/example_code/transcribe-streaming/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + TranscribeJ2 + TranscribeJ2 + 1.0-SNAPSHOT + + UTF-8 + 17 + 17 + 17 + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + + + + + + + + software.amazon.awssdk + bom + 2.21.20 + pom + import + + + + + + org.junit.jupiter + junit-jupiter-api + 5.9.2 + test + + + org.junit.jupiter + junit-jupiter-engine + 5.9.2 + test + + + org.junit.platform + junit-platform-commons + 1.9.2 + + + org.junit.platform + junit-platform-launcher + 1.9.2 + test + + + org.slf4j + slf4j-log4j12 + 2.0.5 + + + software.amazon.awssdk + transcribe + + + software.amazon.awssdk + transcribestreaming + + + diff --git a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribe/AudioStreamPublisher.java b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/AudioStreamPublisher.java similarity index 96% rename from javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribe/AudioStreamPublisher.java rename to javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/AudioStreamPublisher.java index bc0941507d9..a69e2f7b9ac 100644 --- a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribe/AudioStreamPublisher.java +++ b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/AudioStreamPublisher.java @@ -1,110 +1,110 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -// snippet-start:[transcribe.java2.bidir_streaming_audiopublisher.complete] -package com.amazonaws.transcribe; - -// snippet-start:[transcribe.java2.bidir_streaming_audiopublisher.import] -import java.io.IOException; -import java.io.InputStream; -import java.io.UncheckedIOException; -import java.nio.ByteBuffer; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicLong; -import org.reactivestreams.Publisher; -import org.reactivestreams.Subscriber; -import org.reactivestreams.Subscription; -import software.amazon.awssdk.core.SdkBytes; -import software.amazon.awssdk.services.transcribestreaming.model.AudioEvent; -import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; -import software.amazon.awssdk.services.transcribestreaming.model.TranscribeStreamingException; -// snippet-end:[transcribe.java2.bidir_streaming_audiopublisher.import] - -// snippet-start:[transcribe.java2.bidir_streaming_audiopublisher.class] - -public class AudioStreamPublisher implements Publisher { - private final InputStream inputStream; - - public AudioStreamPublisher(InputStream inputStream) { - this.inputStream = inputStream; - } - - @Override - public void subscribe(Subscriber s) { - s.onSubscribe(new SubscriptionImpl(s, inputStream)); - } - - private class SubscriptionImpl implements Subscription { - private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1; - private ExecutorService executor = Executors.newFixedThreadPool(1); - private AtomicLong demand = new AtomicLong(0); - - private final Subscriber subscriber; - private final InputStream inputStream; - - private SubscriptionImpl(Subscriber s, InputStream inputStream) { - this.subscriber = s; - this.inputStream = inputStream; - } - - @Override - public void request(long n) { - if (n <= 0) { - subscriber.onError(new IllegalArgumentException("Demand must be positive")); - } - - demand.getAndAdd(n); - - executor.submit(() -> { - try { - do { - ByteBuffer audioBuffer = getNextEvent(); - if (audioBuffer.remaining() > 0) { - AudioEvent audioEvent = audioEventFromBuffer(audioBuffer); - subscriber.onNext(audioEvent); - } else { - subscriber.onComplete(); - break; - } - } while (demand.decrementAndGet() > 0); - } catch (TranscribeStreamingException e) { - subscriber.onError(e); - } - }); - } - - @Override - public void cancel() { - - } - - private ByteBuffer getNextEvent() { - ByteBuffer audioBuffer; - byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES]; - - int len = 0; - try { - len = inputStream.read(audioBytes); - - if (len <= 0) { - audioBuffer = ByteBuffer.allocate(0); - } else { - audioBuffer = ByteBuffer.wrap(audioBytes, 0, len); - } - } catch (IOException e) { - throw new UncheckedIOException(e); - } - - return audioBuffer; - } - - private AudioEvent audioEventFromBuffer(ByteBuffer bb) { - return AudioEvent.builder() - .audioChunk(SdkBytes.fromByteBuffer(bb)) - .build(); - } - } -} -// snippet-end:[transcribe.java2.bidir_streaming_audiopublisher.class] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[transcribe.java2.bidir_streaming_audiopublisher.complete] +package com.amazonaws.transcribestreaming; + +// snippet-start:[transcribe.java2.bidir_streaming_audiopublisher.import] +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.ByteBuffer; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicLong; +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.services.transcribestreaming.model.AudioEvent; +import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; +import software.amazon.awssdk.services.transcribestreaming.model.TranscribeStreamingException; +// snippet-end:[transcribe.java2.bidir_streaming_audiopublisher.import] + +// snippet-start:[transcribe.java2.bidir_streaming_audiopublisher.class] + +public class AudioStreamPublisher implements Publisher { + private final InputStream inputStream; + + public AudioStreamPublisher(InputStream inputStream) { + this.inputStream = inputStream; + } + + @Override + public void subscribe(Subscriber s) { + s.onSubscribe(new SubscriptionImpl(s, inputStream)); + } + + private class SubscriptionImpl implements Subscription { + private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1; + private ExecutorService executor = Executors.newFixedThreadPool(1); + private AtomicLong demand = new AtomicLong(0); + + private final Subscriber subscriber; + private final InputStream inputStream; + + private SubscriptionImpl(Subscriber s, InputStream inputStream) { + this.subscriber = s; + this.inputStream = inputStream; + } + + @Override + public void request(long n) { + if (n <= 0) { + subscriber.onError(new IllegalArgumentException("Demand must be positive")); + } + + demand.getAndAdd(n); + + executor.submit(() -> { + try { + do { + ByteBuffer audioBuffer = getNextEvent(); + if (audioBuffer.remaining() > 0) { + AudioEvent audioEvent = audioEventFromBuffer(audioBuffer); + subscriber.onNext(audioEvent); + } else { + subscriber.onComplete(); + break; + } + } while (demand.decrementAndGet() > 0); + } catch (TranscribeStreamingException e) { + subscriber.onError(e); + } + }); + } + + @Override + public void cancel() { + + } + + private ByteBuffer getNextEvent() { + ByteBuffer audioBuffer; + byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES]; + + int len = 0; + try { + len = inputStream.read(audioBytes); + + if (len <= 0) { + audioBuffer = ByteBuffer.allocate(0); + } else { + audioBuffer = ByteBuffer.wrap(audioBytes, 0, len); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + + return audioBuffer; + } + + private AudioEvent audioEventFromBuffer(ByteBuffer bb) { + return AudioEvent.builder() + .audioChunk(SdkBytes.fromByteBuffer(bb)) + .build(); + } + } +} +// snippet-end:[transcribe.java2.bidir_streaming_audiopublisher.class] // snippet-end:[transcribe.java2.bidir_streaming_audiopublisher.complete] \ No newline at end of file diff --git a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribe/BidirectionalStreaming.java b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/BidirectionalStreaming.java similarity index 95% rename from javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribe/BidirectionalStreaming.java rename to javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/BidirectionalStreaming.java index ce7539fa5d0..404eae852cb 100644 --- a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribe/BidirectionalStreaming.java +++ b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/BidirectionalStreaming.java @@ -1,78 +1,78 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -// snippet-start:[transcribe.java2.bidir_streaming.complete] -package com.amazonaws.transcribe; - -// snippet-start:[transcribe.java2.bidir_streaming.import] -import javax.sound.sampled.AudioFormat; -import javax.sound.sampled.AudioSystem; -import javax.sound.sampled.DataLine; -import javax.sound.sampled.TargetDataLine; -import javax.sound.sampled.AudioInputStream; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.transcribestreaming.TranscribeStreamingAsyncClient; -import software.amazon.awssdk.services.transcribestreaming.model.TranscribeStreamingException; -import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionRequest; -import software.amazon.awssdk.services.transcribestreaming.model.MediaEncoding; -import software.amazon.awssdk.services.transcribestreaming.model.LanguageCode; -import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler; -import software.amazon.awssdk.services.transcribestreaming.model.TranscriptEvent; -// snippet-end:[transcribe.java2.bidir_streaming.import] - -public class BidirectionalStreaming { - - private static Object TranscribeStreamingException; - - public static void main(String[] args) throws Exception { - - Region region = Region.US_WEST_2; - TranscribeStreamingAsyncClient client = TranscribeStreamingAsyncClient.builder() - .region(region) - .build(); - - convertAudio(client); - } - - // snippet-start:[transcribe.java2.bidir_streaming.main] - public static void convertAudio(TranscribeStreamingAsyncClient client) throws Exception { - - try { - - StartStreamTranscriptionRequest request = StartStreamTranscriptionRequest.builder() - .mediaEncoding(MediaEncoding.PCM) - .languageCode(LanguageCode.EN_US) - .mediaSampleRateHertz(16_000).build(); - - TargetDataLine mic = Microphone.get(); - mic.start(); - - AudioStreamPublisher publisher = new AudioStreamPublisher(new AudioInputStream(mic)); - - StartStreamTranscriptionResponseHandler response = StartStreamTranscriptionResponseHandler.builder() - .subscriber(e -> { - TranscriptEvent event = (TranscriptEvent) e; - event.transcript().results() - .forEach(r -> r.alternatives().forEach(a -> System.out.println(a.transcript()))); - }).build(); - - // Keeps Streaming until you end the Java program - client.startStreamTranscription(request, publisher, response); - - } catch (TranscribeStreamingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - // snippet-end:[transcribe.java2.bidir_streaming.main] - - public static TargetDataLine get() throws Exception { - AudioFormat format = new AudioFormat(16000, 16, 1, true, false); - DataLine.Info datalineInfo = new DataLine.Info(TargetDataLine.class, format); - - TargetDataLine dataLine = (TargetDataLine) AudioSystem.getLine(datalineInfo); - dataLine.open(format); - return dataLine; - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[transcribe.java2.bidir_streaming.complete] +package com.amazonaws.transcribestreaming; + +// snippet-start:[transcribe.java2.bidir_streaming.import] +import javax.sound.sampled.AudioFormat; +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.DataLine; +import javax.sound.sampled.TargetDataLine; +import javax.sound.sampled.AudioInputStream; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.transcribestreaming.TranscribeStreamingAsyncClient; +import software.amazon.awssdk.services.transcribestreaming.model.TranscribeStreamingException; +import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionRequest; +import software.amazon.awssdk.services.transcribestreaming.model.MediaEncoding; +import software.amazon.awssdk.services.transcribestreaming.model.LanguageCode; +import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler; +import software.amazon.awssdk.services.transcribestreaming.model.TranscriptEvent; +// snippet-end:[transcribe.java2.bidir_streaming.import] + +public class BidirectionalStreaming { + + private static Object TranscribeStreamingException; + + public static void main(String[] args) throws Exception { + + Region region = Region.US_WEST_2; + TranscribeStreamingAsyncClient client = TranscribeStreamingAsyncClient.builder() + .region(region) + .build(); + + convertAudio(client); + } + + // snippet-start:[transcribe.java2.bidir_streaming.main] + public static void convertAudio(TranscribeStreamingAsyncClient client) throws Exception { + + try { + + StartStreamTranscriptionRequest request = StartStreamTranscriptionRequest.builder() + .mediaEncoding(MediaEncoding.PCM) + .languageCode(LanguageCode.EN_US) + .mediaSampleRateHertz(16_000).build(); + + TargetDataLine mic = com.amazonaws.transcribestreaming.Microphone.get(); + mic.start(); + + AudioStreamPublisher publisher = new AudioStreamPublisher(new AudioInputStream(mic)); + + StartStreamTranscriptionResponseHandler response = StartStreamTranscriptionResponseHandler.builder() + .subscriber(e -> { + TranscriptEvent event = (TranscriptEvent) e; + event.transcript().results() + .forEach(r -> r.alternatives().forEach(a -> System.out.println(a.transcript()))); + }).build(); + + // Keeps Streaming until you end the Java program + client.startStreamTranscription(request, publisher, response); + + } catch (TranscribeStreamingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + // snippet-end:[transcribe.java2.bidir_streaming.main] + + public static TargetDataLine get() throws Exception { + AudioFormat format = new AudioFormat(16000, 16, 1, true, false); + DataLine.Info datalineInfo = new DataLine.Info(TargetDataLine.class, format); + + TargetDataLine dataLine = (TargetDataLine) AudioSystem.getLine(datalineInfo); + dataLine.open(format); + return dataLine; + } +} // snippet-end:[transcribe.java2.bidir_streaming.complete] \ No newline at end of file diff --git a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribe/Microphone.java b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/Microphone.java similarity index 94% rename from javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribe/Microphone.java rename to javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/Microphone.java index a86b84aef8c..a47a6390d5f 100644 --- a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribe/Microphone.java +++ b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/Microphone.java @@ -1,27 +1,27 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.amazonaws.transcribe; - -// snippet-start:[transcribe.java2.bidir_streaming_microphone.complete] - -// snippet-start:[transcribe.java2.bidir_streaming_microphone.import] -import javax.sound.sampled.AudioFormat; -import javax.sound.sampled.AudioSystem; -import javax.sound.sampled.DataLine; -import javax.sound.sampled.TargetDataLine; -// snippet-end:[transcribe.java2.bidir_streaming_microphone.import] - -public class Microphone { - - public static TargetDataLine get() throws Exception { - AudioFormat format = new AudioFormat(16000, 16, 1, true, false); - DataLine.Info datalineInfo = new DataLine.Info(TargetDataLine.class, format); - - TargetDataLine dataLine = (TargetDataLine) AudioSystem.getLine(datalineInfo); - dataLine.open(format); - - return dataLine; - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.amazonaws.transcribestreaming; + +// snippet-start:[transcribe.java2.bidir_streaming_microphone.complete] + +// snippet-start:[transcribe.java2.bidir_streaming_microphone.import] +import javax.sound.sampled.AudioFormat; +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.DataLine; +import javax.sound.sampled.TargetDataLine; +// snippet-end:[transcribe.java2.bidir_streaming_microphone.import] + +public class Microphone { + + public static TargetDataLine get() throws Exception { + AudioFormat format = new AudioFormat(16000, 16, 1, true, false); + DataLine.Info datalineInfo = new DataLine.Info(TargetDataLine.class, format); + + TargetDataLine dataLine = (TargetDataLine) AudioSystem.getLine(datalineInfo); + dataLine.open(format); + + return dataLine; + } +} // snippet-end:[transcribe.java2.bidir_streaming_microphone.complete] \ No newline at end of file diff --git a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/StreamTranscriptionBehavior.java b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/StreamTranscriptionBehavior.java similarity index 97% rename from javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/StreamTranscriptionBehavior.java rename to javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/StreamTranscriptionBehavior.java index 4b80615f582..ba994d13fb1 100644 --- a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/StreamTranscriptionBehavior.java +++ b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/StreamTranscriptionBehavior.java @@ -1,36 +1,36 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -// snippet-start:[transcribe.java-streaming-client-behavior] -package com.amazonaws.transcribestreaming; - -import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponse; -import software.amazon.awssdk.services.transcribestreaming.model.TranscriptResultStream; - -/** - * Defines how a stream response should be handled. - * You should build a class implementing this interface to define the behavior. - */ -public interface StreamTranscriptionBehavior { - /** - * Defines how to respond when encountering an error on the stream - * transcription. - */ - void onError(Throwable e); - - /** - * Defines how to respond to the Transcript result stream. - */ - void onStream(TranscriptResultStream e); - - /** - * Defines what to do on initiating a stream connection with the service. - */ - void onResponse(StartStreamTranscriptionResponse r); - - /** - * Defines what to do on stream completion - */ - void onComplete(); -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[transcribe.java-streaming-client-behavior] +package com.amazonaws.transcribestreaming; + +import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponse; +import software.amazon.awssdk.services.transcribestreaming.model.TranscriptResultStream; + +/** + * Defines how a stream response should be handled. + * You should build a class implementing this interface to define the behavior. + */ +public interface StreamTranscriptionBehavior { + /** + * Defines how to respond when encountering an error on the stream + * transcription. + */ + void onError(Throwable e); + + /** + * Defines how to respond to the Transcript result stream. + */ + void onStream(TranscriptResultStream e); + + /** + * Defines what to do on initiating a stream connection with the service. + */ + void onResponse(StartStreamTranscriptionResponse r); + + /** + * Defines what to do on stream completion + */ + void onComplete(); +} // snippet-end:[transcribe.java-streaming-client-behavior] \ No newline at end of file diff --git a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/StreamTranscriptionBehaviorImpl.java b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/StreamTranscriptionBehaviorImpl.java similarity index 97% rename from javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/StreamTranscriptionBehaviorImpl.java rename to javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/StreamTranscriptionBehaviorImpl.java index cfb2d945424..29b002b9341 100644 --- a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/StreamTranscriptionBehaviorImpl.java +++ b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/StreamTranscriptionBehaviorImpl.java @@ -1,43 +1,43 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.amazonaws.transcribestreaming; - -import software.amazon.awssdk.services.transcribestreaming.model.Result; -import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponse; -import software.amazon.awssdk.services.transcribestreaming.model.TranscriptEvent; -import software.amazon.awssdk.services.transcribestreaming.model.TranscriptResultStream; -import java.util.List; - -// snippet-start:[transcribe.java-streaming-client-behavior-imp] -public class StreamTranscriptionBehaviorImpl implements StreamTranscriptionBehavior { - - @Override - public void onError(Throwable e) { - System.out.println("=== Failure encountered ==="); - e.printStackTrace(); - } - - @Override - public void onStream(TranscriptResultStream e) { - List results = ((TranscriptEvent) e).transcript().results(); - if (results.size() > 0) { - if (results.get(0).alternatives().size() > 0) - if (!results.get(0).alternatives().get(0).transcript().isEmpty()) { - System.out.println(results.get(0).alternatives().get(0).transcript()); - } - } - } - - @Override - public void onResponse(StartStreamTranscriptionResponse r) { - - System.out.println(String.format("=== Received initial response. Request Id: %s ===", r.requestId())); - } - - @Override - public void onComplete() { - System.out.println("=== All records streamed successfully ==="); - } -} -// snippet-end:[transcribe.java-streaming-client-behavior-imp] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.amazonaws.transcribestreaming; + +import software.amazon.awssdk.services.transcribestreaming.model.Result; +import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponse; +import software.amazon.awssdk.services.transcribestreaming.model.TranscriptEvent; +import software.amazon.awssdk.services.transcribestreaming.model.TranscriptResultStream; +import java.util.List; + +// snippet-start:[transcribe.java-streaming-client-behavior-imp] +public class StreamTranscriptionBehaviorImpl implements StreamTranscriptionBehavior { + + @Override + public void onError(Throwable e) { + System.out.println("=== Failure encountered ==="); + e.printStackTrace(); + } + + @Override + public void onStream(TranscriptResultStream e) { + List results = ((TranscriptEvent) e).transcript().results(); + if (results.size() > 0) { + if (results.get(0).alternatives().size() > 0) + if (!results.get(0).alternatives().get(0).transcript().isEmpty()) { + System.out.println(results.get(0).alternatives().get(0).transcript()); + } + } + } + + @Override + public void onResponse(StartStreamTranscriptionResponse r) { + + System.out.println(String.format("=== Received initial response. Request Id: %s ===", r.requestId())); + } + + @Override + public void onComplete() { + System.out.println("=== All records streamed successfully ==="); + } +} +// snippet-end:[transcribe.java-streaming-client-behavior-imp] diff --git a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/StreamingRetryApp.java b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/StreamingRetryApp.java similarity index 97% rename from javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/StreamingRetryApp.java rename to javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/StreamingRetryApp.java index 5ef8cce385a..bb17dd95a77 100644 --- a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/StreamingRetryApp.java +++ b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/StreamingRetryApp.java @@ -1,95 +1,95 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.amazonaws.transcribestreaming; - -import org.reactivestreams.Publisher; -import org.reactivestreams.Subscriber; -import org.reactivestreams.Subscription; -import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; -import software.amazon.awssdk.services.transcribestreaming.model.LanguageCode; -import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionRequest; -import javax.sound.sampled.LineUnavailableException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.net.URISyntaxException; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -// snippet-start:[transcribe.java-streaming-retry-app] -public class StreamingRetryApp { - private static final String endpoint = "endpoint"; - private static final Region region = Region.US_EAST_1; - private static final int sample_rate = 28800; - private static final String encoding = " "; - private static final String language = LanguageCode.EN_US.toString(); - - public static void main(String args[]) throws URISyntaxException, ExecutionException, InterruptedException, - LineUnavailableException, FileNotFoundException { - /** - * Create Amazon Transcribe streaming retry client. - */ - - TranscribeStreamingRetryClient client = new TranscribeStreamingRetryClient( - EnvironmentVariableCredentialsProvider.create(), endpoint, region); - - StartStreamTranscriptionRequest request = StartStreamTranscriptionRequest.builder() - .languageCode(language) - .mediaEncoding(encoding) - .mediaSampleRateHertz(sample_rate) - .build(); - /** - * Start real-time speech recognition. The Amazon Transcribe streaming java - * client uses the Reactive-streams - * interface. For reference on Reactive-streams: - * https://github.com/reactive-streams/reactive-streams-jvm - */ - CompletableFuture result = client.startStreamTranscription( - /** - * Request parameters. Refer to API documentation for details. - */ - request, - /** - * Provide an input audio stream. - * For input from a microphone, use getStreamFromMic(). - * For input from a file, use getStreamFromFile(). - */ - new AudioStreamPublisher( - new FileInputStream(new File("FileName"))), - /** - * Object that defines the behavior on how to handle the stream - */ - new StreamTranscriptionBehaviorImpl()); - - /** - * Synchronous wait for stream to close, and close client connection - */ - result.get(); - client.close(); - } - - private static class AudioStreamPublisher implements Publisher { - private final InputStream inputStream; - private static Subscription currentSubscription; - - private AudioStreamPublisher(InputStream inputStream) { - this.inputStream = inputStream; - } - - @Override - public void subscribe(Subscriber s) { - if (this.currentSubscription == null) { - this.currentSubscription = new TranscribeStreamingDemoApp.SubscriptionImpl(s, inputStream); - } else { - this.currentSubscription.cancel(); - this.currentSubscription = new TranscribeStreamingDemoApp.SubscriptionImpl(s, inputStream); - } - s.onSubscribe(currentSubscription); - } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.amazonaws.transcribestreaming; + +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; +import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; +import software.amazon.awssdk.services.transcribestreaming.model.LanguageCode; +import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionRequest; +import javax.sound.sampled.LineUnavailableException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +// snippet-start:[transcribe.java-streaming-retry-app] +public class StreamingRetryApp { + private static final String endpoint = "endpoint"; + private static final Region region = Region.US_EAST_1; + private static final int sample_rate = 28800; + private static final String encoding = " "; + private static final String language = LanguageCode.EN_US.toString(); + + public static void main(String args[]) throws URISyntaxException, ExecutionException, InterruptedException, + LineUnavailableException, FileNotFoundException { + /** + * Create Amazon Transcribe streaming retry client. + */ + + TranscribeStreamingRetryClient client = new TranscribeStreamingRetryClient( + EnvironmentVariableCredentialsProvider.create(), endpoint, region); + + StartStreamTranscriptionRequest request = StartStreamTranscriptionRequest.builder() + .languageCode(language) + .mediaEncoding(encoding) + .mediaSampleRateHertz(sample_rate) + .build(); + /** + * Start real-time speech recognition. The Amazon Transcribe streaming java + * client uses the Reactive-streams + * interface. For reference on Reactive-streams: + * https://github.com/reactive-streams/reactive-streams-jvm + */ + CompletableFuture result = client.startStreamTranscription( + /** + * Request parameters. Refer to API documentation for details. + */ + request, + /** + * Provide an input audio stream. + * For input from a microphone, use getStreamFromMic(). + * For input from a file, use getStreamFromFile(). + */ + new AudioStreamPublisher( + new FileInputStream(new File("FileName"))), + /** + * Object that defines the behavior on how to handle the stream + */ + new StreamTranscriptionBehaviorImpl()); + + /** + * Synchronous wait for stream to close, and close client connection + */ + result.get(); + client.close(); + } + + private static class AudioStreamPublisher implements Publisher { + private final InputStream inputStream; + private static Subscription currentSubscription; + + private AudioStreamPublisher(InputStream inputStream) { + this.inputStream = inputStream; + } + + @Override + public void subscribe(Subscriber s) { + if (this.currentSubscription == null) { + this.currentSubscription = new TranscribeStreamingDemoApp.SubscriptionImpl(s, inputStream); + } else { + this.currentSubscription.cancel(); + this.currentSubscription = new TranscribeStreamingDemoApp.SubscriptionImpl(s, inputStream); + } + s.onSubscribe(currentSubscription); + } + } +} // snippet-end:[transcribe.java-streaming-retry-app] \ No newline at end of file diff --git a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/TranscribeMedicalStreamingDemoApp.java b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/TranscribeMedicalStreamingDemoApp.java similarity index 100% rename from javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/TranscribeMedicalStreamingDemoApp.java rename to javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/TranscribeMedicalStreamingDemoApp.java diff --git a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoApp.java b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoApp.java similarity index 97% rename from javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoApp.java rename to javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoApp.java index 5c555161fec..b68f92c784b 100644 --- a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoApp.java +++ b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoApp.java @@ -1,205 +1,205 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.amazonaws.transcribestreaming; - -import org.reactivestreams.Publisher; -import org.reactivestreams.Subscriber; -import org.reactivestreams.Subscription; -import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; -import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; -import software.amazon.awssdk.core.SdkBytes; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.transcribestreaming.TranscribeStreamingAsyncClient; -import software.amazon.awssdk.services.transcribestreaming.model.*; -import javax.sound.sampled.*; -import java.io.*; -import java.net.URISyntaxException; -import java.nio.ByteBuffer; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicLong; - -// snippet-start:[transcribe.java-streaming-demo] -public class TranscribeStreamingDemoApp { - private static final Region REGION = Region.US_EAST_1; - private static TranscribeStreamingAsyncClient client; - - public static void main(String args[]) - throws URISyntaxException, ExecutionException, InterruptedException, LineUnavailableException { - - client = TranscribeStreamingAsyncClient.builder() - .credentialsProvider(getCredentials()) - .region(REGION) - .build(); - - CompletableFuture result = client.startStreamTranscription(getRequest(16_000), - new AudioStreamPublisher(getStreamFromMic()), - getResponseHandler()); - - result.get(); - client.close(); - } - - private static InputStream getStreamFromMic() throws LineUnavailableException { - - // Signed PCM AudioFormat with 16kHz, 16 bit sample size, mono - int sampleRate = 16000; - AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false); - DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); - - if (!AudioSystem.isLineSupported(info)) { - System.out.println("Line not supported"); - System.exit(0); - } - - TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info); - line.open(format); - line.start(); - - InputStream audioStream = new AudioInputStream(line); - return audioStream; - } - - private static AwsCredentialsProvider getCredentials() { - return DefaultCredentialsProvider.create(); - } - - private static StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) { - return StartStreamTranscriptionRequest.builder() - .languageCode(LanguageCode.EN_US.toString()) - .mediaEncoding(MediaEncoding.PCM) - .mediaSampleRateHertz(mediaSampleRateHertz) - .build(); - } - - private static StartStreamTranscriptionResponseHandler getResponseHandler() { - return StartStreamTranscriptionResponseHandler.builder() - .onResponse(r -> { - System.out.println("Received Initial response"); - }) - .onError(e -> { - System.out.println(e.getMessage()); - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - System.out.println("Error Occurred: " + sw.toString()); - }) - .onComplete(() -> { - System.out.println("=== All records stream successfully ==="); - }) - .subscriber(event -> { - List results = ((TranscriptEvent) event).transcript().results(); - if (results.size() > 0) { - if (!results.get(0).alternatives().get(0).transcript().isEmpty()) { - System.out.println(results.get(0).alternatives().get(0).transcript()); - } - } - }) - .build(); - } - - private InputStream getStreamFromFile(String audioFileName) { - try { - File inputFile = new File(getClass().getClassLoader().getResource(audioFileName).getFile()); - InputStream audioStream = new FileInputStream(inputFile); - return audioStream; - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - } - - private static class AudioStreamPublisher implements Publisher { - private final InputStream inputStream; - private static Subscription currentSubscription; - - private AudioStreamPublisher(InputStream inputStream) { - this.inputStream = inputStream; - } - - @Override - public void subscribe(Subscriber s) { - - if (this.currentSubscription == null) { - this.currentSubscription = new SubscriptionImpl(s, inputStream); - } else { - this.currentSubscription.cancel(); - this.currentSubscription = new SubscriptionImpl(s, inputStream); - } - s.onSubscribe(currentSubscription); - } - } - - public static class SubscriptionImpl implements Subscription { - private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1; - private final Subscriber subscriber; - private final InputStream inputStream; - private ExecutorService executor = Executors.newFixedThreadPool(1); - private AtomicLong demand = new AtomicLong(0); - - SubscriptionImpl(Subscriber s, InputStream inputStream) { - this.subscriber = s; - this.inputStream = inputStream; - } - - @Override - public void request(long n) { - if (n <= 0) { - subscriber.onError(new IllegalArgumentException("Demand must be positive")); - } - - demand.getAndAdd(n); - - executor.submit(() -> { - try { - do { - ByteBuffer audioBuffer = getNextEvent(); - if (audioBuffer.remaining() > 0) { - AudioEvent audioEvent = audioEventFromBuffer(audioBuffer); - subscriber.onNext(audioEvent); - } else { - subscriber.onComplete(); - break; - } - } while (demand.decrementAndGet() > 0); - } catch (Exception e) { - subscriber.onError(e); - } - }); - } - - @Override - public void cancel() { - executor.shutdown(); - } - - private ByteBuffer getNextEvent() { - ByteBuffer audioBuffer = null; - byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES]; - - int len = 0; - try { - len = inputStream.read(audioBytes); - - if (len <= 0) { - audioBuffer = ByteBuffer.allocate(0); - } else { - audioBuffer = ByteBuffer.wrap(audioBytes, 0, len); - } - } catch (IOException e) { - throw new UncheckedIOException(e); - } - - return audioBuffer; - } - - private AudioEvent audioEventFromBuffer(ByteBuffer bb) { - return AudioEvent.builder() - .audioChunk(SdkBytes.fromByteBuffer(bb)) - .build(); - } - } -} -// snippet-end:[transcribe.java-streaming-demo] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.amazonaws.transcribestreaming; + +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; +import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; +import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.transcribestreaming.TranscribeStreamingAsyncClient; +import software.amazon.awssdk.services.transcribestreaming.model.*; +import javax.sound.sampled.*; +import java.io.*; +import java.net.URISyntaxException; +import java.nio.ByteBuffer; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicLong; + +// snippet-start:[transcribe.java-streaming-demo] +public class TranscribeStreamingDemoApp { + private static final Region REGION = Region.US_EAST_1; + private static TranscribeStreamingAsyncClient client; + + public static void main(String args[]) + throws URISyntaxException, ExecutionException, InterruptedException, LineUnavailableException { + + client = TranscribeStreamingAsyncClient.builder() + .credentialsProvider(getCredentials()) + .region(REGION) + .build(); + + CompletableFuture result = client.startStreamTranscription(getRequest(16_000), + new AudioStreamPublisher(getStreamFromMic()), + getResponseHandler()); + + result.get(); + client.close(); + } + + private static InputStream getStreamFromMic() throws LineUnavailableException { + + // Signed PCM AudioFormat with 16kHz, 16 bit sample size, mono + int sampleRate = 16000; + AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false); + DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); + + if (!AudioSystem.isLineSupported(info)) { + System.out.println("Line not supported"); + System.exit(0); + } + + TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info); + line.open(format); + line.start(); + + InputStream audioStream = new AudioInputStream(line); + return audioStream; + } + + private static AwsCredentialsProvider getCredentials() { + return DefaultCredentialsProvider.create(); + } + + private static StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) { + return StartStreamTranscriptionRequest.builder() + .languageCode(LanguageCode.EN_US.toString()) + .mediaEncoding(MediaEncoding.PCM) + .mediaSampleRateHertz(mediaSampleRateHertz) + .build(); + } + + private static StartStreamTranscriptionResponseHandler getResponseHandler() { + return StartStreamTranscriptionResponseHandler.builder() + .onResponse(r -> { + System.out.println("Received Initial response"); + }) + .onError(e -> { + System.out.println(e.getMessage()); + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + System.out.println("Error Occurred: " + sw.toString()); + }) + .onComplete(() -> { + System.out.println("=== All records stream successfully ==="); + }) + .subscriber(event -> { + List results = ((TranscriptEvent) event).transcript().results(); + if (results.size() > 0) { + if (!results.get(0).alternatives().get(0).transcript().isEmpty()) { + System.out.println(results.get(0).alternatives().get(0).transcript()); + } + } + }) + .build(); + } + + private InputStream getStreamFromFile(String audioFileName) { + try { + File inputFile = new File(getClass().getClassLoader().getResource(audioFileName).getFile()); + InputStream audioStream = new FileInputStream(inputFile); + return audioStream; + } catch (FileNotFoundException e) { + throw new RuntimeException(e); + } + } + + private static class AudioStreamPublisher implements Publisher { + private final InputStream inputStream; + private static Subscription currentSubscription; + + private AudioStreamPublisher(InputStream inputStream) { + this.inputStream = inputStream; + } + + @Override + public void subscribe(Subscriber s) { + + if (this.currentSubscription == null) { + this.currentSubscription = new SubscriptionImpl(s, inputStream); + } else { + this.currentSubscription.cancel(); + this.currentSubscription = new SubscriptionImpl(s, inputStream); + } + s.onSubscribe(currentSubscription); + } + } + + public static class SubscriptionImpl implements Subscription { + private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1; + private final Subscriber subscriber; + private final InputStream inputStream; + private ExecutorService executor = Executors.newFixedThreadPool(1); + private AtomicLong demand = new AtomicLong(0); + + SubscriptionImpl(Subscriber s, InputStream inputStream) { + this.subscriber = s; + this.inputStream = inputStream; + } + + @Override + public void request(long n) { + if (n <= 0) { + subscriber.onError(new IllegalArgumentException("Demand must be positive")); + } + + demand.getAndAdd(n); + + executor.submit(() -> { + try { + do { + ByteBuffer audioBuffer = getNextEvent(); + if (audioBuffer.remaining() > 0) { + AudioEvent audioEvent = audioEventFromBuffer(audioBuffer); + subscriber.onNext(audioEvent); + } else { + subscriber.onComplete(); + break; + } + } while (demand.decrementAndGet() > 0); + } catch (Exception e) { + subscriber.onError(e); + } + }); + } + + @Override + public void cancel() { + executor.shutdown(); + } + + private ByteBuffer getNextEvent() { + ByteBuffer audioBuffer = null; + byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES]; + + int len = 0; + try { + len = inputStream.read(audioBytes); + + if (len <= 0) { + audioBuffer = ByteBuffer.allocate(0); + } else { + audioBuffer = ByteBuffer.wrap(audioBytes, 0, len); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + + return audioBuffer; + } + + private AudioEvent audioEventFromBuffer(ByteBuffer bb) { + return AudioEvent.builder() + .audioChunk(SdkBytes.fromByteBuffer(bb)) + .build(); + } + } +} +// snippet-end:[transcribe.java-streaming-demo] diff --git a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoFile.java b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoFile.java similarity index 97% rename from javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoFile.java rename to javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoFile.java index 2acb9a4d710..db05e1f4a95 100644 --- a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoFile.java +++ b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoFile.java @@ -1,199 +1,199 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.amazonaws.transcribestreaming; - -// snippet-start:[transcribe.java-streaming-demo-file.import] -import org.reactivestreams.Publisher; -import org.reactivestreams.Subscriber; -import org.reactivestreams.Subscription; -import software.amazon.awssdk.core.SdkBytes; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.transcribestreaming.TranscribeStreamingAsyncClient; -import software.amazon.awssdk.services.transcribestreaming.model.*; -import java.io.*; -import java.nio.ByteBuffer; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicLong; -// snippet-end:[transcribe.java-streaming-demo-file.import] - -// snippet-start:[transcribe.java-streaming-demo-file.main] -/** - * To run this AWS code example, ensure that you have set up your development - * environment, including your AWS credentials. - * - * For information, see this documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class TranscribeStreamingDemoFile { - private static final Region REGION = Region.US_EAST_1; - private static TranscribeStreamingAsyncClient client; - - public static void main(String args[]) throws ExecutionException, InterruptedException { - - final String USAGE = "\n" + - "Usage:\n" + - " \n\n" + - "Where:\n" + - " file - the location of a PCM file to transcribe. In this example, ensure the PCM file is 16 hertz (Hz). \n"; - - if (args.length != 1) { - System.out.println(USAGE); - System.exit(1); - } - - String file = args[0]; - client = TranscribeStreamingAsyncClient.builder() - .region(REGION) - .build(); - - CompletableFuture result = client.startStreamTranscription(getRequest(16_000), - new AudioStreamPublisher(getStreamFromFile(file)), - getResponseHandler()); - - result.get(); - client.close(); - } - - private static InputStream getStreamFromFile(String file) { - try { - File inputFile = new File(file); - InputStream audioStream = new FileInputStream(inputFile); - return audioStream; - - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - } - - private static StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) { - return StartStreamTranscriptionRequest.builder() - .languageCode(LanguageCode.EN_US) - .mediaEncoding(MediaEncoding.PCM) - .mediaSampleRateHertz(mediaSampleRateHertz) - .build(); - } - - private static StartStreamTranscriptionResponseHandler getResponseHandler() { - return StartStreamTranscriptionResponseHandler.builder() - .onResponse(r -> { - System.out.println("Received Initial response"); - }) - .onError(e -> { - System.out.println(e.getMessage()); - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - System.out.println("Error Occurred: " + sw.toString()); - }) - .onComplete(() -> { - System.out.println("=== All records stream successfully ==="); - }) - .subscriber(event -> { - List results = ((TranscriptEvent) event).transcript().results(); - if (results.size() > 0) { - if (!results.get(0).alternatives().get(0).transcript().isEmpty()) { - System.out.println(results.get(0).alternatives().get(0).transcript()); - } - } - }) - .build(); - } - - private static class AudioStreamPublisher implements Publisher { - private final InputStream inputStream; - private static Subscription currentSubscription; - - private AudioStreamPublisher(InputStream inputStream) { - this.inputStream = inputStream; - } - - @Override - public void subscribe(Subscriber s) { - - if (this.currentSubscription == null) { - this.currentSubscription = new SubscriptionImpl(s, inputStream); - } else { - this.currentSubscription.cancel(); - this.currentSubscription = new SubscriptionImpl(s, inputStream); - } - s.onSubscribe(currentSubscription); - } - } - - public static class SubscriptionImpl implements Subscription { - private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1; - private final Subscriber subscriber; - private final InputStream inputStream; - private ExecutorService executor = Executors.newFixedThreadPool(1); - private AtomicLong demand = new AtomicLong(0); - - SubscriptionImpl(Subscriber s, InputStream inputStream) { - this.subscriber = s; - this.inputStream = inputStream; - } - - @Override - public void request(long n) { - if (n <= 0) { - subscriber.onError(new IllegalArgumentException("Demand must be positive")); - } - - demand.getAndAdd(n); - - executor.submit(() -> { - try { - do { - ByteBuffer audioBuffer = getNextEvent(); - if (audioBuffer.remaining() > 0) { - AudioEvent audioEvent = audioEventFromBuffer(audioBuffer); - subscriber.onNext(audioEvent); - } else { - subscriber.onComplete(); - break; - } - } while (demand.decrementAndGet() > 0); - } catch (Exception e) { - subscriber.onError(e); - } - }); - } - - @Override - public void cancel() { - executor.shutdown(); - } - - private ByteBuffer getNextEvent() { - ByteBuffer audioBuffer = null; - byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES]; - - int len = 0; - try { - len = inputStream.read(audioBytes); - - if (len <= 0) { - audioBuffer = ByteBuffer.allocate(0); - } else { - audioBuffer = ByteBuffer.wrap(audioBytes, 0, len); - } - } catch (IOException e) { - throw new UncheckedIOException(e); - } - - return audioBuffer; - } - - private AudioEvent audioEventFromBuffer(ByteBuffer bb) { - return AudioEvent.builder() - .audioChunk(SdkBytes.fromByteBuffer(bb)) - .build(); - } - } -} -// snippet-end:[transcribe.java-streaming-demo-file.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.amazonaws.transcribestreaming; + +// snippet-start:[transcribe.java-streaming-demo-file.import] +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.transcribestreaming.TranscribeStreamingAsyncClient; +import software.amazon.awssdk.services.transcribestreaming.model.*; +import java.io.*; +import java.nio.ByteBuffer; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicLong; +// snippet-end:[transcribe.java-streaming-demo-file.import] + +// snippet-start:[transcribe.java-streaming-demo-file.main] +/** + * To run this AWS code example, ensure that you have set up your development + * environment, including your AWS credentials. + * + * For information, see this documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class TranscribeStreamingDemoFile { + private static final Region REGION = Region.US_EAST_1; + private static TranscribeStreamingAsyncClient client; + + public static void main(String args[]) throws ExecutionException, InterruptedException { + + final String USAGE = "\n" + + "Usage:\n" + + " \n\n" + + "Where:\n" + + " file - the location of a PCM file to transcribe. In this example, ensure the PCM file is 16 hertz (Hz). \n"; + + if (args.length != 1) { + System.out.println(USAGE); + System.exit(1); + } + + String file = args[0]; + client = TranscribeStreamingAsyncClient.builder() + .region(REGION) + .build(); + + CompletableFuture result = client.startStreamTranscription(getRequest(16_000), + new AudioStreamPublisher(getStreamFromFile(file)), + getResponseHandler()); + + result.get(); + client.close(); + } + + private static InputStream getStreamFromFile(String file) { + try { + File inputFile = new File(file); + InputStream audioStream = new FileInputStream(inputFile); + return audioStream; + + } catch (FileNotFoundException e) { + throw new RuntimeException(e); + } + } + + private static StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) { + return StartStreamTranscriptionRequest.builder() + .languageCode(LanguageCode.EN_US) + .mediaEncoding(MediaEncoding.PCM) + .mediaSampleRateHertz(mediaSampleRateHertz) + .build(); + } + + private static StartStreamTranscriptionResponseHandler getResponseHandler() { + return StartStreamTranscriptionResponseHandler.builder() + .onResponse(r -> { + System.out.println("Received Initial response"); + }) + .onError(e -> { + System.out.println(e.getMessage()); + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + System.out.println("Error Occurred: " + sw.toString()); + }) + .onComplete(() -> { + System.out.println("=== All records stream successfully ==="); + }) + .subscriber(event -> { + List results = ((TranscriptEvent) event).transcript().results(); + if (results.size() > 0) { + if (!results.get(0).alternatives().get(0).transcript().isEmpty()) { + System.out.println(results.get(0).alternatives().get(0).transcript()); + } + } + }) + .build(); + } + + private static class AudioStreamPublisher implements Publisher { + private final InputStream inputStream; + private static Subscription currentSubscription; + + private AudioStreamPublisher(InputStream inputStream) { + this.inputStream = inputStream; + } + + @Override + public void subscribe(Subscriber s) { + + if (this.currentSubscription == null) { + this.currentSubscription = new SubscriptionImpl(s, inputStream); + } else { + this.currentSubscription.cancel(); + this.currentSubscription = new SubscriptionImpl(s, inputStream); + } + s.onSubscribe(currentSubscription); + } + } + + public static class SubscriptionImpl implements Subscription { + private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1; + private final Subscriber subscriber; + private final InputStream inputStream; + private ExecutorService executor = Executors.newFixedThreadPool(1); + private AtomicLong demand = new AtomicLong(0); + + SubscriptionImpl(Subscriber s, InputStream inputStream) { + this.subscriber = s; + this.inputStream = inputStream; + } + + @Override + public void request(long n) { + if (n <= 0) { + subscriber.onError(new IllegalArgumentException("Demand must be positive")); + } + + demand.getAndAdd(n); + + executor.submit(() -> { + try { + do { + ByteBuffer audioBuffer = getNextEvent(); + if (audioBuffer.remaining() > 0) { + AudioEvent audioEvent = audioEventFromBuffer(audioBuffer); + subscriber.onNext(audioEvent); + } else { + subscriber.onComplete(); + break; + } + } while (demand.decrementAndGet() > 0); + } catch (Exception e) { + subscriber.onError(e); + } + }); + } + + @Override + public void cancel() { + executor.shutdown(); + } + + private ByteBuffer getNextEvent() { + ByteBuffer audioBuffer = null; + byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES]; + + int len = 0; + try { + len = inputStream.read(audioBytes); + + if (len <= 0) { + audioBuffer = ByteBuffer.allocate(0); + } else { + audioBuffer = ByteBuffer.wrap(audioBytes, 0, len); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + + return audioBuffer; + } + + private AudioEvent audioEventFromBuffer(ByteBuffer bb) { + return AudioEvent.builder() + .audioChunk(SdkBytes.fromByteBuffer(bb)) + .build(); + } + } +} +// snippet-end:[transcribe.java-streaming-demo-file.main] diff --git a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingRetryClient.java b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingRetryClient.java similarity index 97% rename from javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingRetryClient.java rename to javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingRetryClient.java index 47e5a9943b7..8e907cda13c 100644 --- a/javav2/example_code/transcribe/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingRetryClient.java +++ b/javav2/example_code/transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingRetryClient.java @@ -1,194 +1,194 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.amazonaws.transcribestreaming; - -import org.reactivestreams.Publisher; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; -import software.amazon.awssdk.auth.signer.EventStreamAws4Signer; -import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.transcribestreaming.TranscribeStreamingAsyncClient; -import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; -import software.amazon.awssdk.services.transcribestreaming.model.BadRequestException; -import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionRequest; -import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; - -/** - * Build a client wrapper around the Amazon Transcribe client to retry - * on an exception that can be retried. - */ -// snippet-start:[transcribe.java-streaming-retry-client] -public class TranscribeStreamingRetryClient { - - private static final int DEFAULT_MAX_RETRIES = 10; - private static final int DEFAULT_MAX_SLEEP_TIME_MILLS = 100; - private static final Logger log = LoggerFactory.getLogger(TranscribeStreamingRetryClient.class); - private final TranscribeStreamingAsyncClient client; - List> nonRetriableExceptions = Arrays.asList(BadRequestException.class); - private int maxRetries = DEFAULT_MAX_RETRIES; - private int sleepTime = DEFAULT_MAX_SLEEP_TIME_MILLS; - - /** - * Create a TranscribeStreamingRetryClient with given credential and - * configuration - */ - public TranscribeStreamingRetryClient(AwsCredentialsProvider creds, - String endpoint, Region region) throws URISyntaxException { - this(TranscribeStreamingAsyncClient.builder() - .overrideConfiguration( - c -> c.putAdvancedOption( - SdkAdvancedClientOption.SIGNER, - EventStreamAws4Signer.create())) - .credentialsProvider(creds) - .endpointOverride(new URI(endpoint)) - .region(region) - .build()); - } - - /** - * Initiate TranscribeStreamingRetryClient with TranscribeStreamingAsyncClient - */ - - public TranscribeStreamingRetryClient(TranscribeStreamingAsyncClient client) { - this.client = client; - } - - /** - * Get Max retries - */ - public int getMaxRetries() { - return maxRetries; - } - - /** - * Set Max retries - */ - public void setMaxRetries(int maxRetries) { - this.maxRetries = maxRetries; - } - - /** - * Get sleep time - */ - public int getSleepTime() { - return sleepTime; - } - - /** - * Set sleep time between retries - */ - public void setSleepTime(int sleepTime) { - this.sleepTime = sleepTime; - } - - /** - * Initiate a Stream Transcription with retry. - */ - - public CompletableFuture startStreamTranscription(final StartStreamTranscriptionRequest request, - final Publisher publisher, - final StreamTranscriptionBehavior responseHandler) { - - CompletableFuture finalFuture = new CompletableFuture<>(); - - recursiveStartStream(rebuildRequestWithSession(request), publisher, responseHandler, finalFuture, 0); - - return finalFuture; - } - - /** - * Recursively call startStreamTranscription() until the request is completed or - * we run out of retries. - * - */ - private void recursiveStartStream(final StartStreamTranscriptionRequest request, - final Publisher publisher, - final StreamTranscriptionBehavior responseHandler, - final CompletableFuture finalFuture, - final int retryAttempt) { - CompletableFuture result = client.startStreamTranscription(request, publisher, - getResponseHandler(responseHandler)); - result.whenComplete((r, e) -> { - if (e != null) { - log.debug("Error occured:", e); - - if (retryAttempt <= maxRetries && isExceptionRetriable(e)) { - log.debug("Retriable error occurred and will be retried."); - log.debug("Sleeping for sometime before retrying..."); - try { - Thread.sleep(sleepTime); - } catch (InterruptedException e1) { - log.debug("Unable to sleep. Failed with exception: ", e); - e1.printStackTrace(); - } - log.debug("Making retry attempt: " + (retryAttempt + 1)); - recursiveStartStream(request, publisher, responseHandler, finalFuture, retryAttempt + 1); - } else { - log.error("Encountered unretriable exception or ran out of retries. "); - responseHandler.onError(e); - finalFuture.completeExceptionally(e); - } - } else { - responseHandler.onComplete(); - finalFuture.complete(null); - } - }); - } - - private StartStreamTranscriptionRequest rebuildRequestWithSession(StartStreamTranscriptionRequest request) { - return StartStreamTranscriptionRequest.builder() - .languageCode(request.languageCode()) - .mediaEncoding(request.mediaEncoding()) - .mediaSampleRateHertz(request.mediaSampleRateHertz()) - .sessionId(UUID.randomUUID().toString()) - .build(); - } - - /** - * StartStreamTranscriptionResponseHandler implements subscriber of transcript - * stream - * Output is printed to standard output - */ - private StartStreamTranscriptionResponseHandler getResponseHandler( - StreamTranscriptionBehavior transcriptionBehavior) { - final StartStreamTranscriptionResponseHandler build = StartStreamTranscriptionResponseHandler.builder() - .onResponse(r -> { - transcriptionBehavior.onResponse(r); - }) - .onError(e -> { - // Do nothing here. Don't close any streams that shouldn't be cleaned up yet. - }) - .onComplete(() -> { - // Do nothing here. Don't close any streams that shouldn't be cleaned up yet. - }) - - .subscriber(event -> transcriptionBehavior.onStream(event)) - .build(); - return build; - } - - /** - * Check if the exception can be retried. - * - */ - private boolean isExceptionRetriable(Throwable e) { - e.printStackTrace(); - - return nonRetriableExceptions.contains(e.getClass()); - } - - public void close() { - this.client.close(); - } - -} -// snippet-end:[transcribe.java-streaming-retry-client] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.amazonaws.transcribestreaming; + +import org.reactivestreams.Publisher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; +import software.amazon.awssdk.auth.signer.EventStreamAws4Signer; +import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.transcribestreaming.TranscribeStreamingAsyncClient; +import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; +import software.amazon.awssdk.services.transcribestreaming.model.BadRequestException; +import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionRequest; +import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** + * Build a client wrapper around the Amazon Transcribe client to retry + * on an exception that can be retried. + */ +// snippet-start:[transcribe.java-streaming-retry-client] +public class TranscribeStreamingRetryClient { + + private static final int DEFAULT_MAX_RETRIES = 10; + private static final int DEFAULT_MAX_SLEEP_TIME_MILLS = 100; + private static final Logger log = LoggerFactory.getLogger(TranscribeStreamingRetryClient.class); + private final TranscribeStreamingAsyncClient client; + List> nonRetriableExceptions = Arrays.asList(BadRequestException.class); + private int maxRetries = DEFAULT_MAX_RETRIES; + private int sleepTime = DEFAULT_MAX_SLEEP_TIME_MILLS; + + /** + * Create a TranscribeStreamingRetryClient with given credential and + * configuration + */ + public TranscribeStreamingRetryClient(AwsCredentialsProvider creds, + String endpoint, Region region) throws URISyntaxException { + this(TranscribeStreamingAsyncClient.builder() + .overrideConfiguration( + c -> c.putAdvancedOption( + SdkAdvancedClientOption.SIGNER, + EventStreamAws4Signer.create())) + .credentialsProvider(creds) + .endpointOverride(new URI(endpoint)) + .region(region) + .build()); + } + + /** + * Initiate TranscribeStreamingRetryClient with TranscribeStreamingAsyncClient + */ + + public TranscribeStreamingRetryClient(TranscribeStreamingAsyncClient client) { + this.client = client; + } + + /** + * Get Max retries + */ + public int getMaxRetries() { + return maxRetries; + } + + /** + * Set Max retries + */ + public void setMaxRetries(int maxRetries) { + this.maxRetries = maxRetries; + } + + /** + * Get sleep time + */ + public int getSleepTime() { + return sleepTime; + } + + /** + * Set sleep time between retries + */ + public void setSleepTime(int sleepTime) { + this.sleepTime = sleepTime; + } + + /** + * Initiate a Stream Transcription with retry. + */ + + public CompletableFuture startStreamTranscription(final StartStreamTranscriptionRequest request, + final Publisher publisher, + final StreamTranscriptionBehavior responseHandler) { + + CompletableFuture finalFuture = new CompletableFuture<>(); + + recursiveStartStream(rebuildRequestWithSession(request), publisher, responseHandler, finalFuture, 0); + + return finalFuture; + } + + /** + * Recursively call startStreamTranscription() until the request is completed or + * we run out of retries. + * + */ + private void recursiveStartStream(final StartStreamTranscriptionRequest request, + final Publisher publisher, + final StreamTranscriptionBehavior responseHandler, + final CompletableFuture finalFuture, + final int retryAttempt) { + CompletableFuture result = client.startStreamTranscription(request, publisher, + getResponseHandler(responseHandler)); + result.whenComplete((r, e) -> { + if (e != null) { + log.debug("Error occured:", e); + + if (retryAttempt <= maxRetries && isExceptionRetriable(e)) { + log.debug("Retriable error occurred and will be retried."); + log.debug("Sleeping for sometime before retrying..."); + try { + Thread.sleep(sleepTime); + } catch (InterruptedException e1) { + log.debug("Unable to sleep. Failed with exception: ", e); + e1.printStackTrace(); + } + log.debug("Making retry attempt: " + (retryAttempt + 1)); + recursiveStartStream(request, publisher, responseHandler, finalFuture, retryAttempt + 1); + } else { + log.error("Encountered unretriable exception or ran out of retries. "); + responseHandler.onError(e); + finalFuture.completeExceptionally(e); + } + } else { + responseHandler.onComplete(); + finalFuture.complete(null); + } + }); + } + + private StartStreamTranscriptionRequest rebuildRequestWithSession(StartStreamTranscriptionRequest request) { + return StartStreamTranscriptionRequest.builder() + .languageCode(request.languageCode()) + .mediaEncoding(request.mediaEncoding()) + .mediaSampleRateHertz(request.mediaSampleRateHertz()) + .sessionId(UUID.randomUUID().toString()) + .build(); + } + + /** + * StartStreamTranscriptionResponseHandler implements subscriber of transcript + * stream + * Output is printed to standard output + */ + private StartStreamTranscriptionResponseHandler getResponseHandler( + StreamTranscriptionBehavior transcriptionBehavior) { + final StartStreamTranscriptionResponseHandler build = StartStreamTranscriptionResponseHandler.builder() + .onResponse(r -> { + transcriptionBehavior.onResponse(r); + }) + .onError(e -> { + // Do nothing here. Don't close any streams that shouldn't be cleaned up yet. + }) + .onComplete(() -> { + // Do nothing here. Don't close any streams that shouldn't be cleaned up yet. + }) + + .subscriber(event -> transcriptionBehavior.onStream(event)) + .build(); + return build; + } + + /** + * Check if the exception can be retried. + * + */ + private boolean isExceptionRetriable(Throwable e) { + e.printStackTrace(); + + return nonRetriableExceptions.contains(e.getClass()); + } + + public void close() { + this.client.close(); + } + +} +// snippet-end:[transcribe.java-streaming-retry-client] diff --git a/javav2/example_code/transcribe/src/test/java/TranscribeTest.java b/javav2/example_code/transcribe-streaming/src/test/java/TranscribeTest.java similarity index 94% rename from javav2/example_code/transcribe/src/test/java/TranscribeTest.java rename to javav2/example_code/transcribe-streaming/src/test/java/TranscribeTest.java index 38c1a940fb5..2582bb64a56 100644 --- a/javav2/example_code/transcribe/src/test/java/TranscribeTest.java +++ b/javav2/example_code/transcribe-streaming/src/test/java/TranscribeTest.java @@ -1,6 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import com.amazonaws.transcribe.BidirectionalStreaming; +import com.amazonaws.transcribestreaming.BidirectionalStreaming; import software.amazon.awssdk.services.transcribestreaming.TranscribeStreamingAsyncClient; import software.amazon.awssdk.regions.Region; import org.junit.jupiter.api.*; diff --git a/javav2/example_code/transcribe/README.md b/javav2/example_code/transcribe/README.md index 399ea7a7f25..bc5ac6f4d48 100644 --- a/javav2/example_code/transcribe/README.md +++ b/javav2/example_code/transcribe/README.md @@ -34,15 +34,13 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `javav Code excerpts that show you how to call individual service functions. - [ListTranscriptionJobs](src/main/java/com/amazonaws/transcribe/ListTranscriptionJobs.java#L12) -- [StartMedicalStreamTranscription](src/main/java/com/amazonaws/transcribestreaming/TranscribeMedicalStreamingDemoApp.java#L25) -- [StartStreamTranscription](src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoApp.java#L26) ### Scenarios Code examples that show you how to accomplish a specific task by calling multiple functions within the same service. -- [Transcribe audio and get job data](src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoFile.java) +- [Transcribe audio and get job data](../transcribe-streaming/src/main/java/com/amazonaws/transcribestreaming/TranscribeStreamingDemoFile.java)