Search in sources :

Example 16 with RecognitionConfig

use of com.google.cloud.speech.v1p1beta1.RecognitionConfig in project java-docs-samples by GoogleCloudPlatform.

the class Recognize method syncRecognizeWords.

/**
 * Performs sync recognize and prints word time offsets.
 *
 * @param fileName the path to a PCM audio file to transcribe get offsets on.
 */
public static void syncRecognizeWords(String fileName) throws Exception {
    try (SpeechClient speech = SpeechClient.create()) {
        Path path = Paths.get(fileName);
        byte[] data = Files.readAllBytes(path);
        ByteString audioBytes = ByteString.copyFrom(data);
        // Configure request with local raw PCM audio
        RecognitionConfig config = RecognitionConfig.newBuilder().setEncoding(AudioEncoding.LINEAR16).setLanguageCode("en-US").setSampleRateHertz(16000).setEnableWordTimeOffsets(true).build();
        RecognitionAudio audio = RecognitionAudio.newBuilder().setContent(audioBytes).build();
        // Use blocking call to get audio transcript
        RecognizeResponse response = speech.recognize(config, audio);
        List<SpeechRecognitionResult> results = response.getResultsList();
        for (SpeechRecognitionResult result : results) {
            // There can be several alternative transcripts for a given chunk of speech. Just use the
            // first (most likely) one here.
            SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
            System.out.printf("Transcription: %s%n", alternative.getTranscript());
            for (WordInfo wordInfo : alternative.getWordsList()) {
                System.out.println(wordInfo.getWord());
                System.out.printf("\t%s.%s sec - %s.%s sec\n", wordInfo.getStartTime().getSeconds(), wordInfo.getStartTime().getNanos() / 100000000, wordInfo.getEndTime().getSeconds(), wordInfo.getEndTime().getNanos() / 100000000);
            }
        }
    }
}
Also used : Path(java.nio.file.Path) SpeechRecognitionAlternative(com.google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative) RecognitionAudio(com.google.cloud.speech.v1p1beta1.RecognitionAudio) ByteString(com.google.protobuf.ByteString) StreamingRecognitionConfig(com.google.cloud.speech.v1p1beta1.StreamingRecognitionConfig) RecognitionConfig(com.google.cloud.speech.v1p1beta1.RecognitionConfig) SpeechClient(com.google.cloud.speech.v1p1beta1.SpeechClient) RecognizeResponse(com.google.cloud.speech.v1p1beta1.RecognizeResponse) StreamingRecognizeResponse(com.google.cloud.speech.v1p1beta1.StreamingRecognizeResponse) LongRunningRecognizeResponse(com.google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse) SpeechRecognitionResult(com.google.cloud.speech.v1p1beta1.SpeechRecognitionResult) WordInfo(com.google.cloud.speech.v1p1beta1.WordInfo)

Example 17 with RecognitionConfig

use of com.google.cloud.speech.v1p1beta1.RecognitionConfig in project java-docs-samples by GoogleCloudPlatform.

the class Recognize method asyncRecognizeFile.

/**
 * Performs non-blocking speech recognition on raw PCM audio and prints
 * the transcription. Note that transcription is limited to 60 seconds audio.
 *
 * @param fileName the path to a PCM audio file to transcribe.
 */
public static void asyncRecognizeFile(String fileName) throws Exception {
    // Instantiates a client with GOOGLE_APPLICATION_CREDENTIALS
    try (SpeechClient speech = SpeechClient.create()) {
        Path path = Paths.get(fileName);
        byte[] data = Files.readAllBytes(path);
        ByteString audioBytes = ByteString.copyFrom(data);
        // Configure request with local raw PCM audio
        RecognitionConfig config = RecognitionConfig.newBuilder().setEncoding(AudioEncoding.LINEAR16).setLanguageCode("en-US").setSampleRateHertz(16000).build();
        RecognitionAudio audio = RecognitionAudio.newBuilder().setContent(audioBytes).build();
        // Use non-blocking call for getting file transcription
        OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = speech.longRunningRecognizeAsync(config, audio);
        while (!response.isDone()) {
            System.out.println("Waiting for response...");
            Thread.sleep(10000);
        }
        List<SpeechRecognitionResult> results = response.get().getResultsList();
        for (SpeechRecognitionResult result : results) {
            // There can be several alternative transcripts for a given chunk of speech. Just use the
            // first (most likely) one here.
            SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
            System.out.printf("Transcription: %s%n", alternative.getTranscript());
        }
    }
}
Also used : Path(java.nio.file.Path) LongRunningRecognizeResponse(com.google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse) SpeechRecognitionAlternative(com.google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative) RecognitionAudio(com.google.cloud.speech.v1p1beta1.RecognitionAudio) ByteString(com.google.protobuf.ByteString) StreamingRecognitionConfig(com.google.cloud.speech.v1p1beta1.StreamingRecognitionConfig) RecognitionConfig(com.google.cloud.speech.v1p1beta1.RecognitionConfig) SpeechClient(com.google.cloud.speech.v1p1beta1.SpeechClient) SpeechRecognitionResult(com.google.cloud.speech.v1p1beta1.SpeechRecognitionResult) LongRunningRecognizeMetadata(com.google.cloud.speech.v1p1beta1.LongRunningRecognizeMetadata)

Example 18 with RecognitionConfig

use of com.google.cloud.speech.v1p1beta1.RecognitionConfig in project java-docs-samples by GoogleCloudPlatform.

the class Recognize method syncRecognizeGcs.

/**
 * Performs speech recognition on remote FLAC file and prints the transcription.
 *
 * @param gcsUri the path to the remote FLAC audio file to transcribe.
 */
public static void syncRecognizeGcs(String gcsUri) throws Exception {
    // Instantiates a client with GOOGLE_APPLICATION_CREDENTIALS
    try (SpeechClient speech = SpeechClient.create()) {
        // Builds the request for remote FLAC file
        RecognitionConfig config = RecognitionConfig.newBuilder().setEncoding(AudioEncoding.FLAC).setLanguageCode("en-US").setSampleRateHertz(16000).build();
        RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();
        // Use blocking call for getting audio transcript
        RecognizeResponse response = speech.recognize(config, audio);
        List<SpeechRecognitionResult> results = response.getResultsList();
        for (SpeechRecognitionResult result : results) {
            // There can be several alternative transcripts for a given chunk of speech. Just use the
            // first (most likely) one here.
            SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
            System.out.printf("Transcription: %s%n", alternative.getTranscript());
        }
    }
}
Also used : SpeechRecognitionAlternative(com.google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative) RecognitionAudio(com.google.cloud.speech.v1p1beta1.RecognitionAudio) StreamingRecognitionConfig(com.google.cloud.speech.v1p1beta1.StreamingRecognitionConfig) RecognitionConfig(com.google.cloud.speech.v1p1beta1.RecognitionConfig) SpeechClient(com.google.cloud.speech.v1p1beta1.SpeechClient) RecognizeResponse(com.google.cloud.speech.v1p1beta1.RecognizeResponse) StreamingRecognizeResponse(com.google.cloud.speech.v1p1beta1.StreamingRecognizeResponse) LongRunningRecognizeResponse(com.google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse) SpeechRecognitionResult(com.google.cloud.speech.v1p1beta1.SpeechRecognitionResult)

Example 19 with RecognitionConfig

use of com.google.cloud.speech.v1p1beta1.RecognitionConfig in project java-docs-samples by GoogleCloudPlatform.

the class Recognize method streamingRecognizeFile.

/**
 * Performs streaming speech recognition on raw PCM audio data.
 *
 * @param fileName the path to a PCM audio file to transcribe.
 */
public static void streamingRecognizeFile(String fileName) throws Exception, IOException {
    Path path = Paths.get(fileName);
    byte[] data = Files.readAllBytes(path);
    // Instantiates a client with GOOGLE_APPLICATION_CREDENTIALS
    try (SpeechClient speech = SpeechClient.create()) {
        // Configure request with local raw PCM audio
        RecognitionConfig recConfig = RecognitionConfig.newBuilder().setEncoding(AudioEncoding.LINEAR16).setLanguageCode("en-US").setSampleRateHertz(16000).setModel("default").build();
        StreamingRecognitionConfig config = StreamingRecognitionConfig.newBuilder().setConfig(recConfig).build();
        class ResponseApiStreamingObserver<T> implements ApiStreamObserver<T> {

            private final SettableFuture<List<T>> future = SettableFuture.create();

            private final List<T> messages = new java.util.ArrayList<T>();

            @Override
            public void onNext(T message) {
                messages.add(message);
            }

            @Override
            public void onError(Throwable t) {
                future.setException(t);
            }

            @Override
            public void onCompleted() {
                future.set(messages);
            }

            // Returns the SettableFuture object to get received messages / exceptions.
            public SettableFuture<List<T>> future() {
                return future;
            }
        }
        ResponseApiStreamingObserver<StreamingRecognizeResponse> responseObserver = new ResponseApiStreamingObserver<>();
        BidiStreamingCallable<StreamingRecognizeRequest, StreamingRecognizeResponse> callable = speech.streamingRecognizeCallable();
        ApiStreamObserver<StreamingRecognizeRequest> requestObserver = callable.bidiStreamingCall(responseObserver);
        // The first request must **only** contain the audio configuration:
        requestObserver.onNext(StreamingRecognizeRequest.newBuilder().setStreamingConfig(config).build());
        // Subsequent requests must **only** contain the audio data.
        requestObserver.onNext(StreamingRecognizeRequest.newBuilder().setAudioContent(ByteString.copyFrom(data)).build());
        // Mark transmission as completed after sending the data.
        requestObserver.onCompleted();
        List<StreamingRecognizeResponse> responses = responseObserver.future().get();
        for (StreamingRecognizeResponse response : responses) {
            // For streaming recognize, the results list has one is_final result (if available) followed
            // by a number of in-progress results (if iterim_results is true) for subsequent utterances.
            // Just print the first result here.
            StreamingRecognitionResult result = response.getResultsList().get(0);
            // There can be several alternative transcripts for a given chunk of speech. Just use the
            // first (most likely) one here.
            SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
            System.out.printf("Transcript : %s\n", alternative.getTranscript());
        }
    }
}
Also used : Path(java.nio.file.Path) SettableFuture(com.google.common.util.concurrent.SettableFuture) StreamingRecognitionConfig(com.google.cloud.speech.v1p1beta1.StreamingRecognitionConfig) SpeechRecognitionAlternative(com.google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative) StreamingRecognitionResult(com.google.cloud.speech.v1p1beta1.StreamingRecognitionResult) StreamingRecognizeRequest(com.google.cloud.speech.v1p1beta1.StreamingRecognizeRequest) ApiStreamObserver(com.google.api.gax.rpc.ApiStreamObserver) StreamingRecognitionConfig(com.google.cloud.speech.v1p1beta1.StreamingRecognitionConfig) RecognitionConfig(com.google.cloud.speech.v1p1beta1.RecognitionConfig) SpeechClient(com.google.cloud.speech.v1p1beta1.SpeechClient) List(java.util.List) StreamingRecognizeResponse(com.google.cloud.speech.v1p1beta1.StreamingRecognizeResponse)

Aggregations

RecognitionConfig (com.google.cloud.speech.v1p1beta1.RecognitionConfig)10 SpeechClient (com.google.cloud.speech.v1p1beta1.SpeechClient)10 SpeechRecognitionAlternative (com.google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative)10 RecognitionAudio (com.google.cloud.speech.v1p1beta1.RecognitionAudio)9 SpeechRecognitionResult (com.google.cloud.speech.v1p1beta1.SpeechRecognitionResult)9 StreamingRecognitionConfig (com.google.cloud.speech.v1p1beta1.StreamingRecognitionConfig)9 LongRunningRecognizeResponse (com.google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse)8 Test (org.junit.Test)8 Path (java.nio.file.Path)7 RecognitionAudio (com.google.cloud.speech.v1.RecognitionAudio)5 RecognitionConfig (com.google.cloud.speech.v1.RecognitionConfig)5 RecognizeResponse (com.google.cloud.speech.v1p1beta1.RecognizeResponse)5 StreamingRecognizeResponse (com.google.cloud.speech.v1p1beta1.StreamingRecognizeResponse)5 ByteString (com.google.protobuf.ByteString)5 ApiException (com.google.api.gax.grpc.ApiException)4 AudioEncoding (com.google.cloud.speech.v1.RecognitionConfig.AudioEncoding)4 RecognitionAudio (com.google.cloud.speech.v1beta1.RecognitionAudio)4 RecognitionConfig (com.google.cloud.speech.v1beta1.RecognitionConfig)4 AudioEncoding (com.google.cloud.speech.v1beta1.RecognitionConfig.AudioEncoding)4 LongRunningRecognizeMetadata (com.google.cloud.speech.v1p1beta1.LongRunningRecognizeMetadata)4