Skip to content

Commit bf14f71

Browse files
averikitschlesv
authored andcommitted
samples: update shared config (#2443)
* update shared config * Update to 1.0.13 * lint * Fix linting * lint * fix imports Co-authored-by: Les Vogel <[email protected]>
1 parent f6681b9 commit bf14f71

10 files changed

+72
-95
lines changed

speech/snippets/src/main/java/com/example/speech/InfiniteStreamRecognize.java

Lines changed: 27 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,6 @@
3030
import com.google.cloud.speech.v1p1beta1.StreamingRecognizeResponse;
3131
import com.google.protobuf.ByteString;
3232
import com.google.protobuf.Duration;
33-
34-
import java.lang.Math;
3533
import java.text.DecimalFormat;
3634
import java.util.ArrayList;
3735
import java.util.concurrent.BlockingQueue;
@@ -87,11 +85,12 @@ public static String convertMillisToDate(double milliSeconds) {
8785
long millis = (long) milliSeconds;
8886
DecimalFormat format = new DecimalFormat();
8987
format.setMinimumIntegerDigits(2);
90-
return String.format("%s:%s /",
91-
format.format(TimeUnit.MILLISECONDS.toMinutes(millis)),
92-
format.format(TimeUnit.MILLISECONDS.toSeconds(millis)
93-
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)))
94-
);
88+
return String.format(
89+
"%s:%s /",
90+
format.format(TimeUnit.MILLISECONDS.toMinutes(millis)),
91+
format.format(
92+
TimeUnit.MILLISECONDS.toSeconds(millis)
93+
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));
9594
}
9695

9796
/** Performs infinite streaming speech recognition */
@@ -139,37 +138,35 @@ public void onResponse(StreamingRecognizeResponse response) {
139138
responses.add(response);
140139
StreamingRecognitionResult result = response.getResultsList().get(0);
141140
Duration resultEndTime = result.getResultEndTime();
142-
resultEndTimeInMS = (int) ((resultEndTime.getSeconds() * 1000)
143-
+ (resultEndTime.getNanos() / 1000000));
144-
double correctedTime = resultEndTimeInMS - bridgingOffset
145-
+ (STREAMING_LIMIT * restartCounter);
141+
resultEndTimeInMS =
142+
(int)
143+
((resultEndTime.getSeconds() * 1000) + (resultEndTime.getNanos() / 1000000));
144+
double correctedTime =
145+
resultEndTimeInMS - bridgingOffset + (STREAMING_LIMIT * restartCounter);
146146

147147
SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
148148
if (result.getIsFinal()) {
149149
System.out.print(GREEN);
150150
System.out.print("\033[2K\r");
151-
System.out.printf("%s: %s [confidence: %.2f]\n",
152-
convertMillisToDate(correctedTime),
153-
alternative.getTranscript(),
154-
alternative.getConfidence()
155-
);
151+
System.out.printf(
152+
"%s: %s [confidence: %.2f]\n",
153+
convertMillisToDate(correctedTime),
154+
alternative.getTranscript(),
155+
alternative.getConfidence());
156156
isFinalEndTime = resultEndTimeInMS;
157157
lastTranscriptWasFinal = true;
158158
} else {
159159
System.out.print(RED);
160160
System.out.print("\033[2K\r");
161-
System.out.printf("%s: %s", convertMillisToDate(correctedTime),
162-
alternative.getTranscript()
163-
);
161+
System.out.printf(
162+
"%s: %s", convertMillisToDate(correctedTime), alternative.getTranscript());
164163
lastTranscriptWasFinal = false;
165164
}
166165
}
167166

168-
public void onComplete() {
169-
}
167+
public void onComplete() {}
170168

171-
public void onError(Throwable t) {
172-
}
169+
public void onError(Throwable t) {}
173170
};
174171
clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
175172

@@ -244,8 +241,8 @@ public void onError(Throwable t) {
244241

245242
request =
246243
StreamingRecognizeRequest.newBuilder()
247-
.setStreamingConfig(streamingRecognitionConfig)
248-
.build();
244+
.setStreamingConfig(streamingRecognitionConfig)
245+
.build();
249246

250247
System.out.println(YELLOW);
251248
System.out.printf("%d: RESTARTING REQUEST\n", restartCounter * STREAMING_LIMIT);
@@ -269,11 +266,11 @@ public void onError(Throwable t) {
269266
if (bridgingOffset > finalRequestEndTime) {
270267
bridgingOffset = finalRequestEndTime;
271268
}
272-
int chunksFromMS = (int) Math.floor((finalRequestEndTime
273-
- bridgingOffset) / chunkTime);
269+
int chunksFromMS =
270+
(int) Math.floor((finalRequestEndTime - bridgingOffset) / chunkTime);
274271
// chunks from MS is number of chunks to resend
275-
bridgingOffset = (int) Math.floor((lastAudioInput.size()
276-
- chunksFromMS) * chunkTime);
272+
bridgingOffset =
273+
(int) Math.floor((lastAudioInput.size() - chunksFromMS) * chunkTime);
277274
// set bridging offset for next request
278275
for (int i = chunksFromMS; i < lastAudioInput.size(); i++) {
279276
request =
@@ -289,12 +286,9 @@ public void onError(Throwable t) {
289286
tempByteString = ByteString.copyFrom(sharedQueue.take());
290287

291288
request =
292-
StreamingRecognizeRequest.newBuilder()
293-
.setAudioContent(tempByteString)
294-
.build();
289+
StreamingRecognizeRequest.newBuilder().setAudioContent(tempByteString).build();
295290

296291
audioInput.add(tempByteString);
297-
298292
}
299293

300294
clientStream.send(request);
@@ -304,6 +298,5 @@ public void onError(Throwable t) {
304298
}
305299
}
306300
}
307-
308301
}
309302
// [END speech_transcribe_infinite_streaming]

speech/snippets/src/main/java/com/example/speech/InfiniteStreamRecognizeOptions.java

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,18 +24,18 @@
2424
import org.apache.commons.cli.ParseException;
2525

2626
public class InfiniteStreamRecognizeOptions {
27-
String langCode = "en-US"; //by default english US
27+
String langCode = "en-US"; // by default english US
2828

2929
/** Construct an InfiniteStreamRecognizeOptions class from command line flags. */
3030
public static InfiniteStreamRecognizeOptions fromFlags(String[] args) {
3131
Options options = new Options();
3232
options.addOption(
33-
Option.builder()
34-
.type(String.class)
35-
.longOpt("lang_code")
36-
.hasArg()
37-
.desc("Language code")
38-
.build());
33+
Option.builder()
34+
.type(String.class)
35+
.longOpt("lang_code")
36+
.hasArg()
37+
.desc("Language code")
38+
.build());
3939

4040
CommandLineParser parser = new DefaultParser();
4141
CommandLine commandLine;
@@ -52,5 +52,4 @@ public static InfiniteStreamRecognizeOptions fromFlags(String[] args) {
5252
return null;
5353
}
5454
}
55-
5655
}

speech/snippets/src/main/java/com/example/speech/QuickstartSample.java

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,7 @@
3333

3434
public class QuickstartSample {
3535

36-
/**
37-
* Demonstrates using the Speech API to transcribe an audio file.
38-
*/
36+
/** Demonstrates using the Speech API to transcribe an audio file. */
3937
public static void main(String... args) throws Exception {
4038
// Instantiates a client
4139
try (SpeechClient speechClient = SpeechClient.create()) {
@@ -49,14 +47,13 @@ public static void main(String... args) throws Exception {
4947
ByteString audioBytes = ByteString.copyFrom(data);
5048

5149
// Builds the sync recognize request
52-
RecognitionConfig config = RecognitionConfig.newBuilder()
53-
.setEncoding(AudioEncoding.LINEAR16)
54-
.setSampleRateHertz(16000)
55-
.setLanguageCode("en-US")
56-
.build();
57-
RecognitionAudio audio = RecognitionAudio.newBuilder()
58-
.setContent(audioBytes)
59-
.build();
50+
RecognitionConfig config =
51+
RecognitionConfig.newBuilder()
52+
.setEncoding(AudioEncoding.LINEAR16)
53+
.setSampleRateHertz(16000)
54+
.setLanguageCode("en-US")
55+
.build();
56+
RecognitionAudio audio = RecognitionAudio.newBuilder().setContent(audioBytes).build();
6057

6158
// Performs speech recognition on the audio file
6259
RecognizeResponse response = speechClient.recognize(config, audio);

speech/snippets/src/main/java/com/example/speech/Recognize.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,14 +38,12 @@
3838
import com.google.cloud.speech.v1.WordInfo;
3939
import com.google.common.util.concurrent.SettableFuture;
4040
import com.google.protobuf.ByteString;
41-
4241
import java.io.IOException;
4342
import java.nio.file.Files;
4443
import java.nio.file.Path;
4544
import java.nio.file.Paths;
4645
import java.util.ArrayList;
4746
import java.util.List;
48-
4947
import javax.sound.sampled.AudioFormat;
5048
import javax.sound.sampled.AudioInputStream;
5149
import javax.sound.sampled.AudioSystem;

speech/snippets/src/main/java/com/example/speech/TranscribeContextClasses.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
import com.google.cloud.speech.v1.SpeechContext;
2626
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
2727
import com.google.cloud.speech.v1.SpeechRecognitionResult;
28-
2928
import java.io.IOException;
3029

3130
class TranscribeContextClasses {

speech/snippets/src/main/java/com/example/speech/TranscribeDiarization.java

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
2727
import com.google.cloud.speech.v1.WordInfo;
2828
import com.google.protobuf.ByteString;
29-
3029
import java.io.IOException;
3130
import java.nio.file.Files;
3231
import java.nio.file.Path;
@@ -51,14 +50,16 @@ static void transcribeDiarization(String fileName) throws IOException {
5150
try (SpeechClient client = SpeechClient.create()) {
5251
// Get the contents of the local audio file
5352
RecognitionAudio recognitionAudio =
54-
RecognitionAudio.newBuilder().setContent(ByteString.copyFrom(content)).build();
55-
SpeakerDiarizationConfig speakerDiarizationConfig = SpeakerDiarizationConfig.newBuilder()
53+
RecognitionAudio.newBuilder().setContent(ByteString.copyFrom(content)).build();
54+
SpeakerDiarizationConfig speakerDiarizationConfig =
55+
SpeakerDiarizationConfig.newBuilder()
5656
.setEnableSpeakerDiarization(true)
5757
.setMinSpeakerCount(2)
5858
.setMaxSpeakerCount(2)
5959
.build();
6060
// Configure request to enable Speaker diarization
61-
RecognitionConfig config = RecognitionConfig.newBuilder()
61+
RecognitionConfig config =
62+
RecognitionConfig.newBuilder()
6263
.setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
6364
.setLanguageCode("en-US")
6465
.setSampleRateHertz(8000)
@@ -70,14 +71,14 @@ static void transcribeDiarization(String fileName) throws IOException {
7071

7172
// Speaker Tags are only included in the last result object, which has only one alternative.
7273
SpeechRecognitionAlternative alternative =
73-
recognizeResponse.getResults(
74-
recognizeResponse.getResultsCount() - 1).getAlternatives(0);
74+
recognizeResponse.getResults(recognizeResponse.getResultsCount() - 1).getAlternatives(0);
7575
// The alternative is made up of WordInfo objects that contain the speaker_tag.
7676
WordInfo wordInfo = alternative.getWords(0);
7777
int currentSpeakerTag = wordInfo.getSpeakerTag();
7878
// For each word, get all the words associated with one speaker, once the speaker changes,
7979
// add a new line with the new speaker and their spoken words.
80-
StringBuilder speakerWords = new StringBuilder(
80+
StringBuilder speakerWords =
81+
new StringBuilder(
8182
String.format("Speaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
8283
for (int i = 1; i < alternative.getWordsCount(); i++) {
8384
wordInfo = alternative.getWords(i);
@@ -86,9 +87,7 @@ static void transcribeDiarization(String fileName) throws IOException {
8687
speakerWords.append(wordInfo.getWord());
8788
} else {
8889
speakerWords.append(
89-
String.format("\nSpeaker %d: %s",
90-
wordInfo.getSpeakerTag(),
91-
wordInfo.getWord()));
90+
String.format("\nSpeaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
9291
currentSpeakerTag = wordInfo.getSpeakerTag();
9392
}
9493
}

speech/snippets/src/main/java/com/example/speech/TranscribeDiarizationGcs.java

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -27,59 +27,58 @@
2727
import com.google.cloud.speech.v1.SpeechClient;
2828
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
2929
import com.google.cloud.speech.v1.WordInfo;
30-
3130
import java.io.IOException;
3231
import java.util.concurrent.ExecutionException;
3332

3433
public class TranscribeDiarizationGcs {
3534

36-
static void transcribeDiarizationGcs() throws IOException, ExecutionException,
37-
InterruptedException {
35+
static void transcribeDiarizationGcs()
36+
throws IOException, ExecutionException, InterruptedException {
3837
// TODO(developer): Replace these variables before running the sample.
3938
String gcsUri = "gs://cloud-samples-data/speech/commercial_mono.wav";
4039
transcribeDiarizationGcs(gcsUri);
4140
}
4241

4342
// Transcribe the give gcs file using speaker diarization
44-
public static void transcribeDiarizationGcs(String gcsUri) throws IOException,
45-
ExecutionException, InterruptedException {
43+
public static void transcribeDiarizationGcs(String gcsUri)
44+
throws IOException, ExecutionException, InterruptedException {
4645
// Initialize client that will be used to send requests. This client only needs to be created
4746
// once, and can be reused for multiple requests. After completing all of your requests, call
4847
// the "close" method on the client to safely clean up any remaining background resources.
4948
try (SpeechClient speechClient = SpeechClient.create()) {
50-
SpeakerDiarizationConfig speakerDiarizationConfig = SpeakerDiarizationConfig.newBuilder()
49+
SpeakerDiarizationConfig speakerDiarizationConfig =
50+
SpeakerDiarizationConfig.newBuilder()
5151
.setEnableSpeakerDiarization(true)
5252
.setMinSpeakerCount(2)
5353
.setMaxSpeakerCount(2)
5454
.build();
5555
// Configure request to enable Speaker diarization
5656
RecognitionConfig config =
57-
RecognitionConfig.newBuilder()
58-
.setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
59-
.setLanguageCode("en-US")
60-
.setSampleRateHertz(8000)
61-
.setDiarizationConfig(speakerDiarizationConfig)
62-
.build();
57+
RecognitionConfig.newBuilder()
58+
.setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
59+
.setLanguageCode("en-US")
60+
.setSampleRateHertz(8000)
61+
.setDiarizationConfig(speakerDiarizationConfig)
62+
.build();
6363
// Set the remote path for the audio file
6464
RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();
6565

6666
// Use non-blocking call for getting file transcription
6767
OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> future =
68-
speechClient.longRunningRecognizeAsync(config, audio);
68+
speechClient.longRunningRecognizeAsync(config, audio);
6969
System.out.println("Waiting for response...");
7070

7171
// Speaker Tags are only included in the last result object, which has only one alternative.
7272
LongRunningRecognizeResponse response = future.get();
7373
SpeechRecognitionAlternative alternative =
74-
response.getResults(
75-
response.getResultsCount() - 1)
76-
.getAlternatives(0);
74+
response.getResults(response.getResultsCount() - 1).getAlternatives(0);
7775
// The alternative is made up of WordInfo objects that contain the speaker_tag.
7876
WordInfo wordInfo = alternative.getWords(0);
7977
int currentSpeakerTag = wordInfo.getSpeakerTag();
8078
// For each word, get all the words associated with one speaker, once the speaker changes,
8179
// add a new line with the new speaker and their spoken words.
82-
StringBuilder speakerWords = new StringBuilder(
80+
StringBuilder speakerWords =
81+
new StringBuilder(
8382
String.format("Speaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
8483
for (int i = 1; i < alternative.getWordsCount(); i++) {
8584
wordInfo = alternative.getWords(i);
@@ -88,9 +87,7 @@ public static void transcribeDiarizationGcs(String gcsUri) throws IOException,
8887
speakerWords.append(wordInfo.getWord());
8988
} else {
9089
speakerWords.append(
91-
String.format("\nSpeaker %d: %s",
92-
wordInfo.getSpeakerTag(),
93-
wordInfo.getWord()));
90+
String.format("\nSpeaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
9491
currentSpeakerTag = wordInfo.getSpeakerTag();
9592
}
9693
}

speech/snippets/src/test/java/com/example/speech/QuickstartSampleIT.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,7 @@
2626
import org.junit.runner.RunWith;
2727
import org.junit.runners.JUnit4;
2828

29-
/**
30-
* Tests for quickstart sample.
31-
*/
29+
/** Tests for quickstart sample. */
3230
@RunWith(JUnit4.class)
3331
@SuppressWarnings("checkstyle:abbreviationaswordinname")
3432
public class QuickstartSampleIT {

speech/snippets/src/test/java/com/example/speech/TranscribeContextClassesTests.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
import java.io.ByteArrayOutputStream;
2222
import java.io.IOException;
2323
import java.io.PrintStream;
24-
2524
import org.junit.After;
2625
import org.junit.Before;
2726
import org.junit.Test;

0 commit comments

Comments
 (0)