|
| 1 | +/* |
| 2 | + * Copyright 2016 Google Inc. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.examples.cloud.speech; |
| 18 | + |
| 19 | +import com.google.auth.oauth2.GoogleCredentials; |
| 20 | +import com.google.cloud.speech.v1beta1.AsyncRecognizeRequest; |
| 21 | +import com.google.cloud.speech.v1beta1.AsyncRecognizeResponse; |
| 22 | +import com.google.cloud.speech.v1beta1.RecognitionAudio; |
| 23 | +import com.google.cloud.speech.v1beta1.RecognitionConfig; |
| 24 | +import com.google.cloud.speech.v1beta1.RecognitionConfig.AudioEncoding; |
| 25 | +import com.google.cloud.speech.v1beta1.SpeechGrpc; |
| 26 | + |
| 27 | +import com.google.longrunning.GetOperationRequest; |
| 28 | +import com.google.longrunning.Operation; |
| 29 | +import com.google.longrunning.OperationsGrpc; |
| 30 | + |
| 31 | +import io.grpc.ManagedChannel; |
| 32 | +import io.grpc.StatusRuntimeException; |
| 33 | +import io.grpc.auth.ClientAuthInterceptor; |
| 34 | +import io.grpc.netty.NegotiationType; |
| 35 | +import io.grpc.netty.NettyChannelBuilder; |
| 36 | + |
| 37 | +import org.apache.commons.cli.CommandLine; |
| 38 | +import org.apache.commons.cli.CommandLineParser; |
| 39 | +import org.apache.commons.cli.DefaultParser; |
| 40 | +import org.apache.commons.cli.OptionBuilder; |
| 41 | +import org.apache.commons.cli.Options; |
| 42 | +import org.apache.commons.cli.ParseException; |
| 43 | + |
| 44 | +import java.io.IOException; |
| 45 | +import java.net.URI; |
| 46 | +import java.util.Arrays; |
| 47 | +import java.util.List; |
| 48 | +import java.util.concurrent.Executors; |
| 49 | +import java.util.concurrent.TimeUnit; |
| 50 | +import java.util.logging.Level; |
| 51 | +import java.util.logging.Logger; |
| 52 | + |
| 53 | +/** |
| 54 | + * Client that sends audio to Speech.AsyncRecognize and returns transcript. |
| 55 | + */ |
| 56 | +public class AsyncRecognizeClient { |
| 57 | + |
| 58 | + private static final Logger logger = Logger.getLogger(AsyncRecognizeClient.class.getName()); |
| 59 | + |
| 60 | + private static final List<String> OAUTH2_SCOPES = |
| 61 | + Arrays.asList("https://www.googleapis.com/auth/cloud-platform"); |
| 62 | + |
| 63 | + private final URI input; |
| 64 | + private final int samplingRate; |
| 65 | + |
| 66 | + private final ManagedChannel channel; |
| 67 | + private final SpeechGrpc.SpeechBlockingStub speechClient; |
| 68 | + private final OperationsGrpc.OperationsBlockingStub statusClient; |
| 69 | + |
| 70 | + /** |
| 71 | + * Construct client connecting to Cloud Speech server at {@code host:port}. |
| 72 | + */ |
| 73 | + public AsyncRecognizeClient(ManagedChannel channel, URI input, int samplingRate) |
| 74 | + throws IOException { |
| 75 | + this.input = input; |
| 76 | + this.samplingRate = samplingRate; |
| 77 | + this.channel = channel; |
| 78 | + |
| 79 | + speechClient = SpeechGrpc.newBlockingStub(channel); |
| 80 | + statusClient = OperationsGrpc.newBlockingStub(channel); |
| 81 | + } |
| 82 | + |
| 83 | + public void shutdown() throws InterruptedException { |
| 84 | + channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); |
| 85 | + } |
| 86 | + |
| 87 | + public static ManagedChannel createChannel(String host, int port) throws IOException { |
| 88 | + GoogleCredentials creds = GoogleCredentials.getApplicationDefault(); |
| 89 | + creds = creds.createScoped(OAUTH2_SCOPES); |
| 90 | + ManagedChannel channel = |
| 91 | + NettyChannelBuilder.forAddress(host, port) |
| 92 | + .negotiationType(NegotiationType.TLS) |
| 93 | + .intercept(new ClientAuthInterceptor(creds, Executors.newSingleThreadExecutor())) |
| 94 | + .build(); |
| 95 | + |
| 96 | + return channel; |
| 97 | + } |
| 98 | + |
| 99 | + /** |
| 100 | + * Sends a request to the speech API and returns an Operation handle. |
| 101 | + */ |
| 102 | + public void recognize() { |
| 103 | + RecognitionAudio audio; |
| 104 | + try { |
| 105 | + audio = RecognitionAudioFactory.createRecognitionAudio(this.input); |
| 106 | + } catch (IOException e) { |
| 107 | + logger.log(Level.WARNING, "Failed to read audio uri input: " + input); |
| 108 | + return; |
| 109 | + } |
| 110 | + logger.info("Sending " + audio.getContent().size() + " bytes from audio uri input: " + input); |
| 111 | + RecognitionConfig config = |
| 112 | + RecognitionConfig.newBuilder() |
| 113 | + .setEncoding(AudioEncoding.LINEAR16) |
| 114 | + .setSampleRate(samplingRate) |
| 115 | + .build(); |
| 116 | + AsyncRecognizeRequest request = |
| 117 | + AsyncRecognizeRequest.newBuilder().setConfig(config).setAudio(audio).build(); |
| 118 | + |
| 119 | + Operation operation; |
| 120 | + Operation status; |
| 121 | + try { |
| 122 | + operation = speechClient.asyncRecognize(request); |
| 123 | + |
| 124 | + // Print the long running operation handle |
| 125 | + logger.log( |
| 126 | + Level.INFO, |
| 127 | + String.format("Operation handle: %s, URI: %s", operation.getName(), input.toString())); |
| 128 | + } catch (StatusRuntimeException e) { |
| 129 | + logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); |
| 130 | + return; |
| 131 | + } |
| 132 | + |
| 133 | + while (true) { |
| 134 | + try { |
| 135 | + logger.log(Level.INFO, "Waiting 2s for operation, {0} processing...", operation.getName()); |
| 136 | + Thread.sleep(2000); |
| 137 | + GetOperationRequest operationReq = |
| 138 | + GetOperationRequest.newBuilder().setName(operation.getName()).build(); |
| 139 | + status = |
| 140 | + statusClient.getOperation( |
| 141 | + GetOperationRequest.newBuilder().setName(operation.getName()).build()); |
| 142 | + |
| 143 | + if (status.getDone()) { |
| 144 | + break; |
| 145 | + } |
| 146 | + } catch (Exception ex) { |
| 147 | + logger.log(Level.WARNING, ex.getMessage()); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + try { |
| 152 | + AsyncRecognizeResponse asyncRes = status.getResponse().unpack(AsyncRecognizeResponse.class); |
| 153 | + |
| 154 | + logger.info("Received response: " + asyncRes); |
| 155 | + } catch (com.google.protobuf.InvalidProtocolBufferException ex) { |
| 156 | + logger.log(Level.WARNING, "Unpack error, {0}", ex.getMessage()); |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + public static void main(String[] args) throws Exception { |
| 161 | + |
| 162 | + String audioFile = ""; |
| 163 | + String host = "speech.googleapis.com"; |
| 164 | + Integer port = 443; |
| 165 | + Integer sampling = 16000; |
| 166 | + |
| 167 | + CommandLineParser parser = new DefaultParser(); |
| 168 | + |
| 169 | + Options options = new Options(); |
| 170 | + options.addOption( |
| 171 | + OptionBuilder.withLongOpt("uri") |
| 172 | + .withDescription("path to audio uri") |
| 173 | + .hasArg() |
| 174 | + .withArgName("FILE_PATH") |
| 175 | + .create()); |
| 176 | + options.addOption( |
| 177 | + OptionBuilder.withLongOpt("host") |
| 178 | + .withDescription("endpoint for api, e.g. speech.googleapis.com") |
| 179 | + .hasArg() |
| 180 | + .withArgName("ENDPOINT") |
| 181 | + .create()); |
| 182 | + options.addOption( |
| 183 | + OptionBuilder.withLongOpt("port") |
| 184 | + .withDescription("SSL port, usually 443") |
| 185 | + .hasArg() |
| 186 | + .withArgName("PORT") |
| 187 | + .create()); |
| 188 | + options.addOption( |
| 189 | + OptionBuilder.withLongOpt("sampling") |
| 190 | + .withDescription("Sampling Rate, i.e. 16000") |
| 191 | + .hasArg() |
| 192 | + .withArgName("RATE") |
| 193 | + .create()); |
| 194 | + |
| 195 | + try { |
| 196 | + CommandLine line = parser.parse(options, args); |
| 197 | + if (line.hasOption("uri")) { |
| 198 | + audioFile = line.getOptionValue("uri"); |
| 199 | + } else { |
| 200 | + System.err.println("An Audio uri must be specified (e.g. file:///foo/baz.raw)."); |
| 201 | + System.exit(1); |
| 202 | + } |
| 203 | + |
| 204 | + if (line.hasOption("host")) { |
| 205 | + host = line.getOptionValue("host"); |
| 206 | + } else { |
| 207 | + System.err.println("An API enpoint must be specified (typically speech.googleapis.com)."); |
| 208 | + System.exit(1); |
| 209 | + } |
| 210 | + |
| 211 | + if (line.hasOption("port")) { |
| 212 | + port = Integer.parseInt(line.getOptionValue("port")); |
| 213 | + } else { |
| 214 | + System.err.println("An SSL port must be specified (typically 443)."); |
| 215 | + System.exit(1); |
| 216 | + } |
| 217 | + |
| 218 | + if (line.hasOption("sampling")) { |
| 219 | + sampling = Integer.parseInt(line.getOptionValue("sampling")); |
| 220 | + } else { |
| 221 | + System.err.println("An Audio sampling rate must be specified."); |
| 222 | + System.exit(1); |
| 223 | + } |
| 224 | + } catch (ParseException exp) { |
| 225 | + System.err.println("Unexpected exception:" + exp.getMessage()); |
| 226 | + System.exit(1); |
| 227 | + } |
| 228 | + |
| 229 | + ManagedChannel channel = AsyncRecognizeClient.createChannel(host, port); |
| 230 | + |
| 231 | + AsyncRecognizeClient client = |
| 232 | + new AsyncRecognizeClient(channel, URI.create(audioFile), sampling); |
| 233 | + try { |
| 234 | + client.recognize(); |
| 235 | + } finally { |
| 236 | + client.shutdown(); |
| 237 | + } |
| 238 | + } |
| 239 | +} |
0 commit comments