UNPKG

20.5 kBJavaScriptView Raw
1"use strict";
2// Copyright 2021 Google LLC
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// https://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// ** This file is automatically generated by gapic-generator-typescript. **
17// ** https://github.com/googleapis/gapic-generator-typescript **
18// ** All changes to this file may be overwritten. **
19Object.defineProperty(exports, "__esModule", { value: true });
20exports.SpeechClient = void 0;
21/* global window */
22const gax = require("google-gax");
23const jsonProtos = require("../../protos/protos.json");
24/**
25 * Client JSON configuration object, loaded from
26 * `src/v1p1beta1/speech_client_config.json`.
27 * This file defines retry strategy and timeouts for all API methods in this library.
28 */
29const gapicConfig = require("./speech_client_config.json");
30const google_gax_1 = require("google-gax");
31const version = require('../../../package.json').version;
32/**
33 * Service that implements Google Cloud Speech API.
34 * @class
35 * @memberof v1p1beta1
36 */
37class SpeechClient {
38 /**
39 * Construct an instance of SpeechClient.
40 *
41 * @param {object} [options] - The configuration object.
42 * The options accepted by the constructor are described in detail
43 * in [this document](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#creating-the-client-instance).
44 * The common options are:
45 * @param {object} [options.credentials] - Credentials object.
46 * @param {string} [options.credentials.client_email]
47 * @param {string} [options.credentials.private_key]
48 * @param {string} [options.email] - Account email address. Required when
49 * using a .pem or .p12 keyFilename.
50 * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or
51 * .p12 key downloaded from the Google Developers Console. If you provide
52 * a path to a JSON file, the projectId option below is not necessary.
53 * NOTE: .pem and .p12 require you to specify options.email as well.
54 * @param {number} [options.port] - The port on which to connect to
55 * the remote host.
56 * @param {string} [options.projectId] - The project ID from the Google
57 * Developer's Console, e.g. 'grape-spaceship-123'. We will also check
58 * the environment variable GCLOUD_PROJECT for your project ID. If your
59 * app is running in an environment which supports
60 * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials},
61 * your project ID will be detected automatically.
62 * @param {string} [options.apiEndpoint] - The domain name of the
63 * API remote host.
64 * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override.
65 * Follows the structure of {@link gapicConfig}.
66 * @param {boolean} [options.fallback] - Use HTTP fallback mode.
67 * In fallback mode, a special browser-compatible transport implementation is used
68 * instead of gRPC transport. In browser context (if the `window` object is defined)
69 * the fallback mode is enabled automatically; set `options.fallback` to `false`
70 * if you need to override this behavior.
71 */
72 constructor(opts) {
73 var _a, _b;
74 this._terminated = false;
75 this.descriptors = {
76 page: {},
77 stream: {},
78 longrunning: {},
79 batching: {},
80 };
81 // Ensure that options include all the required fields.
82 const staticMembers = this.constructor;
83 const servicePath = (opts === null || opts === void 0 ? void 0 : opts.servicePath) || (opts === null || opts === void 0 ? void 0 : opts.apiEndpoint) || staticMembers.servicePath;
84 this._providedCustomServicePath = !!((opts === null || opts === void 0 ? void 0 : opts.servicePath) || (opts === null || opts === void 0 ? void 0 : opts.apiEndpoint));
85 const port = (opts === null || opts === void 0 ? void 0 : opts.port) || staticMembers.port;
86 const clientConfig = (_a = opts === null || opts === void 0 ? void 0 : opts.clientConfig) !== null && _a !== void 0 ? _a : {};
87 const fallback = (_b = opts === null || opts === void 0 ? void 0 : opts.fallback) !== null && _b !== void 0 ? _b : (typeof window !== 'undefined' && typeof (window === null || window === void 0 ? void 0 : window.fetch) === 'function');
88 opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts);
89 // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case.
90 if (servicePath !== staticMembers.servicePath && !('scopes' in opts)) {
91 opts['scopes'] = staticMembers.scopes;
92 }
93 // Choose either gRPC or proto-over-HTTP implementation of google-gax.
94 this._gaxModule = opts.fallback ? gax.fallback : gax;
95 // Create a `gaxGrpc` object, with any grpc-specific options sent to the client.
96 this._gaxGrpc = new this._gaxModule.GrpcClient(opts);
97 // Save options to use in initialize() method.
98 this._opts = opts;
99 // Save the auth object to the client, for use by other methods.
100 this.auth = this._gaxGrpc.auth;
101 // Set useJWTAccessWithScope on the auth object.
102 this.auth.useJWTAccessWithScope = true;
103 // Set defaultServicePath on the auth object.
104 this.auth.defaultServicePath = staticMembers.servicePath;
105 // Set the default scopes in auth client if needed.
106 if (servicePath === staticMembers.servicePath) {
107 this.auth.defaultScopes = staticMembers.scopes;
108 }
109 // Determine the client header string.
110 const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`];
111 if (typeof process !== 'undefined' && 'versions' in process) {
112 clientHeader.push(`gl-node/${process.versions.node}`);
113 }
114 else {
115 clientHeader.push(`gl-web/${this._gaxModule.version}`);
116 }
117 if (!opts.fallback) {
118 clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`);
119 }
120 else if (opts.fallback === 'rest') {
121 clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`);
122 }
123 if (opts.libName && opts.libVersion) {
124 clientHeader.push(`${opts.libName}/${opts.libVersion}`);
125 }
126 // Load the applicable protos.
127 this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos);
128 // This API contains "path templates"; forward-slash-separated
129 // identifiers to uniquely identify resources within the API.
130 // Create useful helper objects for these.
131 this.pathTemplates = {
132 customClassPathTemplate: new this._gaxModule.PathTemplate('projects/{project}/locations/{location}/customClasses/{custom_class}'),
133 phraseSetPathTemplate: new this._gaxModule.PathTemplate('projects/{project}/locations/{location}/phraseSets/{phrase_set}'),
134 };
135 // Some of the methods on this service provide streaming responses.
136 // Provide descriptors for these.
137 this.descriptors.stream = {
138 streamingRecognize: new this._gaxModule.StreamDescriptor(gax.StreamType.BIDI_STREAMING),
139 };
140 const protoFilesRoot = this._gaxModule.protobuf.Root.fromJSON(jsonProtos);
141 // This API contains "long-running operations", which return a
142 // an Operation object that allows for tracking of the operation,
143 // rather than holding a request open.
144 this.operationsClient = this._gaxModule
145 .lro({
146 auth: this.auth,
147 grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined,
148 })
149 .operationsClient(opts);
150 const longRunningRecognizeResponse = protoFilesRoot.lookup('.google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse');
151 const longRunningRecognizeMetadata = protoFilesRoot.lookup('.google.cloud.speech.v1p1beta1.LongRunningRecognizeMetadata');
152 this.descriptors.longrunning = {
153 longRunningRecognize: new this._gaxModule.LongrunningDescriptor(this.operationsClient, longRunningRecognizeResponse.decode.bind(longRunningRecognizeResponse), longRunningRecognizeMetadata.decode.bind(longRunningRecognizeMetadata)),
154 };
155 // Put together the default options sent with requests.
156 this._defaults = this._gaxGrpc.constructSettings('google.cloud.speech.v1p1beta1.Speech', gapicConfig, opts.clientConfig || {}, { 'x-goog-api-client': clientHeader.join(' ') });
157 // Set up a dictionary of "inner API calls"; the core implementation
158 // of calling the API is handled in `google-gax`, with this code
159 // merely providing the destination and request information.
160 this.innerApiCalls = {};
161 // Add a warn function to the client constructor so it can be easily tested.
162 this.warn = gax.warn;
163 }
164 /**
165 * Initialize the client.
166 * Performs asynchronous operations (such as authentication) and prepares the client.
167 * This function will be called automatically when any class method is called for the
168 * first time, but if you need to initialize it before calling an actual method,
169 * feel free to call initialize() directly.
170 *
171 * You can await on this method if you want to make sure the client is initialized.
172 *
173 * @returns {Promise} A promise that resolves to an authenticated service stub.
174 */
175 initialize() {
176 // If the client stub promise is already initialized, return immediately.
177 if (this.speechStub) {
178 return this.speechStub;
179 }
180 // Put together the "service stub" for
181 // google.cloud.speech.v1p1beta1.Speech.
182 this.speechStub = this._gaxGrpc.createStub(this._opts.fallback
183 ? this._protos.lookupService('google.cloud.speech.v1p1beta1.Speech')
184 : // eslint-disable-next-line @typescript-eslint/no-explicit-any
185 this._protos.google.cloud.speech.v1p1beta1.Speech, this._opts, this._providedCustomServicePath);
186 // Iterate over each of the methods that the service provides
187 // and create an API call method for each.
188 const speechStubMethods = [
189 'recognize',
190 'longRunningRecognize',
191 'streamingRecognize',
192 ];
193 for (const methodName of speechStubMethods) {
194 const callPromise = this.speechStub.then(stub => (...args) => {
195 if (this._terminated) {
196 return Promise.reject('The client has already been closed.');
197 }
198 const func = stub[methodName];
199 return func.apply(stub, args);
200 }, (err) => () => {
201 throw err;
202 });
203 const descriptor = this.descriptors.stream[methodName] ||
204 this.descriptors.longrunning[methodName] ||
205 undefined;
206 const apiCall = this._gaxModule.createApiCall(callPromise, this._defaults[methodName], descriptor);
207 this.innerApiCalls[methodName] = apiCall;
208 }
209 return this.speechStub;
210 }
211 /**
212 * The DNS address for this API service.
213 * @returns {string} The DNS address for this service.
214 */
215 static get servicePath() {
216 return 'speech.googleapis.com';
217 }
218 /**
219 * The DNS address for this API service - same as servicePath(),
220 * exists for compatibility reasons.
221 * @returns {string} The DNS address for this service.
222 */
223 static get apiEndpoint() {
224 return 'speech.googleapis.com';
225 }
226 /**
227 * The port for this API service.
228 * @returns {number} The default port for this service.
229 */
230 static get port() {
231 return 443;
232 }
233 /**
234 * The scopes needed to make gRPC calls for every method defined
235 * in this service.
236 * @returns {string[]} List of default scopes.
237 */
238 static get scopes() {
239 return ['https://www.googleapis.com/auth/cloud-platform'];
240 }
241 /**
242 * Return the project ID used by this class.
243 * @returns {Promise} A promise that resolves to string containing the project ID.
244 */
245 getProjectId(callback) {
246 if (callback) {
247 this.auth.getProjectId(callback);
248 return;
249 }
250 return this.auth.getProjectId();
251 }
252 recognize(request, optionsOrCallback, callback) {
253 request = request || {};
254 let options;
255 if (typeof optionsOrCallback === 'function' && callback === undefined) {
256 callback = optionsOrCallback;
257 options = {};
258 }
259 else {
260 options = optionsOrCallback;
261 }
262 options = options || {};
263 options.otherArgs = options.otherArgs || {};
264 options.otherArgs.headers = options.otherArgs.headers || {};
265 this.initialize();
266 return this.innerApiCalls.recognize(request, options, callback);
267 }
268 /**
269 * Performs bidirectional streaming speech recognition: receive results while
270 * sending audio. This method is only available via the gRPC API (not REST).
271 *
272 * @param {object} [options]
273 * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
274 * @returns {Stream}
275 * An object stream which is both readable and writable. It accepts objects
276 * representing [StreamingRecognizeRequest]{@link google.cloud.speech.v1p1beta1.StreamingRecognizeRequest} for write() method, and
277 * will emit objects representing [StreamingRecognizeResponse]{@link google.cloud.speech.v1p1beta1.StreamingRecognizeResponse} on 'data' event asynchronously.
278 * Please see the
279 * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming)
280 * for more details and examples.
281 * @example <caption>include:samples/generated/v1p1beta1/speech.streaming_recognize.js</caption>
282 * region_tag:speech_v1p1beta1_generated_Speech_StreamingRecognize_async
283 */
284 _streamingRecognize(options) {
285 this.initialize();
286 return this.innerApiCalls.streamingRecognize(options);
287 }
288 longRunningRecognize(request, optionsOrCallback, callback) {
289 request = request || {};
290 let options;
291 if (typeof optionsOrCallback === 'function' && callback === undefined) {
292 callback = optionsOrCallback;
293 options = {};
294 }
295 else {
296 options = optionsOrCallback;
297 }
298 options = options || {};
299 options.otherArgs = options.otherArgs || {};
300 options.otherArgs.headers = options.otherArgs.headers || {};
301 this.initialize();
302 return this.innerApiCalls.longRunningRecognize(request, options, callback);
303 }
304 /**
305 * Check the status of the long running operation returned by `longRunningRecognize()`.
306 * @param {String} name
307 * The operation name that will be passed.
308 * @returns {Promise} - The promise which resolves to an object.
309 * The decoded operation object has result and metadata field to get information from.
310 * Please see the
311 * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations)
312 * for more details and examples.
313 * @example <caption>include:samples/generated/v1p1beta1/speech.long_running_recognize.js</caption>
314 * region_tag:speech_v1p1beta1_generated_Speech_LongRunningRecognize_async
315 */
316 async checkLongRunningRecognizeProgress(name) {
317 const request = new google_gax_1.operationsProtos.google.longrunning.GetOperationRequest({ name });
318 const [operation] = await this.operationsClient.getOperation(request);
319 const decodeOperation = new gax.Operation(operation, this.descriptors.longrunning.longRunningRecognize, gax.createDefaultBackoffSettings());
320 return decodeOperation;
321 }
322 // --------------------
323 // -- Path templates --
324 // --------------------
325 /**
326 * Return a fully-qualified customClass resource name string.
327 *
328 * @param {string} project
329 * @param {string} location
330 * @param {string} custom_class
331 * @returns {string} Resource name string.
332 */
333 customClassPath(project, location, customClass) {
334 return this.pathTemplates.customClassPathTemplate.render({
335 project: project,
336 location: location,
337 custom_class: customClass,
338 });
339 }
340 /**
341 * Parse the project from CustomClass resource.
342 *
343 * @param {string} customClassName
344 * A fully-qualified path representing CustomClass resource.
345 * @returns {string} A string representing the project.
346 */
347 matchProjectFromCustomClassName(customClassName) {
348 return this.pathTemplates.customClassPathTemplate.match(customClassName)
349 .project;
350 }
351 /**
352 * Parse the location from CustomClass resource.
353 *
354 * @param {string} customClassName
355 * A fully-qualified path representing CustomClass resource.
356 * @returns {string} A string representing the location.
357 */
358 matchLocationFromCustomClassName(customClassName) {
359 return this.pathTemplates.customClassPathTemplate.match(customClassName)
360 .location;
361 }
362 /**
363 * Parse the custom_class from CustomClass resource.
364 *
365 * @param {string} customClassName
366 * A fully-qualified path representing CustomClass resource.
367 * @returns {string} A string representing the custom_class.
368 */
369 matchCustomClassFromCustomClassName(customClassName) {
370 return this.pathTemplates.customClassPathTemplate.match(customClassName)
371 .custom_class;
372 }
373 /**
374 * Return a fully-qualified phraseSet resource name string.
375 *
376 * @param {string} project
377 * @param {string} location
378 * @param {string} phrase_set
379 * @returns {string} Resource name string.
380 */
381 phraseSetPath(project, location, phraseSet) {
382 return this.pathTemplates.phraseSetPathTemplate.render({
383 project: project,
384 location: location,
385 phrase_set: phraseSet,
386 });
387 }
388 /**
389 * Parse the project from PhraseSet resource.
390 *
391 * @param {string} phraseSetName
392 * A fully-qualified path representing PhraseSet resource.
393 * @returns {string} A string representing the project.
394 */
395 matchProjectFromPhraseSetName(phraseSetName) {
396 return this.pathTemplates.phraseSetPathTemplate.match(phraseSetName)
397 .project;
398 }
399 /**
400 * Parse the location from PhraseSet resource.
401 *
402 * @param {string} phraseSetName
403 * A fully-qualified path representing PhraseSet resource.
404 * @returns {string} A string representing the location.
405 */
406 matchLocationFromPhraseSetName(phraseSetName) {
407 return this.pathTemplates.phraseSetPathTemplate.match(phraseSetName)
408 .location;
409 }
410 /**
411 * Parse the phrase_set from PhraseSet resource.
412 *
413 * @param {string} phraseSetName
414 * A fully-qualified path representing PhraseSet resource.
415 * @returns {string} A string representing the phrase_set.
416 */
417 matchPhraseSetFromPhraseSetName(phraseSetName) {
418 return this.pathTemplates.phraseSetPathTemplate.match(phraseSetName)
419 .phrase_set;
420 }
421 /**
422 * Terminate the gRPC channel and close the client.
423 *
424 * The client will no longer be usable and all future behavior is undefined.
425 * @returns {Promise} A promise that resolves when the client is closed.
426 */
427 close() {
428 this.initialize();
429 if (!this._terminated) {
430 return this.speechStub.then(stub => {
431 this._terminated = true;
432 stub.close();
433 this.operationsClient.close();
434 });
435 }
436 return Promise.resolve();
437 }
438}
439exports.SpeechClient = SpeechClient;
440//# sourceMappingURL=speech_client.js.map
\No newline at end of file