Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds sync / async examples for local and remote files #503

Merged
merged 4 commits into from
Feb 8, 2017
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions speech/cloud-client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,15 @@ You can then run a given `ClassName` via:
### Transcribe a local audio file (using the quickstart sample)

mvn exec:java -Dexec.mainClass=com.example.speech.QuickstartSample

### Transcribe a local audio file (using the recognize sample)
```
mvn exec:java -Dexec.mainClass=com.example.speech.Recognize \
-Dexec.args="syncrecognize ./resources/audio.raw"
```

### Transcribe a remote audio file (using the recognize sample)
```
mvn exec:java -Dexec.mainClass=com.example.speech.Recognize \
-Dexec.args="syncrecognize 'gs://cloud-samples-tests/speech/brooklyn.flac'"
```
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ public static void main(String... args) throws Exception {
System.out.printf("Transcription: %s%n", alternative.getTranscript());
}
}
speech.close();
}
}
// [END speech_quickstart]
185 changes: 185 additions & 0 deletions speech/cloud-client/src/main/java/com/example/speech/Recognize.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
/*
Copyright 2017, Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.example.speech;

import com.google.api.gax.grpc.OperationFuture;
import com.google.cloud.speech.spi.v1beta1.SpeechClient;
import com.google.cloud.speech.v1beta1.AsyncRecognizeResponse;
import com.google.cloud.speech.v1beta1.RecognitionAudio;
import com.google.cloud.speech.v1beta1.RecognitionConfig;
import com.google.cloud.speech.v1beta1.RecognitionConfig.AudioEncoding;
import com.google.cloud.speech.v1beta1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1beta1.SpeechRecognitionResult;
import com.google.cloud.speech.v1beta1.SyncRecognizeResponse;
import com.google.protobuf.ByteString;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class Recognize {
public static void main(String... args) throws Exception {
if (args.length < 1) {
System.out.println("Usage:");
System.out.printf(
"\tjava %s \"<command>\" \"<path-to-image>\"\n"
+ "Commands:\n"
+ "\tsyncrecognize | asyncrecognize\n"
+ "Path:\n\tA file path (ex: ./resources/audio.raw) or a URI "
+ "for a Cloud Storage resource (gs://...)\n",
Recognize.class.getCanonicalName());
return;
}
String command = args[0];
String path = args.length > 1 ? args[1] : "";

if (command.equals("syncrecognize")) {
if (path.startsWith("gs://")) {
syncRecognizeGcs(path);
} else {
syncRecognizeFile(path);
}
} else if (command.equals("asyncrecognize")) {
if (path.startsWith("gs://")) {
asyncRecognizeGcs(path);
} else {
asyncRecognizeFile(path);
}
}


}

public static void syncRecognizeFile(String fileName) throws Exception, IOException {
SpeechClient speech = SpeechClient.create();

Path path = Paths.get(fileName);
byte[] data = Files.readAllBytes(path);
ByteString audioBytes = ByteString.copyFrom(data);

RecognitionConfig config = RecognitionConfig.newBuilder()
.setEncoding(AudioEncoding.LINEAR16)
.setSampleRate(16000)
.build();
RecognitionAudio audio = RecognitionAudio.newBuilder()
.setContent(audioBytes)
.build();

SyncRecognizeResponse response = speech.syncRecognize(config, audio);
List<SpeechRecognitionResult> results = response.getResultsList();

for (SpeechRecognitionResult result: results) {
List<SpeechRecognitionAlternative> alternatives = result.getAlternativesList();
for (SpeechRecognitionAlternative alternative: alternatives) {
System.out.printf("Transcription: %s%n", alternative.getTranscript());
}
}
speech.close();
}

public static void syncRecognizeGcs(String gcsUri) throws Exception, IOException {
// Instantiates a client
SpeechClient speech = SpeechClient.create();

// Builds the sync recognize request
RecognitionConfig config = RecognitionConfig.newBuilder()
.setEncoding(AudioEncoding.FLAC)
.setSampleRate(16000)
.build();
RecognitionAudio audio = RecognitionAudio.newBuilder()
.setUri(gcsUri)
.build();

// Performs speech recognition on the audio file
SyncRecognizeResponse response = speech.syncRecognize(config, audio);
List<SpeechRecognitionResult> results = response.getResultsList();

for (SpeechRecognitionResult result: results) {
List<SpeechRecognitionAlternative> alternatives = result.getAlternativesList();
for (SpeechRecognitionAlternative alternative: alternatives) {
System.out.printf("Transcription: %s%n", alternative.getTranscript());
}
}


speech.close();
}

public static void asyncRecognizeFile(String fileName) throws Exception, IOException {
SpeechClient speech = SpeechClient.create();

Path path = Paths.get(fileName);
byte[] data = Files.readAllBytes(path);
ByteString audioBytes = ByteString.copyFrom(data);

RecognitionConfig config = RecognitionConfig.newBuilder()
.setEncoding(AudioEncoding.LINEAR16)
.setSampleRate(16000)
.build();
RecognitionAudio audio = RecognitionAudio.newBuilder()
.setContent(audioBytes)
.build();

OperationFuture<AsyncRecognizeResponse> response = speech.asyncRecognizeAsync(config, audio);

while (!response.isDone()) {
System.out.println("Waiting for response...");
Thread.sleep(200);
}

List<SpeechRecognitionResult> results = response.get().getResultsList();

for (SpeechRecognitionResult result: results) {
List<SpeechRecognitionAlternative> alternatives = result.getAlternativesList();
for (SpeechRecognitionAlternative alternative: alternatives) {
System.out.printf("Transcription: %s%n", alternative.getTranscript());
}
}
speech.close();
}

public static void asyncRecognizeGcs(String gcsUri) throws Exception, IOException {
SpeechClient speech = SpeechClient.create();

RecognitionConfig config = RecognitionConfig.newBuilder()
.setEncoding(AudioEncoding.FLAC)
.setSampleRate(16000)
.build();
RecognitionAudio audio = RecognitionAudio.newBuilder()
.setUri(gcsUri)
.build();

OperationFuture<AsyncRecognizeResponse> response = speech.asyncRecognizeAsync(config, audio);

while (!response.isDone()) {
System.out.println("Waiting for response...");
Thread.sleep(200);
}

List<SpeechRecognitionResult> results = response.get().getResultsList();

for (SpeechRecognitionResult result: results) {
List<SpeechRecognitionAlternative> alternatives = result.getAlternativesList();
for (SpeechRecognitionAlternative alternative: alternatives) {
System.out.printf("Transcription: %s%n", alternative.getTranscript());
}
}
speech.close();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
Copyright 2017, Google, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.example.speech;

import static com.google.common.truth.Truth.assertThat;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**
* Tests for speech recognize sample.
*/
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class RecognizeIT {
private ByteArrayOutputStream bout;
private PrintStream out;

// The path to the audio file to transcribe
private String fileName = "./resources/audio.raw";
private String gcsPath = "gs://cloud-samples-tests/speech/brooklyn.flac";

@Before
public void setUp() {
bout = new ByteArrayOutputStream();
out = new PrintStream(bout);
System.setOut(out);
}

@After
public void tearDown() {
System.setOut(null);
}

@Test
public void testRecognizeFile() throws Exception {
Recognize.syncRecognizeFile(fileName);
String got = bout.toString();
assertThat(got).contains("how old is the Brooklyn Bridge");
}

@Test
public void testRecognizeGcs() throws Exception {
Recognize.syncRecognizeGcs(gcsPath);
String got = bout.toString();
assertThat(got).contains("how old is the Brooklyn Bridge");
}

@Test
public void testAsyncRecognizeFile() throws Exception {
Recognize.asyncRecognizeFile(fileName);
String got = bout.toString();
assertThat(got).contains("how old is the Brooklyn Bridge");
}

@Test
public void testAsyncRecognizeGcs() throws Exception {
Recognize.asyncRecognizeGcs(gcsPath);
String got = bout.toString();
assertThat(got).contains("how old is the Brooklyn Bridge");
}
}