From 7b78abc9ddbf10e48564d2a2956a405808480dae Mon Sep 17 00:00:00 2001 From: Luke Sneeringer Date: Mon, 6 Nov 2017 10:25:51 -0800 Subject: [PATCH] Repository Migration (#4) --- packages/google-cloud-node/.appveyor.yml | 20 + .../google-cloud-node/.circleci/config.yml | 225 +++++ .../google-cloud-node/.circleci/key.json.enc | Bin 0 -> 2368 bytes .../google-cloud-node/.cloud-repo-tools.json | 16 + packages/google-cloud-node/.eslintignore | 3 + packages/google-cloud-node/.eslintrc.yml | 13 + packages/google-cloud-node/.gitignore | 10 + packages/google-cloud-node/.jsdoc.js | 45 + packages/google-cloud-node/.mailmap | 9 + packages/google-cloud-node/.nycrc | 26 + packages/google-cloud-node/.prettierignore | 3 + packages/google-cloud-node/.prettierrc | 8 + packages/google-cloud-node/CODE_OF_CONDUCT.md | 43 + packages/google-cloud-node/CONTRIBUTORS | 23 + packages/google-cloud-node/LICENSE | 202 +++++ packages/google-cloud-node/README.md | 194 +++-- packages/google-cloud-node/package.json | 101 ++- .../google/cloud/speech/v1/cloud_speech.proto | 445 ++++++++++ .../google-cloud-node/samples/.eslintrc.yml | 3 + packages/google-cloud-node/samples/README.md | 74 +- .../google-cloud-node/samples/package.json | 38 +- .../google-cloud-node/samples/quickstart.js | 26 +- .../smoke-test/speech_smoke_test.js | 50 -- packages/google-cloud-node/src/helpers.js | 49 +- packages/google-cloud-node/src/index.js | 129 +-- .../cloud/speech/v1}/doc_cloud_speech.js | 194 +++-- .../protobuf/doc_any.js} | 56 +- .../v1/doc/google/protobuf/doc_duration.js | 97 +++ .../rpc/doc_status.js} | 58 +- packages/google-cloud-node/src/v1/index.js | 47 +- .../google-cloud-node/src/v1/speech_client.js | 779 ++++++++++-------- .../src/v1/speech_client_config.json | 2 +- .../system-test/.eslintrc.yml | 6 + .../system-test/speech_smoke_test.js | 50 ++ packages/google-cloud-node/test/.eslintrc.yml | 5 + .../google-cloud-node/test/gapic-v1.test.js | 274 +++--- .../google-cloud-node/test/helpers.test.js | 67 +- 37 files changed, 2394 insertions(+), 996 deletions(-) create mode 100644 packages/google-cloud-node/.appveyor.yml create mode 100644 packages/google-cloud-node/.circleci/config.yml create mode 100644 packages/google-cloud-node/.circleci/key.json.enc create mode 100644 packages/google-cloud-node/.cloud-repo-tools.json create mode 100644 packages/google-cloud-node/.eslintignore create mode 100644 packages/google-cloud-node/.eslintrc.yml create mode 100644 packages/google-cloud-node/.gitignore create mode 100644 packages/google-cloud-node/.jsdoc.js create mode 100644 packages/google-cloud-node/.mailmap create mode 100644 packages/google-cloud-node/.nycrc create mode 100644 packages/google-cloud-node/.prettierignore create mode 100644 packages/google-cloud-node/.prettierrc create mode 100644 packages/google-cloud-node/CODE_OF_CONDUCT.md create mode 100644 packages/google-cloud-node/CONTRIBUTORS create mode 100644 packages/google-cloud-node/LICENSE create mode 100644 packages/google-cloud-node/protos/google/cloud/speech/v1/cloud_speech.proto create mode 100644 packages/google-cloud-node/samples/.eslintrc.yml delete mode 100644 packages/google-cloud-node/smoke-test/speech_smoke_test.js rename packages/google-cloud-node/src/v1/doc/{ => google/cloud/speech/v1}/doc_cloud_speech.js (77%) rename packages/google-cloud-node/src/v1/doc/{doc_google_protobuf_any.js => google/protobuf/doc_any.js} (74%) create mode 100644 packages/google-cloud-node/src/v1/doc/google/protobuf/doc_duration.js rename packages/google-cloud-node/src/v1/doc/{doc_google_rpc_status.js => google/rpc/doc_status.js} (67%) create mode 100644 packages/google-cloud-node/system-test/.eslintrc.yml create mode 100644 packages/google-cloud-node/system-test/speech_smoke_test.js create mode 100644 packages/google-cloud-node/test/.eslintrc.yml diff --git a/packages/google-cloud-node/.appveyor.yml b/packages/google-cloud-node/.appveyor.yml new file mode 100644 index 000000000000..240821526553 --- /dev/null +++ b/packages/google-cloud-node/.appveyor.yml @@ -0,0 +1,20 @@ +environment: + matrix: + - nodejs_version: 8 + +install: + - ps: Install-Product node $env:nodejs_version + - npm install -g npm # Force using the latest npm to get dedupe during install + - set PATH=%APPDATA%\npm;%PATH% + - npm install --force --ignore-scripts + +test_script: + - node --version + - npm --version + - npm rebuild + - npm test + +build: off + +matrix: + fast_finish: true diff --git a/packages/google-cloud-node/.circleci/config.yml b/packages/google-cloud-node/.circleci/config.yml new file mode 100644 index 000000000000..e2d6fbb10016 --- /dev/null +++ b/packages/google-cloud-node/.circleci/config.yml @@ -0,0 +1,225 @@ +--- +# "Include" for unit tests definition. +unit_tests: &unit_tests + steps: + - checkout + - run: + name: Install modules and dependencies. + command: npm install + - run: + name: Run unit tests. + command: npm test + - run: + name: Submit coverage data to codecov. + command: node_modules/.bin/codecov + when: always + +version: 2.0 +workflows: + version: 2 + tests: + jobs: + - node4: + filters: + tags: + only: /.*/ + - node6: + filters: + tags: + only: /.*/ + - node7: + filters: + tags: + only: /.*/ + - node8: + filters: + tags: + only: /.*/ + - node9: + filters: + tags: + only: /.*/ + - lint: + requires: + - node4 + - node6 + - node7 + - node8 + - node9 + filters: + tags: + only: /.*/ + - docs: + requires: + - node4 + - node6 + - node7 + - node8 + - node9 + filters: + tags: + only: /.*/ + - system_tests: + requires: + - lint + - docs + filters: + branches: + only: master + tags: + only: /^v[\d.]+$/ + - sample_tests: + requires: + - lint + - docs + filters: + branches: + only: master + tags: + only: /^v[\d.]+$/ + - publish_npm: + requires: + - system_tests + - sample_tests + filters: + branches: + ignore: /.*/ + tags: + only: /^v[\d.]+$/ + +jobs: + node4: + docker: + - image: node:4 + steps: + - checkout + - run: + name: Install modules and dependencies. + command: npm install --unsafe-perm + - run: + name: Run unit tests. + command: npm test + - run: + name: Submit coverage data to codecov. + command: node_modules/.bin/codecov + when: always + node6: + docker: + - image: node:6 + <<: *unit_tests + node7: + docker: + - image: node:7 + <<: *unit_tests + node8: + docker: + - image: node:8 + <<: *unit_tests + node9: + docker: + - image: node:9 + <<: *unit_tests + + lint: + docker: + - image: node:8 + steps: + - checkout + - run: + name: Install modules and dependencies. + command: | + npm install + npm link + - run: + name: Link the module being tested to the samples. + command: | + cd samples/ + npm link @google-cloud/speech + npm install + cd .. + - run: + name: Run linting. + command: npm run lint + + docs: + docker: + - image: node:8 + steps: + - checkout + - run: + name: Install modules and dependencies. + command: npm install + - run: + name: Build documentation. + command: npm run docs + + sample_tests: + docker: + - image: node:8 + steps: + - checkout + - run: + name: Decrypt credentials. + command: | + openssl aes-256-cbc -d -in .circleci/key.json.enc \ + -out .circleci/key.json \ + -k "${SYSTEM_TESTS_ENCRYPTION_KEY}" + - run: + name: Install and link the module. + command: | + npm install + npm link + - run: + name: Link the module being tested to the samples. + command: | + cd samples/ + npm link @google-cloud/speech + npm install + cd .. + - run: + name: Run sample tests. + command: npm run samples-test + environment: + GCLOUD_PROJECT: long-door-651 + GOOGLE_APPLICATION_CREDENTIALS: /var/speech/.circleci/key.json + - run: + name: Remove unencrypted key. + command: rm .circleci/key.json + when: always + working_directory: /var/speech/ + + system_tests: + docker: + - image: node:8 + steps: + - checkout + - run: + name: Decrypt credentials. + command: | + openssl aes-256-cbc -d -in .circleci/key.json.enc \ + -out .circleci/key.json \ + -k "${SYSTEM_TESTS_ENCRYPTION_KEY}" + - run: + name: Install modules and dependencies. + command: npm install + - run: + name: Run system tests. + command: npm run system-test + environment: + GOOGLE_APPLICATION_CREDENTIALS: .circleci/key.json + - run: + name: Remove unencrypted key. + command: rm .circleci/key.json + when: always + + publish_npm: + docker: + - image: node:8 + steps: + - checkout + - run: + name: Set NPM authentication. + command: echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc + - run: + name: Publish the module to npm. + command: npm publish diff --git a/packages/google-cloud-node/.circleci/key.json.enc b/packages/google-cloud-node/.circleci/key.json.enc new file mode 100644 index 0000000000000000000000000000000000000000..8d522f44763342f65c2b7f658c999b66e8e24d61 GIT binary patch literal 2368 zcmV-G3BUGJVQh3|WM5wqdHwPsEJB~*Dr^$fSNw;yrouu3tfnWrPqTux;7Tx8JD)mR z%B=&UXEZQXoMXTrGpm;VLHUSsGju}$kHKJn&Rkd=r4uh% z-hZGnZ)?kFlrCyWx)i*h_gTQ(XkI5QQ24|5lZLyTsrX-2Jbs#9I)py+bC}_$vdYu1Jm$_Pkqf%ZcZjs>BVmh#KskoswwuNGhtKcQ+mi( z?c-5w5PQN2uMEE2C8gcCa45u*-b7$uCJk27tno#xBjB2nwzGNlJqq}H_Bb6`SuztK z$nqFrmCMD3pG1`0U40M<@ze)(9T02D66^` zVKhb$?&46zS4o@n&W%9lf0AKLiP-(8-ReQ(v6-GN;(rJ(kPVue_F6ISf(rr#&p;3;BfzJdD?4yY?cJQi6^y!2=^B)6$^J91ypPM?* z#0>6)28qm{3+Dt(9`e#i^T{5Qww32`;c_LhVYUeyL2Wm(+FoG%^$c;U-Z6HoOrK8Y8?Wtt* zx*ZBb9S012Y=s4}jDKW6E(-UttmJn`KF-IWFcq+#@Vi;&ci1-+d`jbYD&bUG=lw_#K7 zTVI59IbniXIDlIYDOaEs$AWKXW(*PL9{i8-z4lry;?YfGu2bmJqh(Pvrk3T43ZOC~x^U4p+5^u43>9=N!^QqN*w$S?yn( z6|;bnK$HCcI$NRQ9XBkyaX#&wv7gNJl-RG}8;yGTJ{%hszHb<@bx@kzi9JWXUUne0 zxYwC7L_Xopr;5FGtvS)){5X=DDHqi^ksXdncon3C{r>U(6bN}6ZzZ5(H`QoS@S4ZR zDggv#O&^ZXp+NZGl-Sq8Eo0gC+)hn4k~BiJ+=Wu}R>sS1QuRD!?;@iU9=3VIUNH)I zr`{*+2h#oU_|cI{cwQ`7h~EY2ITs!-SX5QbI9v{|rOobS2}nw(flD{^FkCf8f_ zC8D6rP#g_xwbYvoYI2Mu*yOVVLr=p3D-2^1Sw9RmlogdRJ;N48&uT+Gg9I*}J>UGR zpw(|o3YOFOC8ma9FxUi8OGJ0>JQ|`q$pN}wg$ei!ok1MoCLYJ!JRPrzCkb--yI`4T z`1M0C^f2oMT+?@OzvRGvR~QV*o1>qjRbRf&|5U^kXsCVFR}wo+96nF0cbnEzB_*#i z-Ruzpav!G_*P9+-3wr;quk2+?QvA^OK7V&@bnN;Rr}hw79TH)xH1E#B`y&V-u9SU@}z$+z+v((VLu;qGF*-C3Y%$Nj`=c< zI}r)-5Rx38PtZnq0rn+`SrD2Q16oS*LcT@TwICX+a0v*tfDLAc%stG6arAxKRZ3F! z#r9l&5N;r8BvNE%&ta@i(v(?*S?oYi!asuFj&pnm+>VQU|8%_LFH?Tb^F`h{WTmIcK`d`QohuK~PJjgwGGW^kJ13EP+4ml7}T45FIECN^(#Yg^R$b{lM-i8tT8?K{kXNO mM~aqg$5V{ELVe07g!WH(qm!sO#B(jn%lYeh1tDB(KHHuBnVUlZ literal 0 HcmV?d00001 diff --git a/packages/google-cloud-node/.cloud-repo-tools.json b/packages/google-cloud-node/.cloud-repo-tools.json new file mode 100644 index 000000000000..bea559a8112b --- /dev/null +++ b/packages/google-cloud-node/.cloud-repo-tools.json @@ -0,0 +1,16 @@ +{ + "requiresKeyFile": true, + "requiresProjectId": true, + "product": "speech", + "client_reference_url": "https://cloud.google.com/nodejs/docs/reference/speech/latest/", + "release_quality": "beta", + "samples": [ + { + "id": "recognize", + "name": "Speech Recognition", + "file": "recognize.js", + "docs_link": "https://cloud.google.com/speech/docs", + "usage": "node recognize.js --help" + } + ] +} diff --git a/packages/google-cloud-node/.eslintignore b/packages/google-cloud-node/.eslintignore new file mode 100644 index 000000000000..f6fac98b0a8e --- /dev/null +++ b/packages/google-cloud-node/.eslintignore @@ -0,0 +1,3 @@ +node_modules/* +samples/node_modules/* +src/**/doc/* diff --git a/packages/google-cloud-node/.eslintrc.yml b/packages/google-cloud-node/.eslintrc.yml new file mode 100644 index 000000000000..bed57fbc42c7 --- /dev/null +++ b/packages/google-cloud-node/.eslintrc.yml @@ -0,0 +1,13 @@ +--- +extends: + - 'eslint:recommended' + - 'plugin:node/recommended' + - prettier +plugins: + - node + - prettier +rules: + prettier/prettier: error + block-scoped-var: error + eqeqeq: error + no-warning-comments: warn diff --git a/packages/google-cloud-node/.gitignore b/packages/google-cloud-node/.gitignore new file mode 100644 index 000000000000..6b80718f261c --- /dev/null +++ b/packages/google-cloud-node/.gitignore @@ -0,0 +1,10 @@ +**/*.log +**/node_modules +.coverage +.nyc_output +docs/ +out/ +system-test/secrets.js +system-test/*key.json +*.lock +*-lock.js* diff --git a/packages/google-cloud-node/.jsdoc.js b/packages/google-cloud-node/.jsdoc.js new file mode 100644 index 000000000000..f60c3054e8c7 --- /dev/null +++ b/packages/google-cloud-node/.jsdoc.js @@ -0,0 +1,45 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * 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. + */ + +'use strict'; + +module.exports = { + opts: { + readme: './README.md', + package: './package.json', + template: './node_modules/ink-docstrap/template', + recurse: true, + verbose: true, + destination: './docs/' + }, + plugins: [ + 'plugins/markdown' + ], + source: { + excludePattern: '(^|\\/|\\\\)[._]', + include: [ + 'src' + ], + includePattern: '\\.js$' + }, + templates: { + copyright: 'Copyright 2017 Google, Inc.', + includeDate: false, + sourceFiles: false, + systemName: '@google-cloud/speech', + theme: 'lumen' + } +}; diff --git a/packages/google-cloud-node/.mailmap b/packages/google-cloud-node/.mailmap new file mode 100644 index 000000000000..59a710ba8c01 --- /dev/null +++ b/packages/google-cloud-node/.mailmap @@ -0,0 +1,9 @@ +Dan Aharon danaharon +Daryush Laqab Daryush Laqab +Gus Class Gus Class +Jason Dobry Jason Dobry +Jason Dobry Jason Dobry +Jun Mukai Jun Mukai +Luke Sneeringer Luke Sneeringer +Puneith Kaul puneith +Stephen Sawchuk Stephen Sawchuk diff --git a/packages/google-cloud-node/.nycrc b/packages/google-cloud-node/.nycrc new file mode 100644 index 000000000000..a1a8e6920ced --- /dev/null +++ b/packages/google-cloud-node/.nycrc @@ -0,0 +1,26 @@ +{ + "report-dir": "./.coverage", + "exclude": [ + "src/*{/*,/**/*}.js", + "src/*/v*/*.js", + "test/**/*.js" + ], + "watermarks": { + "branches": [ + 95, + 100 + ], + "functions": [ + 95, + 100 + ], + "lines": [ + 95, + 100 + ], + "statements": [ + 95, + 100 + ] + } +} diff --git a/packages/google-cloud-node/.prettierignore b/packages/google-cloud-node/.prettierignore new file mode 100644 index 000000000000..f6fac98b0a8e --- /dev/null +++ b/packages/google-cloud-node/.prettierignore @@ -0,0 +1,3 @@ +node_modules/* +samples/node_modules/* +src/**/doc/* diff --git a/packages/google-cloud-node/.prettierrc b/packages/google-cloud-node/.prettierrc new file mode 100644 index 000000000000..df6eac074460 --- /dev/null +++ b/packages/google-cloud-node/.prettierrc @@ -0,0 +1,8 @@ +--- +bracketSpacing: false +printWidth: 80 +semi: true +singleQuote: true +tabWidth: 2 +trailingComma: es5 +useTabs: false diff --git a/packages/google-cloud-node/CODE_OF_CONDUCT.md b/packages/google-cloud-node/CODE_OF_CONDUCT.md new file mode 100644 index 000000000000..46b2a08ea6d1 --- /dev/null +++ b/packages/google-cloud-node/CODE_OF_CONDUCT.md @@ -0,0 +1,43 @@ +# Contributor Code of Conduct + +As contributors and maintainers of this project, +and in the interest of fostering an open and welcoming community, +we pledge to respect all people who contribute through reporting issues, +posting feature requests, updating documentation, +submitting pull requests or patches, and other activities. + +We are committed to making participation in this project +a harassment-free experience for everyone, +regardless of level of experience, gender, gender identity and expression, +sexual orientation, disability, personal appearance, +body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, +such as physical or electronic +addresses, without explicit permission +* Other unethical or unprofessional conduct. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct. +By adopting this Code of Conduct, +project maintainers commit themselves to fairly and consistently +applying these principles to every aspect of managing this project. +Project maintainers who do not follow or enforce the Code of Conduct +may be permanently removed from the project team. + +This code of conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior +may be reported by opening an issue +or contacting one or more of the project maintainers. + +This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, +available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) diff --git a/packages/google-cloud-node/CONTRIBUTORS b/packages/google-cloud-node/CONTRIBUTORS new file mode 100644 index 000000000000..2b95ef32bb36 --- /dev/null +++ b/packages/google-cloud-node/CONTRIBUTORS @@ -0,0 +1,23 @@ +# The names of individuals who have contributed to this project. +# +# Names are formatted as: +# name +# +Ace Nassri +Ali Ijaz Sheikh +Dan Aharon +Daryush Laqab +Dave Gramlich +Eric Uldall +Ernest Landrito +Gus Class +Jason Dobry +Jerjou +Jun Mukai +Luke Sneeringer +Pierre Fritsch +Puneith Kaul +Song Wang +Stephen Sawchuk +Tim Swast +wanacode diff --git a/packages/google-cloud-node/LICENSE b/packages/google-cloud-node/LICENSE new file mode 100644 index 000000000000..7a4a3ea2424c --- /dev/null +++ b/packages/google-cloud-node/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. \ No newline at end of file diff --git a/packages/google-cloud-node/README.md b/packages/google-cloud-node/README.md index ad7bfc45c831..c3a885643d13 100644 --- a/packages/google-cloud-node/README.md +++ b/packages/google-cloud-node/README.md @@ -1,59 +1,151 @@ -# Node.js Client for Google Cloud Speech API ([Beta](https://github.com/GoogleCloudPlatform/google-cloud-node#versioning)) +Google Cloud Platform logo -[Google Cloud Speech API][Product Documentation]: Google Cloud Speech API. -- [Client Library Documentation][] -- [Product Documentation][] +# [Google Cloud Speech API: Node.js Client](https://github.com/googleapis/nodejs-speech) -## Quick Start -In order to use this library, you first need to go through the following steps: +[![release level](https://img.shields.io/badge/release%20level-beta-yellow.svg?style=flat)](https://cloud.google.com/terms/launch-stages) +[![CircleCI](https://img.shields.io/circleci/project/github/googleapis/nodejs-speech.svg?style=flat)](https://circleci.com/gh/googleapis/nodejs-speech) +[![AppVeyor](https://ci.appveyor.com/api/projects/status/github/googleapis/nodejs-speech?branch=master&svg=true)](https://ci.appveyor.com/project/googleapis/nodejs-speech) +[![codecov](https://img.shields.io/codecov/c/github/googleapis/nodejs-speech/master.svg?style=flat)](https://codecov.io/gh/googleapis/nodejs-speech) -1. [Select or create a Cloud Platform project.](https://console.cloud.google.com/project) -2. [Enable the Google Cloud Speech API.](https://console.cloud.google.com/apis/api/speech) -3. [Setup Authentication.](https://googlecloudplatform.github.io/google-cloud-node/#/docs/google-cloud/master/guides/authentication) +> Node.js idiomatic client for [Speech API][product-docs]. -### Installation -``` -$ npm install --save @google-cloud/speech -``` +The [Cloud Speech API](https://cloud.google.com/speech/docs) enables easy integration of Google speech recognition technologies into developer applications. Send audio and receive a text transcription from the Cloud Speech API service. + + +* [Speech API Node.js Client API Reference][client-docs] +* [github.com/googleapis/nodejs-speech](https://github.com/googleapis/nodejs-speech) +* [Speech API Documentation][product-docs] + +Read more about the client libraries for Cloud APIs, including the older +Google APIs Client Libraries, in [Client Libraries Explained][explained]. + +[explained]: https://cloud.google.com/apis/docs/client-libraries-explained + +**Table of contents:** + +* [Quickstart](#quickstart) + * [Before you begin](#before-you-begin) + * [Installing the client library](#installing-the-client-library) + * [Using the client library](#using-the-client-library) +* [Samples](#samples) +* [Versioning](#versioning) +* [Contributing](#contributing) +* [License](#license) + +## Quickstart + +### Before you begin + +1. Select or create a Cloud Platform project. + + [Go to the projects page][projects] + +1. Enable billing for your project. + + [Enable billing][billing] + +1. Enable the Google Cloud Speech API API. + + [Enable the API][enable_api] + +1. [Set up authentication with a service account][auth] so you can access the + API from your local workstation. + +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing +[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=speech.googleapis.com +[auth]: https://cloud.google.com/docs/authentication/getting-started + +### Installing the client library + + npm install --save @google-cloud/speech -### Preview -#### SpeechClient -```js - var speech = require('@google-cloud/speech'); - - var client = speech({ - // optional auth parameters. - }); - - var languageCode = 'en-US'; - var sampleRateHertz = 44100; - var encoding = speech.v1.types.RecognitionConfig.AudioEncoding.FLAC; - var config = { - languageCode : languageCode, - sampleRateHertz : sampleRateHertz, - encoding : encoding - }; - var uri = 'gs://gapic-toolkit/hello.flac'; - var audio = { - uri : uri - }; - var request = { - config: config, - audio: audio - }; - client.recognize(request).then(function(responses) { - var response = responses[0]; - // doThingsWith(response) - }) - .catch(function(err) { - console.error(err); - }); +### Using the client library + +```javascript +// Imports the Google Cloud client library +const speech = require('@google-cloud/speech'); +const fs = require('fs'); + +// Your Google Cloud Platform project ID +const projectId = 'your-project-id'; + +// Creates a client +const client = new speech.SpeechClient({ + projectId: projectId, +}); + +// The name of the audio file to transcribe +const fileName = './resources/audio.raw'; + +// Reads a local audio file and converts it to base64 +const file = fs.readFileSync(fileName); +const audioBytes = file.toString('base64'); + +// The audio file's encoding, sample rate in hertz, and BCP-47 language code +const audio = { + content: audioBytes, +}; +const config = { + encoding: 'LINEAR16', + sampleRateHertz: 16000, + languageCode: 'en-US', +}; +const request = { + audio: audio, + config: config, +}; + +// Detects speech in the audio file +client + .recognize(request) + .then(data => { + const response = data[0]; + const transcription = response.results + .map(result => result.alternatives[0].transcript) + .join('\n'); + console.log(`Transcription: ${transcription}`); + }) + .catch(err => { + console.error('ERROR:', err); + }); ``` -### Next Steps -- Read the [Client Library Documentation][] for Google Cloud Speech API to see other available methods on the client. -- Read the [Google Cloud Speech API Product documentation][Product Documentation] to learn more about the product and see How-to Guides. -- View this [repository's main README](https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/README.md) to see the full list of Cloud APIs that we cover. +## Samples + +Samples are in the [`samples/`](https://github.com/googleapis/nodejs-speech/tree/master/samples) directory. The samples' `README.md` +has instructions for running the samples. + +| Sample | Source Code | Try it | +| --------------------------- | --------------------------------- | ------ | +| Speech Recognition | [source code](https://github.com/googleapis/nodejs-speech/blob/master/samples/recognize.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-speech&page=editor&open_in_editor=samples/recognize.js,samples/README.md) | + +The [Speech API Node.js Client API Reference][client-docs] documentation +also contains samples. + +## Versioning + +This library follows [Semantic Versioning](http://semver.org/). + +This library is considered to be in **beta**. This means it is expected to be +mostly stable while we work toward a general availability release; however, +complete stability is not guaranteed. We will address issues and requests +against beta libraries with a high priority. + +More Information: [Google Cloud Platform Launch Stages][launch_stages] + +[launch_stages]: https://cloud.google.com/terms/launch-stages + +## Contributing + +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/nodejs-speech/blob/master/.github/CONTRIBUTING.md). + +## License + +Apache Version 2.0 + +See [LICENSE](https://github.com/googleapis/nodejs-speech/blob/master/LICENSE) -[Client Library Documentation]: https://googlecloudplatform.github.io/google-cloud-node/#/docs/speech -[Product Documentation]: https://cloud.google.com/speech \ No newline at end of file +[client-docs]: https://cloud.google.com/nodejs/docs/reference/speech/latest/ +[product-docs]: https://cloud.google.com/speech/docs +[shell_img]: http://gstatic.com/cloudssh/images/open-btn.png diff --git a/packages/google-cloud-node/package.json b/packages/google-cloud-node/package.json index 0edfb2f345fa..e9d366eed5e3 100644 --- a/packages/google-cloud-node/package.json +++ b/packages/google-cloud-node/package.json @@ -1,39 +1,13 @@ { - "repository": "GoogleCloudPlatform/google-cloud-node", "name": "@google-cloud/speech", + "description": "Cloud Speech Client Library for Node.js", "version": "0.10.3", + "license": "Apache-2.0", "author": "Google Inc.", - "description": "Cloud Speech Client Library for Node.js", - "contributors": [ - { - "name": "Burcu Dogan", - "email": "jbd@google.com" - }, - { - "name": "Jason Dobry", - "email": "jason.dobry@gmail.com" - }, - { - "name": "Johan Euphrosine", - "email": "proppy@google.com" - }, - { - "name": "Patrick Costello", - "email": "pcostell@google.com" - }, - { - "name": "Ryan Seys", - "email": "ryan@ryanseys.com" - }, - { - "name": "Silvano Luciani", - "email": "silvano@google.com" - }, - { - "name": "Stephen Sawchuk", - "email": "sawchuk@gmail.com" - } - ], + "engines": { + "node": ">=4.0.0" + }, + "repository": "googleapis/nodejs-speech", "main": "./src/index.js", "files": [ "protos", @@ -54,26 +28,63 @@ "speech", "Google Cloud Speech API" ], + "contributors": [ + "Ace Nassri ", + "Ali Ijaz Sheikh ", + "Dan Aharon ", + "Daryush Laqab ", + "Dave Gramlich ", + "Eric Uldall ", + "Ernest Landrito ", + "Gus Class ", + "Jason Dobry ", + "Jerjou ", + "Jun Mukai ", + "Luke Sneeringer ", + "Pierre Fritsch ", + "Puneith Kaul ", + "Song Wang ", + "Stephen Sawchuk ", + "Tim Swast ", + "wanacode " + ], + "scripts": { + "cover": "nyc --reporter=lcov mocha --require intelli-espower-loader test/*.js && nyc report", + "docs": "repo-tools exec -- jsdoc -c .jsdoc.js", + "generate-scaffolding": "repo-tools generate all && repo-tools generate lib_samples_readme -l samples/ --config ../.cloud-repo-tools.json", + "lint": "repo-tools lint --cmd eslint -- src/ samples/ system-test/ test/", + "prettier": "repo-tools exec -- prettier --write src/*.js src/*/*.js samples/*.js samples/*/*.js test/*.js test/*/*.js system-test/*.js system-test/*/*.js", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "repo-tools test run --cmd mocha -- system-test/*.js --no-timeouts", + "test-no-cover": "repo-tools test run --cmd mocha -- test/*.js --no-timeouts", + "test": "repo-tools test run --cmd npm -- run cover" + }, "dependencies": { - "google-proto-files": "^0.13.1", - "google-gax": "^0.14.2", "extend": "^3.0.0", + "google-gax": "^0.14.2", + "google-proto-files": "^0.13.1", + "lodash.merge": "^4.6.0", + "protobufjs": "^6.8.0", "pumpify": "^1.3.5", "stream-events": "^1.0.1", "through2": "^2.0.3" }, "devDependencies": { - "mocha": "^3.2.0", - "power-assert": "^1.4.2", + "@google-cloud/nodejs-repo-tools": "^2.1.1", + "async": "^2.5.0", + "codecov": "^3.0.0", + "eslint": "^4.10.0", + "eslint-config-prettier": "^2.7.0", + "eslint-plugin-node": "^5.2.1", + "eslint-plugin-prettier": "^2.3.1", + "ink-docstrap": "^1.3.0", + "intelli-espower-loader": "^1.0.1", + "jsdoc": "^3.5.5", + "mocha": "^3.5.3", + "nyc": "^11.3.0", + "power-assert": "^1.4.4", + "prettier": "^1.7.4", + "safe-buffer": "^5.1.1", "sinon": "^2.2.0" - }, - "scripts": { - "publish-module": "node ../../scripts/publish.js speech", - "smoke-test": "mocha smoke-test/*.js --timeout 5000", - "test": "mocha test/*.js" - }, - "license": "Apache-2.0", - "engines": { - "node": ">=4.0.0" } } diff --git a/packages/google-cloud-node/protos/google/cloud/speech/v1/cloud_speech.proto b/packages/google-cloud-node/protos/google/cloud/speech/v1/cloud_speech.proto new file mode 100644 index 000000000000..b1bac7df2b0f --- /dev/null +++ b/packages/google-cloud-node/protos/google/cloud/speech/v1/cloud_speech.proto @@ -0,0 +1,445 @@ +// 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. + +syntax = "proto3"; + +package google.cloud.speech.v1; + +import "google/api/annotations.proto"; +import "google/longrunning/operations.proto"; +import "google/protobuf/any.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; +import "google/rpc/status.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/cloud/speech/v1;speech"; +option java_multiple_files = true; +option java_outer_classname = "SpeechProto"; +option java_package = "com.google.cloud.speech.v1"; + + +// Service that implements Google Cloud Speech API. +service Speech { + // Performs synchronous speech recognition: receive results after all audio + // has been sent and processed. + rpc Recognize(RecognizeRequest) returns (RecognizeResponse) { + option (google.api.http) = { post: "/v1/speech:recognize" body: "*" }; + } + + // Performs asynchronous speech recognition: receive results via the + // google.longrunning.Operations interface. Returns either an + // `Operation.error` or an `Operation.response` which contains + // a `LongRunningRecognizeResponse` message. + rpc LongRunningRecognize(LongRunningRecognizeRequest) returns (google.longrunning.Operation) { + option (google.api.http) = { post: "/v1/speech:longrunningrecognize" body: "*" }; + } + + // Performs bidirectional streaming speech recognition: receive results while + // sending audio. This method is only available via the gRPC API (not REST). + rpc StreamingRecognize(stream StreamingRecognizeRequest) returns (stream StreamingRecognizeResponse); +} + +// The top-level message sent by the client for the `Recognize` method. +message RecognizeRequest { + // *Required* Provides information to the recognizer that specifies how to + // process the request. + RecognitionConfig config = 1; + + // *Required* The audio data to be recognized. + RecognitionAudio audio = 2; +} + +// The top-level message sent by the client for the `LongRunningRecognize` +// method. +message LongRunningRecognizeRequest { + // *Required* Provides information to the recognizer that specifies how to + // process the request. + RecognitionConfig config = 1; + + // *Required* The audio data to be recognized. + RecognitionAudio audio = 2; +} + +// The top-level message sent by the client for the `StreamingRecognize` method. +// Multiple `StreamingRecognizeRequest` messages are sent. The first message +// must contain a `streaming_config` message and must not contain `audio` data. +// All subsequent messages must contain `audio` data and must not contain a +// `streaming_config` message. +message StreamingRecognizeRequest { + // The streaming request, which is either a streaming config or audio content. + oneof streaming_request { + // Provides information to the recognizer that specifies how to process the + // request. The first `StreamingRecognizeRequest` message must contain a + // `streaming_config` message. + StreamingRecognitionConfig streaming_config = 1; + + // The audio data to be recognized. Sequential chunks of audio data are sent + // in sequential `StreamingRecognizeRequest` messages. The first + // `StreamingRecognizeRequest` message must not contain `audio_content` data + // and all subsequent `StreamingRecognizeRequest` messages must contain + // `audio_content` data. The audio bytes must be encoded as specified in + // `RecognitionConfig`. Note: as with all bytes fields, protobuffers use a + // pure binary representation (not base64). See + // [audio limits](https://cloud.google.com/speech/limits#content). + bytes audio_content = 2; + } +} + +// Provides information to the recognizer that specifies how to process the +// request. +message StreamingRecognitionConfig { + // *Required* Provides information to the recognizer that specifies how to + // process the request. + RecognitionConfig config = 1; + + // *Optional* If `false` or omitted, the recognizer will perform continuous + // recognition (continuing to wait for and process audio even if the user + // pauses speaking) until the client closes the input stream (gRPC API) or + // until the maximum time limit has been reached. May return multiple + // `StreamingRecognitionResult`s with the `is_final` flag set to `true`. + // + // If `true`, the recognizer will detect a single spoken utterance. When it + // detects that the user has paused or stopped speaking, it will return an + // `END_OF_SINGLE_UTTERANCE` event and cease recognition. It will return no + // more than one `StreamingRecognitionResult` with the `is_final` flag set to + // `true`. + bool single_utterance = 2; + + // *Optional* If `true`, interim results (tentative hypotheses) may be + // returned as they become available (these interim results are indicated with + // the `is_final=false` flag). + // If `false` or omitted, only `is_final=true` result(s) are returned. + bool interim_results = 3; +} + +// Provides information to the recognizer that specifies how to process the +// request. +message RecognitionConfig { + // Audio encoding of the data sent in the audio message. All encodings support + // only 1 channel (mono) audio. Only `FLAC` and `WAV` include a header that + // describes the bytes of audio that follow the header. The other encodings + // are raw audio bytes with no header. + // + // For best results, the audio source should be captured and transmitted using + // a lossless encoding (`FLAC` or `LINEAR16`). Recognition accuracy may be + // reduced if lossy codecs, which include the other codecs listed in + // this section, are used to capture or transmit the audio, particularly if + // background noise is present. + enum AudioEncoding { + // Not specified. Will return result [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + ENCODING_UNSPECIFIED = 0; + + // Uncompressed 16-bit signed little-endian samples (Linear PCM). + LINEAR16 = 1; + + // [`FLAC`](https://xiph.org/flac/documentation.html) (Free Lossless Audio + // Codec) is the recommended encoding because it is + // lossless--therefore recognition is not compromised--and + // requires only about half the bandwidth of `LINEAR16`. `FLAC` stream + // encoding supports 16-bit and 24-bit samples, however, not all fields in + // `STREAMINFO` are supported. + FLAC = 2; + + // 8-bit samples that compand 14-bit audio samples using G.711 PCMU/mu-law. + MULAW = 3; + + // Adaptive Multi-Rate Narrowband codec. `sample_rate_hertz` must be 8000. + AMR = 4; + + // Adaptive Multi-Rate Wideband codec. `sample_rate_hertz` must be 16000. + AMR_WB = 5; + + // Opus encoded audio frames in Ogg container + // ([OggOpus](https://wiki.xiph.org/OggOpus)). + // `sample_rate_hertz` must be 16000. + OGG_OPUS = 6; + + // Although the use of lossy encodings is not recommended, if a very low + // bitrate encoding is required, `OGG_OPUS` is highly preferred over + // Speex encoding. The [Speex](https://speex.org/) encoding supported by + // Cloud Speech API has a header byte in each block, as in MIME type + // `audio/x-speex-with-header-byte`. + // It is a variant of the RTP Speex encoding defined in + // [RFC 5574](https://tools.ietf.org/html/rfc5574). + // The stream is a sequence of blocks, one block per RTP packet. Each block + // starts with a byte containing the length of the block, in bytes, followed + // by one or more frames of Speex data, padded to an integral number of + // bytes (octets) as specified in RFC 5574. In other words, each RTP header + // is replaced with a single byte containing the block length. Only Speex + // wideband is supported. `sample_rate_hertz` must be 16000. + SPEEX_WITH_HEADER_BYTE = 7; + } + + // *Required* Encoding of audio data sent in all `RecognitionAudio` messages. + AudioEncoding encoding = 1; + + // *Required* Sample rate in Hertz of the audio data sent in all + // `RecognitionAudio` messages. Valid values are: 8000-48000. + // 16000 is optimal. For best results, set the sampling rate of the audio + // source to 16000 Hz. If that's not possible, use the native sample rate of + // the audio source (instead of re-sampling). + int32 sample_rate_hertz = 2; + + // *Required* The language of the supplied audio as a + // [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag. + // Example: "en-US". + // See [Language Support](https://cloud.google.com/speech/docs/languages) + // for a list of the currently supported language codes. + string language_code = 3; + + // *Optional* Maximum number of recognition hypotheses to be returned. + // Specifically, the maximum number of `SpeechRecognitionAlternative` messages + // within each `SpeechRecognitionResult`. + // The server may return fewer than `max_alternatives`. + // Valid values are `0`-`30`. A value of `0` or `1` will return a maximum of + // one. If omitted, will return a maximum of one. + int32 max_alternatives = 4; + + // *Optional* If set to `true`, the server will attempt to filter out + // profanities, replacing all but the initial character in each filtered word + // with asterisks, e.g. "f***". If set to `false` or omitted, profanities + // won't be filtered out. + bool profanity_filter = 5; + + // *Optional* A means to provide context to assist the speech recognition. + repeated SpeechContext speech_contexts = 6; + + // *Optional* If `true`, the top result includes a list of words and + // the start and end time offsets (timestamps) for those words. If + // `false`, no word-level time offset information is returned. The default is + // `false`. + bool enable_word_time_offsets = 8; +} + +// Provides "hints" to the speech recognizer to favor specific words and phrases +// in the results. +message SpeechContext { + // *Optional* A list of strings containing words and phrases "hints" so that + // the speech recognition is more likely to recognize them. This can be used + // to improve the accuracy for specific words and phrases, for example, if + // specific commands are typically spoken by the user. This can also be used + // to add additional words to the vocabulary of the recognizer. See + // [usage limits](https://cloud.google.com/speech/limits#content). + repeated string phrases = 1; +} + +// Contains audio data in the encoding specified in the `RecognitionConfig`. +// Either `content` or `uri` must be supplied. Supplying both or neither +// returns [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. See +// [audio limits](https://cloud.google.com/speech/limits#content). +message RecognitionAudio { + // The audio source, which is either inline content or a Google Cloud + // Storage uri. + oneof audio_source { + // The audio data bytes encoded as specified in + // `RecognitionConfig`. Note: as with all bytes fields, protobuffers use a + // pure binary representation, whereas JSON representations use base64. + bytes content = 1; + + // URI that points to a file that contains audio data bytes as specified in + // `RecognitionConfig`. Currently, only Google Cloud Storage URIs are + // supported, which must be specified in the following format: + // `gs://bucket_name/object_name` (other URI formats return + // [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see + // [Request URIs](https://cloud.google.com/storage/docs/reference-uris). + string uri = 2; + } +} + +// The only message returned to the client by the `Recognize` method. It +// contains the result as zero or more sequential `SpeechRecognitionResult` +// messages. +message RecognizeResponse { + // *Output-only* Sequential list of transcription results corresponding to + // sequential portions of audio. + repeated SpeechRecognitionResult results = 2; +} + +// The only message returned to the client by the `LongRunningRecognize` method. +// It contains the result as zero or more sequential `SpeechRecognitionResult` +// messages. It is included in the `result.response` field of the `Operation` +// returned by the `GetOperation` call of the `google::longrunning::Operations` +// service. +message LongRunningRecognizeResponse { + // *Output-only* Sequential list of transcription results corresponding to + // sequential portions of audio. + repeated SpeechRecognitionResult results = 2; +} + +// Describes the progress of a long-running `LongRunningRecognize` call. It is +// included in the `metadata` field of the `Operation` returned by the +// `GetOperation` call of the `google::longrunning::Operations` service. +message LongRunningRecognizeMetadata { + // Approximate percentage of audio processed thus far. Guaranteed to be 100 + // when the audio is fully processed and the results are available. + int32 progress_percent = 1; + + // Time when the request was received. + google.protobuf.Timestamp start_time = 2; + + // Time of the most recent processing update. + google.protobuf.Timestamp last_update_time = 3; +} + +// `StreamingRecognizeResponse` is the only message returned to the client by +// `StreamingRecognize`. A series of zero or more `StreamingRecognizeResponse` +// messages are streamed back to the client. If there is no recognizable +// audio, and `single_utterance` is set to false, then no messages are streamed +// back to the client. +// +// Here's an example of a series of ten `StreamingRecognizeResponse`s that might +// be returned while processing audio: +// +// 1. results { alternatives { transcript: "tube" } stability: 0.01 } +// +// 2. results { alternatives { transcript: "to be a" } stability: 0.01 } +// +// 3. results { alternatives { transcript: "to be" } stability: 0.9 } +// results { alternatives { transcript: " or not to be" } stability: 0.01 } +// +// 4. results { alternatives { transcript: "to be or not to be" +// confidence: 0.92 } +// alternatives { transcript: "to bee or not to bee" } +// is_final: true } +// +// 5. results { alternatives { transcript: " that's" } stability: 0.01 } +// +// 6. results { alternatives { transcript: " that is" } stability: 0.9 } +// results { alternatives { transcript: " the question" } stability: 0.01 } +// +// 7. results { alternatives { transcript: " that is the question" +// confidence: 0.98 } +// alternatives { transcript: " that was the question" } +// is_final: true } +// +// Notes: +// +// - Only two of the above responses #4 and #7 contain final results; they are +// indicated by `is_final: true`. Concatenating these together generates the +// full transcript: "to be or not to be that is the question". +// +// - The others contain interim `results`. #3 and #6 contain two interim +// `results`: the first portion has a high stability and is less likely to +// change; the second portion has a low stability and is very likely to +// change. A UI designer might choose to show only high stability `results`. +// +// - The specific `stability` and `confidence` values shown above are only for +// illustrative purposes. Actual values may vary. +// +// - In each response, only one of these fields will be set: +// `error`, +// `speech_event_type`, or +// one or more (repeated) `results`. +message StreamingRecognizeResponse { + // Indicates the type of speech event. + enum SpeechEventType { + // No speech event specified. + SPEECH_EVENT_UNSPECIFIED = 0; + + // This event indicates that the server has detected the end of the user's + // speech utterance and expects no additional speech. Therefore, the server + // will not process additional audio (although it may subsequently return + // additional results). The client should stop sending additional audio + // data, half-close the gRPC connection, and wait for any additional results + // until the server closes the gRPC connection. This event is only sent if + // `single_utterance` was set to `true`, and is not used otherwise. + END_OF_SINGLE_UTTERANCE = 1; + } + + // *Output-only* If set, returns a [google.rpc.Status][google.rpc.Status] message that + // specifies the error for the operation. + google.rpc.Status error = 1; + + // *Output-only* This repeated list contains zero or more results that + // correspond to consecutive portions of the audio currently being processed. + // It contains zero or more `is_final=false` results followed by zero or one + // `is_final=true` result (the newly settled portion). + repeated StreamingRecognitionResult results = 2; + + // *Output-only* Indicates the type of speech event. + SpeechEventType speech_event_type = 4; +} + +// A streaming speech recognition result corresponding to a portion of the audio +// that is currently being processed. +message StreamingRecognitionResult { + // *Output-only* May contain one or more recognition hypotheses (up to the + // maximum specified in `max_alternatives`). + repeated SpeechRecognitionAlternative alternatives = 1; + + // *Output-only* If `false`, this `StreamingRecognitionResult` represents an + // interim result that may change. If `true`, this is the final time the + // speech service will return this particular `StreamingRecognitionResult`, + // the recognizer will not return any further hypotheses for this portion of + // the transcript and corresponding audio. + bool is_final = 2; + + // *Output-only* An estimate of the likelihood that the recognizer will not + // change its guess about this interim result. Values range from 0.0 + // (completely unstable) to 1.0 (completely stable). + // This field is only provided for interim results (`is_final=false`). + // The default of 0.0 is a sentinel value indicating `stability` was not set. + float stability = 3; +} + +// A speech recognition result corresponding to a portion of the audio. +message SpeechRecognitionResult { + // *Output-only* May contain one or more recognition hypotheses (up to the + // maximum specified in `max_alternatives`). + // These alternatives are ordered in terms of accuracy, with the top (first) + // alternative being the most probable, as ranked by the recognizer. + repeated SpeechRecognitionAlternative alternatives = 1; +} + +// Alternative hypotheses (a.k.a. n-best list). +message SpeechRecognitionAlternative { + // *Output-only* Transcript text representing the words that the user spoke. + string transcript = 1; + + // *Output-only* The confidence estimate between 0.0 and 1.0. A higher number + // indicates an estimated greater likelihood that the recognized words are + // correct. This field is typically provided only for the top hypothesis, and + // only for `is_final=true` results. Clients should not rely on the + // `confidence` field as it is not guaranteed to be accurate or consistent. + // The default of 0.0 is a sentinel value indicating `confidence` was not set. + float confidence = 2; + + // *Output-only* A list of word-specific information for each recognized word. + repeated WordInfo words = 3; +} + +// Word-specific information for recognized words. Word information is only +// included in the response when certain request parameters are set, such +// as `enable_word_time_offsets`. +message WordInfo { + // *Output-only* Time offset relative to the beginning of the audio, + // and corresponding to the start of the spoken word. + // This field is only set if `enable_word_time_offsets=true` and only + // in the top hypothesis. + // This is an experimental feature and the accuracy of the time offset can + // vary. + google.protobuf.Duration start_time = 1; + + // *Output-only* Time offset relative to the beginning of the audio, + // and corresponding to the end of the spoken word. + // This field is only set if `enable_word_time_offsets=true` and only + // in the top hypothesis. + // This is an experimental feature and the accuracy of the time offset can + // vary. + google.protobuf.Duration end_time = 2; + + // *Output-only* The word corresponding to this set of information. + string word = 3; +} diff --git a/packages/google-cloud-node/samples/.eslintrc.yml b/packages/google-cloud-node/samples/.eslintrc.yml new file mode 100644 index 000000000000..282535f55f6a --- /dev/null +++ b/packages/google-cloud-node/samples/.eslintrc.yml @@ -0,0 +1,3 @@ +--- +rules: + no-console: off diff --git a/packages/google-cloud-node/samples/README.md b/packages/google-cloud-node/samples/README.md index 4390f45b43dd..5b5995cf0cae 100644 --- a/packages/google-cloud-node/samples/README.md +++ b/packages/google-cloud-node/samples/README.md @@ -1,62 +1,57 @@ Google Cloud Platform logo -# Google Cloud Speech API Node.js Samples +# Google Cloud Speech API: Node.js Samples -[![Build](https://storage.googleapis.com/cloud-docs-samples-badges/GoogleCloudPlatform/nodejs-docs-samples/nodejs-docs-samples-speech.svg)]() +[![Open in Cloud Shell][shell_img]][shell_link] The [Cloud Speech API](https://cloud.google.com/speech/docs) enables easy integration of Google speech recognition technologies into developer applications. Send audio and receive a text transcription from the Cloud Speech API service. ## Table of Contents -* [Setup](#setup) +* [Before you begin](#before-you-begin) * [Samples](#samples) * [Speech Recognition](#speech-recognition) -* [Running the tests](#running-the-tests) -## Setup +## Before you begin -1. Read [Prerequisites][prereq] and [How to run a sample][run] first. -1. Install dependencies: - - With **npm**: - - npm install - - With **yarn**: - - yarn install - -[prereq]: ../README.md#prerequisites -[run]: ../README.md#how-to-run-a-sample +Before running the samples, make sure you've followed the steps in the +[Before you begin section](../README.md#before-you-begin) of the client +library's README. ## Samples ### Speech Recognition -View the [documentation][recognize_0_docs] or the [source code][recognize_0_code]. +View the [source code][recognize_0_code]. + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-speech&page=editor&open_in_editor=samples/recognize.js,samples/README.md) __Usage:__ `node recognize.js --help` ``` +recognize.js + Commands: - sync Detects speech in a local audio file. - sync-gcs Detects speech in an audio file located in a Google Cloud Storage bucket. - sync-words Detects speech in a local audio file with word time offset. - async Creates a job to detect speech in a local audio file, and waits for the job to complete. - async-gcs Creates a job to detect speech in an audio file located in a Google Cloud Storage bucket, - and waits for the job to complete. - async-gcs-words Creates a job to detect speech with word time offset in an audio file located in a Google - Cloud Storage bucket, and waits for the job to complete. - stream Detects speech in a local audio file by streaming it to the Speech API. - listen Detects speech in a microphone input stream. This command requires that you have SoX - installed and available in your $PATH. See - https://www.npmjs.com/package/node-record-lpcm16#dependencies + recognize.js sync Detects speech in a local audio file. + recognize.js sync-gcs Detects speech in an audio file located in a Google Cloud Storage bucket. + recognize.js sync-words Detects speech in a local audio file with word time offset. + recognize.js async Creates a job to detect speech in a local audio file, and waits for the job to + complete. + recognize.js async-gcs Creates a job to detect speech in an audio file located in a Google Cloud + Storage bucket, and waits for the job to complete. + recognize.js async-gcs-words Creates a job to detect speech with word time offset in an audio file located + in a Google Cloud Storage bucket, and waits for the job to complete. + recognize.js stream Detects speech in a local audio file by streaming it to the Speech API. + recognize.js listen Detects speech in a microphone input stream. This command requires that you + have SoX installed and available in your $PATH. See + https://www.npmjs.com/package/node-record-lpcm16#dependencies Options: - --help Show help [boolean] + --version Show version number [boolean] --encoding, -e [string] [default: "LINEAR16"] --sampleRateHertz, -r [number] [default: 16000] --languageCode, -l [string] [default: "en-US"] + --help Show help [boolean] Examples: node recognize.js sync ./resources/audio.raw -e LINEAR16 -r 16000 @@ -70,16 +65,5 @@ For more information, see https://cloud.google.com/speech/docs [recognize_0_docs]: https://cloud.google.com/speech/docs [recognize_0_code]: recognize.js -## Running the tests - -1. Set the **GCLOUD_PROJECT** and **GOOGLE_APPLICATION_CREDENTIALS** environment variables. - -1. Run the tests: - - With **npm**: - - npm test - - With **yarn**: - - yarn test +[shell_img]: http://gstatic.com/cloudssh/images/open-btn.png +[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-speech&page=editor&open_in_editor=samples/README.md diff --git a/packages/google-cloud-node/samples/package.json b/packages/google-cloud-node/samples/package.json index 6449f5ac396d..06c72e2a5281 100644 --- a/packages/google-cloud-node/samples/package.json +++ b/packages/google-cloud-node/samples/package.json @@ -4,42 +4,24 @@ "private": true, "license": "Apache-2.0", "author": "Google Inc.", - "repository": { - "type": "git", - "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git" - }, + "repository": "googleapis/nodejs-speech", "engines": { - "node": ">=4.3.2" + "node": ">=4.0.0" }, "scripts": { - "lint": "samples lint", - "pretest": "npm run lint", - "test": "samples test run --cmd ava -- -T 20s --verbose system-test/*.test.js" + "test": "repo-tools test run --cmd ava -- -T 20s --verbose system-test/*.test.js" }, "dependencies": { - "@google-cloud/speech": "0.10.2", - "@google-cloud/storage": "1.2.1", + "@google-cloud/speech": "0.10.3", + "@google-cloud/storage": "1.4.0", "node-record-lpcm16": "0.3.0", - "yargs": "8.0.2" + "yargs": "10.0.3" }, "devDependencies": { - "@google-cloud/nodejs-repo-tools": "1.4.17", - "ava": "0.21.0", + "@google-cloud/nodejs-repo-tools": "2.1.1", + "ava": "0.23.0", "proxyquire": "1.8.0", - "sinon": "3.2.0" - }, - "cloud-repo-tools": { - "requiresKeyFile": true, - "requiresProjectId": true, - "product": "speech", - "samples": [ - { - "id": "recognize", - "name": "Speech Recognition", - "file": "recognize.js", - "docs_link": "https://cloud.google.com/speech/docs", - "usage": "node recognize.js --help" - } - ] + "sinon": "4.1.1", + "uuid": "3.1.0" } } diff --git a/packages/google-cloud-node/samples/quickstart.js b/packages/google-cloud-node/samples/quickstart.js index 8652facb5f00..47cd24bc0d70 100644 --- a/packages/google-cloud-node/samples/quickstart.js +++ b/packages/google-cloud-node/samples/quickstart.js @@ -17,15 +17,15 @@ // [START speech_quickstart] // Imports the Google Cloud client library -const Speech = require('@google-cloud/speech'); +const speech = require('@google-cloud/speech'); const fs = require('fs'); // Your Google Cloud Platform project ID const projectId = 'your-project-id'; -// Instantiates a client -const speechClient = Speech({ - projectId: projectId +// Creates a client +const client = new speech.SpeechClient({ + projectId: projectId, }); // The name of the audio file to transcribe @@ -37,27 +37,29 @@ const audioBytes = file.toString('base64'); // The audio file's encoding, sample rate in hertz, and BCP-47 language code const audio = { - content: audioBytes + content: audioBytes, }; const config = { encoding: 'LINEAR16', sampleRateHertz: 16000, - languageCode: 'en-US' + languageCode: 'en-US', }; const request = { audio: audio, - config: config + config: config, }; // Detects speech in the audio file -speechClient.recognize(request) - .then((data) => { +client + .recognize(request) + .then(data => { const response = data[0]; - const transcription = response.results.map(result => - result.alternatives[0].transcript).join('\n'); + const transcription = response.results + .map(result => result.alternatives[0].transcript) + .join('\n'); console.log(`Transcription: ${transcription}`); }) - .catch((err) => { + .catch(err => { console.error('ERROR:', err); }); // [END speech_quickstart] diff --git a/packages/google-cloud-node/smoke-test/speech_smoke_test.js b/packages/google-cloud-node/smoke-test/speech_smoke_test.js deleted file mode 100644 index 7477fbaaa1b8..000000000000 --- a/packages/google-cloud-node/smoke-test/speech_smoke_test.js +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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. - */ -'use strict'; - -describe('SpeechSmokeTest', function() { - - it('successfully makes a call to the service', function(done) { - var speech = require('../src'); - - var client = speech.v1({ - // optional auth parameters. - }); - - var languageCode = 'en-US'; - var sampleRateHertz = 44100; - var encoding = speech.v1.types.RecognitionConfig.AudioEncoding.FLAC; - var config = { - languageCode : languageCode, - sampleRateHertz : sampleRateHertz, - encoding : encoding - }; - var uri = 'gs://gapic-toolkit/hello.flac'; - var audio = { - uri : uri - }; - var request = { - config: config, - audio: audio - }; - client.recognize(request).then(function(responses) { - var response = responses[0]; - console.log(response); - }) - .then(done) - .catch(done); - }); -}); \ No newline at end of file diff --git a/packages/google-cloud-node/src/helpers.js b/packages/google-cloud-node/src/helpers.js index 6f81ef2dfe11..704ef64b1250 100644 --- a/packages/google-cloud-node/src/helpers.js +++ b/packages/google-cloud-node/src/helpers.js @@ -14,10 +14,6 @@ * limitations under the License. */ -/*! - * @module speech/helpers - */ - 'use strict'; var pumpify = require('pumpify'); @@ -27,9 +23,6 @@ var through = require('through2'); /*! * Return a dictionary-like object with helpers to augment the Speech * GAPIC. - * - * @return {Object} - An object with keys and functions which are placed - * onto the pure GAPIC. */ module.exports = () => { var methods = {}; @@ -38,25 +31,25 @@ module.exports = () => { * Performs bidirectional streaming speech recognition: receive results while * sending audio. This method is only available via the gRPC API (not REST). * - * @param {Object} config - * The configuration for the stream. This is appropriately wrapped and - * sent as the first argument. It should be an object conforming to the - * [StreamingRecognitionConfig]{@link StreamingRecognitionConfig} - * structure. - * @param {Object=} options - * Optional parameters. You can override the default settings for this - * call, e.g, timeout, retries, paginations, etc. See - * [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} - * for the details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts - * raw audio for the write() method, and will emit objects representing - * [StreamingRecognizeResponse]{@link StreamingRecognizeResponse} on the - * 'data' event asynchronously. + * @method v1.SpeechClient#streamingRecognize + * @param {object} config The configuration for the stream. This is + * appropriately wrapped and sent as the first argument. It should be an + * object conforming to the [StreamingRecognitionConfig]{@link StreamingRecognitionConfig} + * structure. + * @param {object} [options] Optional parameters. You can override the default + * settings for this call, e.g, timeout, retries, paginations, etc. See + * [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} + * for the details. + * @returns {stream} An object stream which is both readable and writable. It + * accepts raw audio for the `write()` method, and will emit objects + * representing [StreamingRecognizeResponse]{@link StreamingRecognizeResponse} + * on the 'data' event asynchronously. * * @example + * const speech = require('@google-cloud/speech'); + * const client = new speech.SpeechClient(); * - * var stream = speech.streamingRecognize({ + * const stream = client.streamingRecognize({ * config: { * encoding: 'LINEAR16', * languageCode: 'en-us', @@ -65,7 +58,7 @@ module.exports = () => { * }).on('data', function(response) { * // doThingsWith(response); * }); - * var request = {}; + * const request = {}; * // Write request objects. * stream.write(request); */ @@ -74,7 +67,7 @@ module.exports = () => { options = {}; } - var requestStream = this._streamingRecognize(options); + var requestStream = this._innerApiCalls.streamingRecognize(options); // Format the audio content as input request for pipeline var recognizeStream = streamEvents(pumpify.obj()); @@ -96,7 +89,7 @@ module.exports = () => { // Write the initial configuration to the stream. requestStream.write({ - streamingConfig: config + streamingConfig: config, }); // Set up appropriate piping between the stream returned by @@ -107,11 +100,11 @@ module.exports = () => { // the appropriate request structure. through.obj((obj, _, next) => { next(null, { - audioContent: obj + audioContent: obj, }); }), requestStream, - through.obj() + through.obj(), ]); }); diff --git a/packages/google-cloud-node/src/index.js b/packages/google-cloud-node/src/index.js index d55e6a74498d..fae6dbe1fdca 100644 --- a/packages/google-cloud-node/src/index.js +++ b/packages/google-cloud-node/src/index.js @@ -1,72 +1,87 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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. - */ +// Copyright 2017, Google LLC All rights reserved. +// +// 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. /*! - * @module speech - * @name Speech + * DO NOT REMOVE THE FOLLOWING NAMESPACE DEFINITIONS + */ +/** + * @namespace google + */ +/** + * @namespace google.cloud + */ +/** + * @namespace google.cloud.speech + */ +/** + * @namespace google.cloud.speech.v1 + */ +/** + * @namespace google.protobuf + */ +/** + * @namespace google.rpc */ 'use strict'; -var extend = require('extend'); -var gapic = { - v1: require('./v1') -}; -var gaxGrpc = require('google-gax').grpc(); -var helpers = require('./helpers'); +const helpers = require('./helpers'); -const VERSION = require('../package.json').version; +// Import the clients for each version supported by this package. +const gapic = Object.freeze({ + v1: require('./v1'), +}); + +// Augment the SpeechClient objects with the helpers. +for (let gapicVersion of Object.keys(gapic)) { + let clientProto = gapic[gapicVersion].SpeechClient.prototype; + Object.assign(clientProto, helpers()); +} /** - * Create an speechClient with additional helpers for common - * tasks. + * The `@google-cloud/speech` package has the following named exports: + * + * - `SpeechClient` - Reference to {@link v1.SpeechClient} + * - `v1` - This is used for selecting or pinning a particular backend service + * version. It exports: + * - `SpeechClient` - Reference to {@link v1.SpeechClient} + * + * @module {object} @google-cloud/speech + * @alias nodejs-speech * - * Service that implements Google Cloud Speech API. + * @example Install the client library with npm: + * npm install --save @google-cloud/speech * - * @constructor - * @alias module:speech - * @mixes module:speech/helpers + * @example Import the client library: + * const speech = require('@google-cloud/speech'); * - * @param {object=} options - [Configuration object](#/docs). - * @param {number=} options.port - The port on which to connect to - * the remote host. - * @param {string=} options.servicePath - The domain name of the - * API remote host. + * @example Create a client that uses Application Default Credentials (ADC): + * const client = new speech.SpeechClient(); + * + * @example Create a client with explicit credentials: + * const client = new speech.SpeechClient({ + * projectId: 'your-project-id', + * keyFilename: '/path/to/keyfile.json', + * }); */ -function speechV1(options) { - // Define the header options. - options = extend({}, options, { - libName: 'gccl', - libVersion: VERSION - }); - - // Create the speech client with the provided options. - var client = gapic.v1(options).speechClient(options); - Object.assign(client.constructor.prototype, helpers()); - return client; -} +module.exports = gapic.v1; -var v1Protos = {}; - -extend(v1Protos, gaxGrpc.load([{ - root: require('google-proto-files')('..'), - file: 'google/cloud/speech/v1/cloud_speech.proto' -}]).google.cloud.speech.v1); +/** + * @type {object} + * @property {constructor} SpeechClient Reference to {@link v1.SpeechClient}. + */ +module.exports.v1 = gapic.v1; -module.exports = speechV1; -module.exports.types = v1Protos; -module.exports.v1 = speechV1; -module.exports.v1.types = v1Protos; +// Alias `module.exports` as `module.exports.default`, for future-proofing. +module.exports.default = Object.assign({}, module.exports); diff --git a/packages/google-cloud-node/src/v1/doc/doc_cloud_speech.js b/packages/google-cloud-node/src/v1/doc/google/cloud/speech/v1/doc_cloud_speech.js similarity index 77% rename from packages/google-cloud-node/src/v1/doc/doc_cloud_speech.js rename to packages/google-cloud-node/src/v1/doc/google/cloud/speech/v1/doc_cloud_speech.js index 0438652ccb27..15b37874e692 100644 --- a/packages/google-cloud-node/src/v1/doc/doc_cloud_speech.js +++ b/packages/google-cloud-node/src/v1/doc/google/cloud/speech/v1/doc_cloud_speech.js @@ -1,23 +1,19 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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. - */ +// Copyright 2017, Google LLC All rights reserved. +// +// 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. -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ +// Note: this file is purely for documentation. Any contents are not expected +// to be loaded as the JS file. /** * The top-level message sent by the client for the `Recognize` method. @@ -26,14 +22,15 @@ * *Required* Provides information to the recognizer that specifies how to * process the request. * - * This object should have the same structure as [RecognitionConfig]{@link RecognitionConfig} + * This object should have the same structure as [RecognitionConfig]{@link google.cloud.speech.v1.RecognitionConfig} * * @property {Object} audio * *Required* The audio data to be recognized. * - * This object should have the same structure as [RecognitionAudio]{@link RecognitionAudio} + * This object should have the same structure as [RecognitionAudio]{@link google.cloud.speech.v1.RecognitionAudio} * - * @class + * @typedef RecognizeRequest + * @memberof google.cloud.speech.v1 * @see [google.cloud.speech.v1.RecognizeRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} */ var RecognizeRequest = { @@ -48,14 +45,15 @@ var RecognizeRequest = { * *Required* Provides information to the recognizer that specifies how to * process the request. * - * This object should have the same structure as [RecognitionConfig]{@link RecognitionConfig} + * This object should have the same structure as [RecognitionConfig]{@link google.cloud.speech.v1.RecognitionConfig} * * @property {Object} audio * *Required* The audio data to be recognized. * - * This object should have the same structure as [RecognitionAudio]{@link RecognitionAudio} + * This object should have the same structure as [RecognitionAudio]{@link google.cloud.speech.v1.RecognitionAudio} * - * @class + * @typedef LongRunningRecognizeRequest + * @memberof google.cloud.speech.v1 * @see [google.cloud.speech.v1.LongRunningRecognizeRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} */ var LongRunningRecognizeRequest = { @@ -74,7 +72,7 @@ var LongRunningRecognizeRequest = { * request. The first `StreamingRecognizeRequest` message must contain a * `streaming_config` message. * - * This object should have the same structure as [StreamingRecognitionConfig]{@link StreamingRecognitionConfig} + * This object should have the same structure as [StreamingRecognitionConfig]{@link google.cloud.speech.v1.StreamingRecognitionConfig} * * @property {string} audioContent * The audio data to be recognized. Sequential chunks of audio data are sent @@ -86,7 +84,8 @@ var LongRunningRecognizeRequest = { * pure binary representation (not base64). See * [audio limits](https://cloud.google.com/speech/limits#content). * - * @class + * @typedef StreamingRecognizeRequest + * @memberof google.cloud.speech.v1 * @see [google.cloud.speech.v1.StreamingRecognizeRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} */ var StreamingRecognizeRequest = { @@ -101,7 +100,7 @@ var StreamingRecognizeRequest = { * *Required* Provides information to the recognizer that specifies how to * process the request. * - * This object should have the same structure as [RecognitionConfig]{@link RecognitionConfig} + * This object should have the same structure as [RecognitionConfig]{@link google.cloud.speech.v1.RecognitionConfig} * * @property {boolean} singleUtterance * *Optional* If `false` or omitted, the recognizer will perform continuous @@ -122,7 +121,8 @@ var StreamingRecognizeRequest = { * the `is_final=false` flag). * If `false` or omitted, only `is_final=true` result(s) are returned. * - * @class + * @typedef StreamingRecognitionConfig + * @memberof google.cloud.speech.v1 * @see [google.cloud.speech.v1.StreamingRecognitionConfig definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} */ var StreamingRecognitionConfig = { @@ -136,7 +136,7 @@ var StreamingRecognitionConfig = { * @property {number} encoding * *Required* Encoding of audio data sent in all `RecognitionAudio` messages. * - * The number should be among the values of [AudioEncoding]{@link AudioEncoding} + * The number should be among the values of [AudioEncoding]{@link google.cloud.speech.v1.AudioEncoding} * * @property {number} sampleRateHertz * *Required* Sample rate in Hertz of the audio data sent in all @@ -169,9 +169,16 @@ var StreamingRecognitionConfig = { * @property {Object[]} speechContexts * *Optional* A means to provide context to assist the speech recognition. * - * This object should have the same structure as [SpeechContext]{@link SpeechContext} + * This object should have the same structure as [SpeechContext]{@link google.cloud.speech.v1.SpeechContext} + * + * @property {boolean} enableWordTimeOffsets + * *Optional* If `true`, the top result includes a list of words and + * the start and end time offsets (timestamps) for those words. If + * `false`, no word-level time offset information is returned. The default is + * `false`. * - * @class + * @typedef RecognitionConfig + * @memberof google.cloud.speech.v1 * @see [google.cloud.speech.v1.RecognitionConfig definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} */ var RecognitionConfig = { @@ -179,9 +186,9 @@ var RecognitionConfig = { /** * Audio encoding of the data sent in the audio message. All encodings support - * only 1 channel (mono) audio. Only `FLAC` includes a header that describes - * the bytes of audio that follow the header. The other encodings are raw - * audio bytes with no header. + * only 1 channel (mono) audio. Only `FLAC` and `WAV` include a header that + * describes the bytes of audio that follow the header. The other encodings + * are raw audio bytes with no header. * * For best results, the audio source should be captured and transmitted using * a lossless encoding (`FLAC` or `LINEAR16`). Recognition accuracy may be @@ -190,11 +197,12 @@ var RecognitionConfig = { * background noise is present. * * @enum {number} + * @memberof google.cloud.speech.v1 */ AudioEncoding: { /** - * Not specified. Will return result {@link google.rpc.Code.INVALID_ARGUMENT}. + * Not specified. Will return result google.rpc.Code.INVALID_ARGUMENT. */ ENCODING_UNSPECIFIED: 0, @@ -266,7 +274,8 @@ var RecognitionConfig = { * to add additional words to the vocabulary of the recognizer. See * [usage limits](https://cloud.google.com/speech/limits#content). * - * @class + * @typedef SpeechContext + * @memberof google.cloud.speech.v1 * @see [google.cloud.speech.v1.SpeechContext definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} */ var SpeechContext = { @@ -276,7 +285,7 @@ var SpeechContext = { /** * Contains audio data in the encoding specified in the `RecognitionConfig`. * Either `content` or `uri` must be supplied. Supplying both or neither - * returns {@link google.rpc.Code.INVALID_ARGUMENT}. See + * returns google.rpc.Code.INVALID_ARGUMENT. See * [audio limits](https://cloud.google.com/speech/limits#content). * * @property {string} content @@ -289,10 +298,11 @@ var SpeechContext = { * `RecognitionConfig`. Currently, only Google Cloud Storage URIs are * supported, which must be specified in the following format: * `gs://bucket_name/object_name` (other URI formats return - * {@link google.rpc.Code.INVALID_ARGUMENT}). For more information, see + * google.rpc.Code.INVALID_ARGUMENT). For more information, see * [Request URIs](https://cloud.google.com/storage/docs/reference-uris). * - * @class + * @typedef RecognitionAudio + * @memberof google.cloud.speech.v1 * @see [google.cloud.speech.v1.RecognitionAudio definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} */ var RecognitionAudio = { @@ -308,9 +318,10 @@ var RecognitionAudio = { * *Output-only* Sequential list of transcription results corresponding to * sequential portions of audio. * - * This object should have the same structure as [SpeechRecognitionResult]{@link SpeechRecognitionResult} + * This object should have the same structure as [SpeechRecognitionResult]{@link google.cloud.speech.v1.SpeechRecognitionResult} * - * @class + * @typedef RecognizeResponse + * @memberof google.cloud.speech.v1 * @see [google.cloud.speech.v1.RecognizeResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} */ var RecognizeResponse = { @@ -328,9 +339,10 @@ var RecognizeResponse = { * *Output-only* Sequential list of transcription results corresponding to * sequential portions of audio. * - * This object should have the same structure as [SpeechRecognitionResult]{@link SpeechRecognitionResult} + * This object should have the same structure as [SpeechRecognitionResult]{@link google.cloud.speech.v1.SpeechRecognitionResult} * - * @class + * @typedef LongRunningRecognizeResponse + * @memberof google.cloud.speech.v1 * @see [google.cloud.speech.v1.LongRunningRecognizeResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} */ var LongRunningRecognizeResponse = { @@ -349,14 +361,15 @@ var LongRunningRecognizeResponse = { * @property {Object} startTime * Time when the request was received. * - * This object should have the same structure as [google.protobuf.Timestamp]{@link external:"google.protobuf.Timestamp"} + * This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp} * * @property {Object} lastUpdateTime * Time of the most recent processing update. * - * This object should have the same structure as [google.protobuf.Timestamp]{@link external:"google.protobuf.Timestamp"} + * This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp} * - * @class + * @typedef LongRunningRecognizeMetadata + * @memberof google.cloud.speech.v1 * @see [google.cloud.speech.v1.LongRunningRecognizeMetadata definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} */ var LongRunningRecognizeMetadata = { @@ -365,8 +378,10 @@ var LongRunningRecognizeMetadata = { /** * `StreamingRecognizeResponse` is the only message returned to the client by - * `StreamingRecognize`. A series of one or more `StreamingRecognizeResponse` - * messages are streamed back to the client. + * `StreamingRecognize`. A series of zero or more `StreamingRecognizeResponse` + * messages are streamed back to the client. If there is no recognizable + * audio, and `single_utterance` is set to false, then no messages are streamed + * back to the client. * * Here's an example of a series of ten `StreamingRecognizeResponse`s that might * be returned while processing audio: @@ -388,16 +403,14 @@ var LongRunningRecognizeMetadata = { * 6. results { alternatives { transcript: " that is" } stability: 0.9 } * results { alternatives { transcript: " the question" } stability: 0.01 } * - * 7. speech_event_type: END_OF_SINGLE_UTTERANCE - * - * 8. results { alternatives { transcript: " that is the question" + * 7. results { alternatives { transcript: " that is the question" * confidence: 0.98 } * alternatives { transcript: " that was the question" } * is_final: true } * * Notes: * - * - Only two of the above responses #4 and #8 contain final results; they are + * - Only two of the above responses #4 and #7 contain final results; they are * indicated by `is_final: true`. Concatenating these together generates the * full transcript: "to be or not to be that is the question". * @@ -415,25 +428,26 @@ var LongRunningRecognizeMetadata = { * one or more (repeated) `results`. * * @property {Object} error - * *Output-only* If set, returns a {@link google.rpc.Status} message that + * *Output-only* If set, returns a google.rpc.Status message that * specifies the error for the operation. * - * This object should have the same structure as [google.rpc.Status]{@link external:"google.rpc.Status"} + * This object should have the same structure as [Status]{@link google.rpc.Status} * * @property {Object[]} results * *Output-only* This repeated list contains zero or more results that * correspond to consecutive portions of the audio currently being processed. - * It contains zero or one `is_final=true` result (the newly settled portion), - * followed by zero or more `is_final=false` results. + * It contains zero or more `is_final=false` results followed by zero or one + * `is_final=true` result (the newly settled portion). * - * This object should have the same structure as [StreamingRecognitionResult]{@link StreamingRecognitionResult} + * This object should have the same structure as [StreamingRecognitionResult]{@link google.cloud.speech.v1.StreamingRecognitionResult} * * @property {number} speechEventType * *Output-only* Indicates the type of speech event. * - * The number should be among the values of [SpeechEventType]{@link SpeechEventType} + * The number should be among the values of [SpeechEventType]{@link google.cloud.speech.v1.SpeechEventType} * - * @class + * @typedef StreamingRecognizeResponse + * @memberof google.cloud.speech.v1 * @see [google.cloud.speech.v1.StreamingRecognizeResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} */ var StreamingRecognizeResponse = { @@ -443,6 +457,7 @@ var StreamingRecognizeResponse = { * Indicates the type of speech event. * * @enum {number} + * @memberof google.cloud.speech.v1 */ SpeechEventType: { @@ -472,7 +487,7 @@ var StreamingRecognizeResponse = { * *Output-only* May contain one or more recognition hypotheses (up to the * maximum specified in `max_alternatives`). * - * This object should have the same structure as [SpeechRecognitionAlternative]{@link SpeechRecognitionAlternative} + * This object should have the same structure as [SpeechRecognitionAlternative]{@link google.cloud.speech.v1.SpeechRecognitionAlternative} * * @property {boolean} isFinal * *Output-only* If `false`, this `StreamingRecognitionResult` represents an @@ -488,7 +503,8 @@ var StreamingRecognizeResponse = { * This field is only provided for interim results (`is_final=false`). * The default of 0.0 is a sentinel value indicating `stability` was not set. * - * @class + * @typedef StreamingRecognitionResult + * @memberof google.cloud.speech.v1 * @see [google.cloud.speech.v1.StreamingRecognitionResult definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} */ var StreamingRecognitionResult = { @@ -501,10 +517,13 @@ var StreamingRecognitionResult = { * @property {Object[]} alternatives * *Output-only* May contain one or more recognition hypotheses (up to the * maximum specified in `max_alternatives`). + * These alternatives are ordered in terms of accuracy, with the top (first) + * alternative being the most probable, as ranked by the recognizer. * - * This object should have the same structure as [SpeechRecognitionAlternative]{@link SpeechRecognitionAlternative} + * This object should have the same structure as [SpeechRecognitionAlternative]{@link google.cloud.speech.v1.SpeechRecognitionAlternative} * - * @class + * @typedef SpeechRecognitionResult + * @memberof google.cloud.speech.v1 * @see [google.cloud.speech.v1.SpeechRecognitionResult definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} */ var SpeechRecognitionResult = { @@ -522,13 +541,54 @@ var SpeechRecognitionResult = { * indicates an estimated greater likelihood that the recognized words are * correct. This field is typically provided only for the top hypothesis, and * only for `is_final=true` results. Clients should not rely on the - * `confidence` field as it is not guaranteed to be accurate, or even set, in - * any of the results. + * `confidence` field as it is not guaranteed to be accurate or consistent. * The default of 0.0 is a sentinel value indicating `confidence` was not set. * - * @class + * @property {Object[]} words + * *Output-only* A list of word-specific information for each recognized word. + * + * This object should have the same structure as [WordInfo]{@link google.cloud.speech.v1.WordInfo} + * + * @typedef SpeechRecognitionAlternative + * @memberof google.cloud.speech.v1 * @see [google.cloud.speech.v1.SpeechRecognitionAlternative definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} */ var SpeechRecognitionAlternative = { // This is for documentation. Actual contents will be loaded by gRPC. +}; + +/** + * Word-specific information for recognized words. Word information is only + * included in the response when certain request parameters are set, such + * as `enable_word_time_offsets`. + * + * @property {Object} startTime + * *Output-only* Time offset relative to the beginning of the audio, + * and corresponding to the start of the spoken word. + * This field is only set if `enable_word_time_offsets=true` and only + * in the top hypothesis. + * This is an experimental feature and the accuracy of the time offset can + * vary. + * + * This object should have the same structure as [Duration]{@link google.protobuf.Duration} + * + * @property {Object} endTime + * *Output-only* Time offset relative to the beginning of the audio, + * and corresponding to the end of the spoken word. + * This field is only set if `enable_word_time_offsets=true` and only + * in the top hypothesis. + * This is an experimental feature and the accuracy of the time offset can + * vary. + * + * This object should have the same structure as [Duration]{@link google.protobuf.Duration} + * + * @property {string} word + * *Output-only* The word corresponding to this set of information. + * + * @typedef WordInfo + * @memberof google.cloud.speech.v1 + * @see [google.cloud.speech.v1.WordInfo definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto} + */ +var WordInfo = { + // This is for documentation. Actual contents will be loaded by gRPC. }; \ No newline at end of file diff --git a/packages/google-cloud-node/src/v1/doc/doc_google_protobuf_any.js b/packages/google-cloud-node/src/v1/doc/google/protobuf/doc_any.js similarity index 74% rename from packages/google-cloud-node/src/v1/doc/doc_google_protobuf_any.js rename to packages/google-cloud-node/src/v1/doc/google/protobuf/doc_any.js index 0697ec158142..21feb7442434 100644 --- a/packages/google-cloud-node/src/v1/doc/doc_google_protobuf_any.js +++ b/packages/google-cloud-node/src/v1/doc/google/protobuf/doc_any.js @@ -1,23 +1,19 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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. - */ +// Copyright 2017, Google LLC All rights reserved. +// +// 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. -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ +// Note: this file is purely for documentation. Any contents are not expected +// to be loaded as the JS file. /** * `Any` contains an arbitrary serialized protocol buffer message along with a @@ -55,6 +51,16 @@ * any.Unpack(foo) * ... * + * Example 4: Pack and unpack a message in Go + * + * foo := &pb.Foo{...} + * any, err := ptypes.MarshalAny(foo) + * ... + * foo := &pb.Foo{} + * if err := ptypes.UnmarshalAny(any, foo); err != nil { + * ... + * } + * * The pack methods provided by protobuf library will by default use * 'type.googleapis.com/full.type.name' as the type URL and the unpack * methods only use the fully qualified type name after the last '/' @@ -83,14 +89,13 @@ * If the embedded message type is well-known and has a custom JSON * representation, that representation will be embedded adding a field * `value` which holds the custom JSON in addition to the `@type` - * field. Example (for message {@link google.protobuf.Duration}): + * field. Example (for message google.protobuf.Duration): * * { * "@type": "type.googleapis.com/google.protobuf.Duration", * "value": "1.212s" * } * - * @external "google.protobuf.Any" * @property {string} typeUrl * A URL/resource name whose content describes the type of the * serialized protocol buffer message. @@ -103,7 +108,7 @@ * qualified name of the type (as in `path/google.protobuf.Duration`). * The name should be in a canonical form (e.g., leading "." is * not accepted). - * * An HTTP GET on the URL must yield a {@link google.protobuf.Type} + * * An HTTP GET on the URL must yield a google.protobuf.Type * value in binary format, or produce an error. * * Applications are allowed to cache lookup results based on the * URL, or have them precompiled into a binary to avoid any @@ -117,5 +122,10 @@ * @property {string} value * Must be a valid serialized protocol buffer of the above specified type. * + * @typedef Any + * @memberof google.protobuf * @see [google.protobuf.Any definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/any.proto} - */ \ No newline at end of file + */ +var Any = { + // This is for documentation. Actual contents will be loaded by gRPC. +}; \ No newline at end of file diff --git a/packages/google-cloud-node/src/v1/doc/google/protobuf/doc_duration.js b/packages/google-cloud-node/src/v1/doc/google/protobuf/doc_duration.js new file mode 100644 index 000000000000..6c3cdb383e20 --- /dev/null +++ b/packages/google-cloud-node/src/v1/doc/google/protobuf/doc_duration.js @@ -0,0 +1,97 @@ +// Copyright 2017, Google LLC All rights reserved. +// +// 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. + +// Note: this file is purely for documentation. Any contents are not expected +// to be loaded as the JS file. + +/** + * A Duration represents a signed, fixed-length span of time represented + * as a count of seconds and fractions of seconds at nanosecond + * resolution. It is independent of any calendar and concepts like "day" + * or "month". It is related to Timestamp in that the difference between + * two Timestamp values is a Duration and it can be added or subtracted + * from a Timestamp. Range is approximately +-10,000 years. + * + * # Examples + * + * Example 1: Compute Duration from two Timestamps in pseudo code. + * + * Timestamp start = ...; + * Timestamp end = ...; + * Duration duration = ...; + * + * duration.seconds = end.seconds - start.seconds; + * duration.nanos = end.nanos - start.nanos; + * + * if (duration.seconds < 0 && duration.nanos > 0) { + * duration.seconds += 1; + * duration.nanos -= 1000000000; + * } else if (durations.seconds > 0 && duration.nanos < 0) { + * duration.seconds -= 1; + * duration.nanos += 1000000000; + * } + * + * Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. + * + * Timestamp start = ...; + * Duration duration = ...; + * Timestamp end = ...; + * + * end.seconds = start.seconds + duration.seconds; + * end.nanos = start.nanos + duration.nanos; + * + * if (end.nanos < 0) { + * end.seconds -= 1; + * end.nanos += 1000000000; + * } else if (end.nanos >= 1000000000) { + * end.seconds += 1; + * end.nanos -= 1000000000; + * } + * + * Example 3: Compute Duration from datetime.timedelta in Python. + * + * td = datetime.timedelta(days=3, minutes=10) + * duration = Duration() + * duration.FromTimedelta(td) + * + * # JSON Mapping + * + * In JSON format, the Duration type is encoded as a string rather than an + * object, where the string ends in the suffix "s" (indicating seconds) and + * is preceded by the number of seconds, with nanoseconds expressed as + * fractional seconds. For example, 3 seconds with 0 nanoseconds should be + * encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should + * be expressed in JSON format as "3.000000001s", and 3 seconds and 1 + * microsecond should be expressed in JSON format as "3.000001s". + * + * @property {number} seconds + * Signed seconds of the span of time. Must be from -315,576,000,000 + * to +315,576,000,000 inclusive. Note: these bounds are computed from: + * 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years + * + * @property {number} nanos + * Signed fractions of a second at nanosecond resolution of the span + * of time. Durations less than one second are represented with a 0 + * `seconds` field and a positive or negative `nanos` field. For durations + * of one second or more, a non-zero value for the `nanos` field must be + * of the same sign as the `seconds` field. Must be from -999,999,999 + * to +999,999,999 inclusive. + * + * @typedef Duration + * @memberof google.protobuf + * @see [google.protobuf.Duration definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/duration.proto} + */ +var Duration = { + // This is for documentation. Actual contents will be loaded by gRPC. +}; \ No newline at end of file diff --git a/packages/google-cloud-node/src/v1/doc/doc_google_rpc_status.js b/packages/google-cloud-node/src/v1/doc/google/rpc/doc_status.js similarity index 67% rename from packages/google-cloud-node/src/v1/doc/doc_google_rpc_status.js rename to packages/google-cloud-node/src/v1/doc/google/rpc/doc_status.js index c85f1befe902..be5e96ce26d5 100644 --- a/packages/google-cloud-node/src/v1/doc/doc_google_rpc_status.js +++ b/packages/google-cloud-node/src/v1/doc/google/rpc/doc_status.js @@ -1,23 +1,19 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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. - */ +// Copyright 2017, Google LLC All rights reserved. +// +// 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. -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ +// Note: this file is purely for documentation. Any contents are not expected +// to be loaded as the JS file. /** * The `Status` type defines a logical error model that is suitable for different @@ -31,13 +27,13 @@ * * The `Status` message contains three pieces of data: error code, error message, * and error details. The error code should be an enum value of - * {@link google.rpc.Code}, but it may accept additional error codes if needed. The + * google.rpc.Code, but it may accept additional error codes if needed. The * error message should be a developer-facing English message that helps * developers *understand* and *resolve* the error. If a localized user-facing * error message is needed, put the localized message in the error details or * localize it in the client. The optional error details may contain arbitrary * information about the error. There is a predefined set of error detail types - * in the package `google.rpc` which can be used for common error conditions. + * in the package `google.rpc` that can be used for common error conditions. * * # Language mapping * @@ -60,7 +56,7 @@ * errors. * * - Workflow errors. A typical workflow has multiple steps. Each step may - * have a `Status` message for error reporting purpose. + * have a `Status` message for error reporting. * * - Batch operations. If a client uses batch request and batch response, the * `Status` message should be used directly inside batch response, one for @@ -73,20 +69,24 @@ * - Logging. If some API errors are stored in logs, the message `Status` could * be used directly after any stripping needed for security/privacy reasons. * - * @external "google.rpc.Status" * @property {number} code - * The status code, which should be an enum value of {@link google.rpc.Code}. + * The status code, which should be an enum value of google.rpc.Code. * * @property {string} message * A developer-facing error message, which should be in English. Any * user-facing error message should be localized and sent in the - * {@link google.rpc.Status.details} field, or localized by the client. + * google.rpc.Status.details field, or localized by the client. * * @property {Object[]} details - * A list of messages that carry the error details. There will be a - * common set of message types for APIs to use. + * A list of messages that carry the error details. There is a common set of + * message types for APIs to use. * - * This object should have the same structure as [google.protobuf.Any]{@link external:"google.protobuf.Any"} + * This object should have the same structure as [Any]{@link google.protobuf.Any} * + * @typedef Status + * @memberof google.rpc * @see [google.rpc.Status definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/rpc/status.proto} - */ \ No newline at end of file + */ +var Status = { + // This is for documentation. Actual contents will be loaded by gRPC. +}; \ No newline at end of file diff --git a/packages/google-cloud-node/src/v1/index.js b/packages/google-cloud-node/src/v1/index.js index 9aac5a2d5f9c..88ec97f1b2ce 100644 --- a/packages/google-cloud-node/src/v1/index.js +++ b/packages/google-cloud-node/src/v1/index.js @@ -1,34 +1,19 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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. - */ -'use strict'; - -var speechClient = require('./speech_client'); -var gax = require('google-gax'); -var extend = require('extend'); +// Copyright 2017, Google LLC All rights reserved. +// +// 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. -function v1(options) { - options = extend({ - scopes: v1.ALL_SCOPES - }, options); - var gaxGrpc = gax.grpc(options); - return speechClient(gaxGrpc); -} +'use strict'; -v1.GAPIC_VERSION = '0.10.0'; -v1.SERVICE_ADDRESS = speechClient.SERVICE_ADDRESS; -v1.ALL_SCOPES = speechClient.ALL_SCOPES; +const SpeechClient = require('./speech_client'); -module.exports = v1; \ No newline at end of file +module.exports.SpeechClient = SpeechClient; diff --git a/packages/google-cloud-node/src/v1/speech_client.js b/packages/google-cloud-node/src/v1/speech_client.js index 999514f76123..068723c9c118 100644 --- a/packages/google-cloud-node/src/v1/speech_client.js +++ b/packages/google-cloud-node/src/v1/speech_client.js @@ -1,398 +1,453 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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. - * - * EDITING INSTRUCTIONS - * This file was generated from the file - * https://github.com/googleapis/googleapis/blob/master/google/cloud/speech/v1/cloud_speech.proto, - * and updates to that file get reflected here through a refresh process. - * For the short term, the refresh process will only be runnable by Google - * engineers. - * - * The only allowed edits are to method and file documentation. A 3-way - * merge preserves those additions if the generated source changes. - */ -/* TODO: introduce line-wrapping so that it never exceeds the limit. */ -/* jscs: disable maximumLineLength */ -'use strict'; - -var configData = require('./speech_client_config'); -var extend = require('extend'); -var gax = require('google-gax'); +// Copyright 2017, Google LLC All rights reserved. +// +// 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. -var SERVICE_ADDRESS = 'speech.googleapis.com'; - -var DEFAULT_SERVICE_PORT = 443; +'use strict'; -var CODE_GEN_NAME_VERSION = 'gapic/0.10.0'; +const gapicConfig = require('./speech_client_config'); +const gax = require('google-gax'); +const merge = require('lodash.merge'); +const path = require('path'); +const protobuf = require('protobufjs'); -var STREAM_DESCRIPTORS = { - streamingRecognize: new gax.StreamDescriptor(gax.StreamType.BIDI_STREAMING) -}; - -/** - * The scopes needed to make gRPC calls to all of the methods defined in - * this service. - */ -var ALL_SCOPES = [ - 'https://www.googleapis.com/auth/cloud-platform' -]; +const VERSION = require('../../package.json').version; /** * Service that implements Google Cloud Speech API. * - * * @class + * @memberof v1 */ -function SpeechClient(gaxGrpc, grpcClients, opts) { - opts = extend({ - servicePath: SERVICE_ADDRESS, - port: DEFAULT_SERVICE_PORT, - clientConfig: {} - }, opts); +class SpeechClient { + /** + * Construct an instance of SpeechClient. + * + * @param {object} [options] - The configuration object. See the subsequent + * parameters for more details. + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * usaing a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option above is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param {function} [options.promise] - Custom promise module to use instead + * of native Promises. + * @param {string} [options.servicePath] - The domain name of the + * API remote host. + */ + constructor(opts) { + this._descriptors = {}; - var googleApiClient = [ - 'gl-node/' + process.versions.node - ]; - if (opts.libName && opts.libVersion) { - googleApiClient.push(opts.libName + '/' + opts.libVersion); - } - googleApiClient.push( - CODE_GEN_NAME_VERSION, - 'gax/' + gax.version, - 'grpc/' + gaxGrpc.grpcVersion - ); + // Ensure that options include the service address and port. + opts = Object.assign( + { + clientConfig: {}, + port: this.constructor.port, + servicePath: this.constructor.servicePath, + }, + opts + ); - this.operationsClient = new gax.lro({ - auth: gaxGrpc.auth, - grpc: gaxGrpc.grpc - }).operationsClient(opts); + // Create a `gaxGrpc` object, with any grpc-specific options + // sent to the client. + opts.scopes = this.constructor.scopes; + var gaxGrpc = gax.grpc(opts); - this.longrunningDescriptors = { - longRunningRecognize: new gax.LongrunningDescriptor( - this.operationsClient, - grpcClients.google.cloud.speech.v1.LongRunningRecognizeResponse.decode, - grpcClients.google.cloud.speech.v1.LongRunningRecognizeMetadata.decode) - }; + // Save the auth object to the client, for use by other methods. + this.auth = gaxGrpc.auth; - var defaults = gaxGrpc.constructSettings( - 'google.cloud.speech.v1.Speech', - configData, - opts.clientConfig, - {'x-goog-api-client': googleApiClient.join(' ')}); + // Determine the client header string. + var clientHeader = [ + `gl-node/${process.version.node}`, + `grpc/${gaxGrpc.grpcVersion}`, + `gax/${gax.version}`, + `gapic/${VERSION}`, + ]; + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } - var self = this; + // Load the applicable protos. + var protos = merge( + {}, + gaxGrpc.loadProto( + path.join(__dirname, '..', '..', 'protos'), + 'google/cloud/speech/v1/cloud_speech.proto' + ) + ); - this.auth = gaxGrpc.auth; - var speechStub = gaxGrpc.createStub( - grpcClients.google.cloud.speech.v1.Speech, - opts); - var speechStubMethods = [ - 'recognize', - 'longRunningRecognize', - 'streamingRecognize' - ]; - speechStubMethods.forEach(function(methodName) { - self['_' + methodName] = gax.createApiCall( - speechStub.then(function(speechStub) { - return function() { - var args = Array.prototype.slice.call(arguments, 0); - return speechStub[methodName].apply(speechStub, args); - }; - }), - defaults[methodName], - STREAM_DESCRIPTORS[methodName] || self.longrunningDescriptors[methodName]); - }); -} + // Some of the methods on this service provide streaming responses. + // Provide descriptors for these. + this._descriptors.stream = { + streamingRecognize: new gax.StreamDescriptor( + gax.StreamType.BIDI_STREAMING + ), + }; + var protoFilesRoot = new gax.grpc.GoogleProtoFilesRoot(); + protoFilesRoot = protobuf.loadSync( + path.join( + __dirname, + '..', + '..', + 'protos', + 'google/cloud/speech/v1/cloud_speech.proto' + ), + protoFilesRoot + ); + // This API contains "long-running operations", which return a + // an Operation object that allows for tracking of the operation, + // rather than holding a request open. + this.operationsClient = new gax.lro({ + auth: gaxGrpc.auth, + grpc: gaxGrpc.grpc, + }).operationsClient(opts); -/** - * Get the project ID used by this class. - * @param {function(Error, string)} callback - the callback to be called with - * the current project Id. - */ -SpeechClient.prototype.getProjectId = function(callback) { - return this.auth.getProjectId(callback); -}; + var longRunningRecognizeResponse = protoFilesRoot.lookup( + 'google.cloud.speech.v1.LongRunningRecognizeResponse' + ); + var longRunningRecognizeMetadata = protoFilesRoot.lookup( + 'google.cloud.speech.v1.LongRunningRecognizeMetadata' + ); -// Service calls + this._descriptors.longrunning = { + longRunningRecognize: new gax.LongrunningDescriptor( + this.operationsClient, + longRunningRecognizeResponse.decode.bind(longRunningRecognizeResponse), + longRunningRecognizeMetadata.decode.bind(longRunningRecognizeMetadata) + ), + }; -/** - * Performs synchronous speech recognition: receive results after all audio - * has been sent and processed. - * - * @param {Object} request - * The request object that will be sent. - * @param {Object} request.config - * *Required* Provides information to the recognizer that specifies how to - * process the request. - * - * This object should have the same structure as [RecognitionConfig]{@link RecognitionConfig} - * @param {Object} request.audio - * *Required* The audio data to be recognized. - * - * This object should have the same structure as [RecognitionAudio]{@link RecognitionAudio} - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing [RecognizeResponse]{@link RecognizeResponse}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [RecognizeResponse]{@link RecognizeResponse}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var speech = require('@google-cloud/speech'); - * - * var client = speech.v1({ - * // optional auth parameters. - * }); - * - * var encoding = speech.v1.types.RecognitionConfig.AudioEncoding.FLAC; - * var sampleRateHertz = 44100; - * var languageCode = 'en-US'; - * var config = { - * encoding : encoding, - * sampleRateHertz : sampleRateHertz, - * languageCode : languageCode - * }; - * var uri = 'gs://bucket_name/file_name.flac'; - * var audio = { - * uri : uri - * }; - * var request = { - * config: config, - * audio: audio - * }; - * client.recognize(request).then(function(responses) { - * var response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(function(err) { - * console.error(err); - * }); - */ -SpeechClient.prototype.recognize = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } + // Put together the default options sent with requests. + var defaults = gaxGrpc.constructSettings( + 'google.cloud.speech.v1.Speech', + gapicConfig, + opts.clientConfig, + {'x-goog-api-client': clientHeader.join(' ')} + ); - return this._recognize(request, options, callback); -}; + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this._innerApiCalls = {}; -/** - * Performs asynchronous speech recognition: receive results via the - * google.longrunning.Operations interface. Returns either an - * `Operation.error` or an `Operation.response` which contains - * a `LongRunningRecognizeResponse` message. - * - * @param {Object} request - * The request object that will be sent. - * @param {Object} request.config - * *Required* Provides information to the recognizer that specifies how to - * process the request. - * - * This object should have the same structure as [RecognitionConfig]{@link RecognitionConfig} - * @param {Object} request.audio - * *Required* The audio data to be recognized. - * - * This object should have the same structure as [RecognitionAudio]{@link RecognitionAudio} - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var speech = require('@google-cloud/speech'); - * - * var client = speech.v1({ - * // optional auth parameters. - * }); - * - * var encoding = speech.v1.types.RecognitionConfig.AudioEncoding.FLAC; - * var sampleRateHertz = 44100; - * var languageCode = 'en-US'; - * var config = { - * encoding : encoding, - * sampleRateHertz : sampleRateHertz, - * languageCode : languageCode - * }; - * var uri = 'gs://bucket_name/file_name.flac'; - * var audio = { - * uri : uri - * }; - * var request = { - * config: config, - * audio: audio - * }; - * - * // Handle the operation using the promise pattern. - * client.longRunningRecognize(request).then(function(responses) { - * var operation = responses[0]; - * var initialApiResponse = responses[1]; - * - * // Operation#promise starts polling for the completion of the LRO. - * return operation.promise(); - * }).then(function(responses) { - * // The final result of the operation. - * var result = responses[0]; - * - * // The metadata value of the completed operation. - * var metadata = responses[1]; - * - * // The response of the api call returning the complete operation. - * var finalApiResponse = responses[2]; - * }) - * .catch(function(err) { - * console.error(err); - * }); - * - * var encoding = speech.v1.types.RecognitionConfig.AudioEncoding.FLAC; - * var sampleRateHertz = 44100; - * var languageCode = 'en-US'; - * var config = { - * encoding : encoding, - * sampleRateHertz : sampleRateHertz, - * languageCode : languageCode - * }; - * var uri = 'gs://bucket_name/file_name.flac'; - * var audio = { - * uri : uri - * }; - * var request = { - * config: config, - * audio: audio - * }; - * - * // Handle the operation using the event emitter pattern. - * client.longRunningRecognize(request).then(function(responses) { - * var operation = responses[0]; - * var initialApiResponse = responses[1]; - * - * // Adding a listener for the "complete" event starts polling for the - * // completion of the operation. - * operation.on('complete', function(result, metadata, finalApiResponse) { - * // doSomethingWith(result); - * }); - * - * // Adding a listener for the "progress" event causes the callback to be - * // called on any change in metadata when the operation is polled. - * operation.on('progress', function(metadata, apiResponse) { - * // doSomethingWith(metadata) - * }) - * - * // Adding a listener for the "error" event handles any errors found during polling. - * operation.on('error', function(err) { - * // throw(err); - * }) - * }) - * .catch(function(err) { - * console.error(err); - * }); - */ -SpeechClient.prototype.longRunningRecognize = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; + // Put together the "service stub" for + // google.cloud.speech.v1.Speech. + var speechStub = gaxGrpc.createStub( + protos.google.cloud.speech.v1.Speech, + opts + ); + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + var speechStubMethods = [ + 'recognize', + 'longRunningRecognize', + 'streamingRecognize', + ]; + for (let methodName of speechStubMethods) { + this._innerApiCalls[methodName] = gax.createApiCall( + speechStub.then( + stub => + function() { + var args = Array.prototype.slice.call(arguments, 0); + return stub[methodName].apply(stub, args); + } + ), + defaults[methodName], + this._descriptors.stream[methodName] || + this._descriptors.longrunning[methodName] + ); + } } - if (options === undefined) { - options = {}; + + /** + * The DNS address for this API service. + */ + static get servicePath() { + return 'speech.googleapis.com'; } - return this._longRunningRecognize(request, options, callback); -}; + /** + * The port for this API service. + */ + static get port() { + return 443; + } -/** - * Performs bidirectional streaming speech recognition: receive results while - * sending audio. This method is only available via the gRPC API (not REST). - * - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing [StreamingRecognizeRequest]{@link StreamingRecognizeRequest} for write() method, and - * will emit objects representing [StreamingRecognizeResponse]{@link StreamingRecognizeResponse} on 'data' event asynchronously. - * - * @example - * - * var speech = require('@google-cloud/speech'); - * - * var client = speech.v1({ - * // optional auth parameters. - * }); - * - * var stream = client.streamingRecognize().on('data', function(response) { - * // doThingsWith(response) - * }); - * var request = {}; - * // Write request objects. - * stream.write(request); - */ -SpeechClient.prototype.streamingRecognize = function(options) { - if (options === undefined) { - options = {}; + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + */ + static get scopes() { + return ['https://www.googleapis.com/auth/cloud-platform']; } - return this._streamingRecognize(options); -}; + /** + * Return the project ID used by this class. + * @param {function(Error, string)} callback - the callback to + * be called with the current project Id. + */ + getProjectId(callback) { + return this.auth.getProjectId(callback); + } + + // ------------------- + // -- Service calls -- + // ------------------- -function SpeechClientBuilder(gaxGrpc) { - if (!(this instanceof SpeechClientBuilder)) { - return new SpeechClientBuilder(gaxGrpc); + /** + * Performs synchronous speech recognition: receive results after all audio + * has been sent and processed. + * + * @param {Object} request + * The request object that will be sent. + * @param {Object} request.config + * *Required* Provides information to the recognizer that specifies how to + * process the request. + * + * This object should have the same structure as [RecognitionConfig]{@link google.cloud.speech.v1.RecognitionConfig} + * @param {Object} request.audio + * *Required* The audio data to be recognized. + * + * This object should have the same structure as [RecognitionAudio]{@link google.cloud.speech.v1.RecognitionAudio} + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param {function(?Error, ?Object)} [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [RecognizeResponse]{@link google.cloud.speech.v1.RecognizeResponse}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing [RecognizeResponse]{@link google.cloud.speech.v1.RecognizeResponse}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * const speech = require('@google-cloud/speech'); + * + * var client = new speech.v1.SpeechClient({ + * // optional auth parameters. + * }); + * + * var encoding = 'FLAC'; + * var sampleRateHertz = 44100; + * var languageCode = 'en-US'; + * var config = { + * encoding: encoding, + * sampleRateHertz: sampleRateHertz, + * languageCode: languageCode, + * }; + * var uri = 'gs://bucket_name/file_name.flac'; + * var audio = { + * uri: uri, + * }; + * var request = { + * config: config, + * audio: audio, + * }; + * client.recognize(request) + * .then(responses => { + * var response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + recognize(request, options, callback) { + if (options instanceof Function && callback === undefined) { + callback = options; + options = {}; + } + options = options || {}; + + return this._innerApiCalls.recognize(request, options, callback); } - var speechClient = gaxGrpc.load([{ - root: require('google-proto-files')('..'), - file: 'google/cloud/speech/v1/cloud_speech.proto' - }]); - extend(this, speechClient.google.cloud.speech.v1); + /** + * Performs asynchronous speech recognition: receive results via the + * google.longrunning.Operations interface. Returns either an + * `Operation.error` or an `Operation.response` which contains + * a `LongRunningRecognizeResponse` message. + * + * @param {Object} request + * The request object that will be sent. + * @param {Object} request.config + * *Required* Provides information to the recognizer that specifies how to + * process the request. + * + * This object should have the same structure as [RecognitionConfig]{@link google.cloud.speech.v1.RecognitionConfig} + * @param {Object} request.audio + * *Required* The audio data to be recognized. + * + * This object should have the same structure as [RecognitionAudio]{@link google.cloud.speech.v1.RecognitionAudio} + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param {function(?Error, ?Object)} [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * const speech = require('@google-cloud/speech'); + * + * var client = new speech.v1.SpeechClient({ + * // optional auth parameters. + * }); + * + * var encoding = 'FLAC'; + * var sampleRateHertz = 44100; + * var languageCode = 'en-US'; + * var config = { + * encoding: encoding, + * sampleRateHertz: sampleRateHertz, + * languageCode: languageCode, + * }; + * var uri = 'gs://bucket_name/file_name.flac'; + * var audio = { + * uri: uri, + * }; + * var request = { + * config: config, + * audio: audio, + * }; + * + * // Handle the operation using the promise pattern. + * client.longRunningRecognize(request) + * .then(responses => { + * var operation = responses[0]; + * var initialApiResponse = responses[1]; + * + * // Operation#promise starts polling for the completion of the LRO. + * return operation.promise(); + * }) + * .then(responses => { + * // The final result of the operation. + * var result = responses[0]; + * + * // The metadata value of the completed operation. + * var metadata = responses[1]; + * + * // The response of the api call returning the complete operation. + * var finalApiResponse = responses[2]; + * }) + * .catch(err => { + * console.error(err); + * }); + * + * var encoding = 'FLAC'; + * var sampleRateHertz = 44100; + * var languageCode = 'en-US'; + * var config = { + * encoding: encoding, + * sampleRateHertz: sampleRateHertz, + * languageCode: languageCode, + * }; + * var uri = 'gs://bucket_name/file_name.flac'; + * var audio = { + * uri: uri, + * }; + * var request = { + * config: config, + * audio: audio, + * }; + * + * // Handle the operation using the event emitter pattern. + * client.longRunningRecognize(request) + * .then(responses => { + * var operation = responses[0]; + * var initialApiResponse = responses[1]; + * + * // Adding a listener for the "complete" event starts polling for the + * // completion of the operation. + * operation.on('complete', (result, metadata, finalApiResponse) => { + * // doSomethingWith(result); + * }); + * + * // Adding a listener for the "progress" event causes the callback to be + * // called on any change in metadata when the operation is polled. + * operation.on('progress', (metadata, apiResponse) => { + * // doSomethingWith(metadata) + * }); + * + * // Adding a listener for the "error" event handles any errors found during polling. + * operation.on('error', err => { + * // throw(err); + * }); + * }) + * .catch(err => { + * console.error(err); + * }); + */ + longRunningRecognize(request, options, callback) { + if (options instanceof Function && callback === undefined) { + callback = options; + options = {}; + } + options = options || {}; + return this._innerApiCalls.longRunningRecognize(request, options, callback); + } /** - * Build a new instance of {@link SpeechClient}. + * Performs bidirectional streaming speech recognition: receive results while + * sending audio. This method is only available via the gRPC API (not REST). * - * @param {Object=} opts - The optional parameters. - * @param {String=} opts.servicePath - * The domain name of the API remote host. - * @param {number=} opts.port - * The port on which to connect to the remote host. - * @param {grpc.ClientCredentials=} opts.sslCreds - * A ClientCredentials for use with an SSL-enabled channel. - * @param {Object=} opts.clientConfig - * The customized config to build the call settings. See - * {@link gax.constructSettings} for the format. + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing [StreamingRecognizeRequest]{@link google.cloud.speech.v1.StreamingRecognizeRequest} for write() method, and + * will emit objects representing [StreamingRecognizeResponse]{@link google.cloud.speech.v1.StreamingRecognizeResponse} on 'data' event asynchronously. + * + * @example + * + * const speech = require('@google-cloud/speech'); + * + * var client = new speech.v1.SpeechClient({ + * // optional auth parameters. + * }); + * + * var stream = client.streamingRecognize().on('data', response => { + * // doThingsWith(response) + * }); + * var request = {}; + * // Write request objects. + * stream.write(request); */ - this.speechClient = function(opts) { - return new SpeechClient(gaxGrpc, speechClient, opts); - }; - extend(this.speechClient, SpeechClient); + streamingRecognize(options) { + options = options || {}; + + return this._innerApiCalls.streamingRecognize(options); + } } -module.exports = SpeechClientBuilder; -module.exports.SERVICE_ADDRESS = SERVICE_ADDRESS; -module.exports.ALL_SCOPES = ALL_SCOPES; \ No newline at end of file + +module.exports = SpeechClient; diff --git a/packages/google-cloud-node/src/v1/speech_client_config.json b/packages/google-cloud-node/src/v1/speech_client_config.json index bf5c507caf1a..7428b7882144 100644 --- a/packages/google-cloud-node/src/v1/speech_client_config.json +++ b/packages/google-cloud-node/src/v1/speech_client_config.json @@ -31,7 +31,7 @@ "retry_params_name": "default" }, "StreamingRecognize": { - "timeout_millis": 190000, + "timeout_millis": 600000, "retry_codes_name": "idempotent", "retry_params_name": "default" } diff --git a/packages/google-cloud-node/system-test/.eslintrc.yml b/packages/google-cloud-node/system-test/.eslintrc.yml new file mode 100644 index 000000000000..2e6882e46d23 --- /dev/null +++ b/packages/google-cloud-node/system-test/.eslintrc.yml @@ -0,0 +1,6 @@ +--- +env: + mocha: true +rules: + node/no-unpublished-require: off + no-console: off diff --git a/packages/google-cloud-node/system-test/speech_smoke_test.js b/packages/google-cloud-node/system-test/speech_smoke_test.js new file mode 100644 index 000000000000..3cb013bf094b --- /dev/null +++ b/packages/google-cloud-node/system-test/speech_smoke_test.js @@ -0,0 +1,50 @@ +// Copyright 2017, Google LLC All rights reserved. +// +// 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. + +'use strict'; + +describe('SpeechSmokeTest', () => { + it('successfully makes a call to the service', done => { + const speech = require('../src'); + + var client = new speech.v1.SpeechClient({ + // optional auth parameters. + }); + + var languageCode = 'en-US'; + var sampleRateHertz = 44100; + var encoding = 'FLAC'; + var config = { + languageCode: languageCode, + sampleRateHertz: sampleRateHertz, + encoding: encoding, + }; + var uri = 'gs://gapic-toolkit/hello.flac'; + var audio = { + uri: uri, + }; + var request = { + config: config, + audio: audio, + }; + client + .recognize(request) + .then(responses => { + var response = responses[0]; + console.log(response); + }) + .then(done) + .catch(done); + }); +}); diff --git a/packages/google-cloud-node/test/.eslintrc.yml b/packages/google-cloud-node/test/.eslintrc.yml new file mode 100644 index 000000000000..73f7bbc946f9 --- /dev/null +++ b/packages/google-cloud-node/test/.eslintrc.yml @@ -0,0 +1,5 @@ +--- +env: + mocha: true +rules: + node/no-unpublished-require: off diff --git a/packages/google-cloud-node/test/gapic-v1.test.js b/packages/google-cloud-node/test/gapic-v1.test.js index 2e37b7ff5384..1240223be762 100644 --- a/packages/google-cloud-node/test/gapic-v1.test.js +++ b/packages/google-cloud-node/test/gapic-v1.test.js @@ -1,210 +1,220 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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. - */ +// Copyright 2017, Google LLC All rights reserved. +// +// 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. + 'use strict'; -var assert = require('assert'); -var speechV1 = require('../src/v1')(); -var through2 = require('through2'); +const assert = require('assert'); + +const speechModule = require('../src'); var FAKE_STATUS_CODE = 1; var error = new Error(); error.code = FAKE_STATUS_CODE; -describe('SpeechClient', function() { - describe('recognize', function() { - it('invokes recognize without error', function(done) { - var client = speechV1.speechClient(); +describe('SpeechClient', () => { + describe('recognize', () => { + it('invokes recognize without error', done => { + var client = new speechModule.v1.SpeechClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Mock request - var encoding = speechV1.RecognitionConfig.AudioEncoding.FLAC; + var encoding = 'FLAC'; var sampleRateHertz = 44100; var languageCode = 'en-US'; var config = { - encoding : encoding, - sampleRateHertz : sampleRateHertz, - languageCode : languageCode + encoding: encoding, + sampleRateHertz: sampleRateHertz, + languageCode: languageCode, }; var uri = 'gs://bucket_name/file_name.flac'; var audio = { - uri : uri + uri: uri, }; var request = { - config : config, - audio : audio + config: config, + audio: audio, }; // Mock response var expectedResponse = {}; // Mock Grpc layer - client._recognize = mockSimpleGrpcMethod(request, expectedResponse); + client._innerApiCalls.recognize = mockSimpleGrpcMethod( + request, + expectedResponse + ); - client.recognize(request, function(err, response) { + client.recognize(request, (err, response) => { assert.ifError(err); assert.deepStrictEqual(response, expectedResponse); done(); }); }); - it('invokes recognize with error', function(done) { - var client = speechV1.speechClient(); + it('invokes recognize with error', done => { + var client = new speechModule.v1.SpeechClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Mock request - var encoding = speechV1.RecognitionConfig.AudioEncoding.FLAC; + var encoding = 'FLAC'; var sampleRateHertz = 44100; var languageCode = 'en-US'; var config = { - encoding : encoding, - sampleRateHertz : sampleRateHertz, - languageCode : languageCode + encoding: encoding, + sampleRateHertz: sampleRateHertz, + languageCode: languageCode, }; var uri = 'gs://bucket_name/file_name.flac'; var audio = { - uri : uri + uri: uri, }; var request = { - config : config, - audio : audio + config: config, + audio: audio, }; // Mock Grpc layer - client._recognize = mockSimpleGrpcMethod(request, null, error); + client._innerApiCalls.recognize = mockSimpleGrpcMethod( + request, + null, + error + ); - client.recognize(request, function(err, response) { + client.recognize(request, (err, response) => { assert(err instanceof Error); assert.equal(err.code, FAKE_STATUS_CODE); + assert(typeof response === 'undefined'); done(); }); }); }); describe('longRunningRecognize', function() { - it('invokes longRunningRecognize without error', function(done) { - var client = speechV1.speechClient(); + it('invokes longRunningRecognize without error', done => { + var client = new speechModule.v1.SpeechClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Mock request - var encoding = speechV1.RecognitionConfig.AudioEncoding.FLAC; + var encoding = 'FLAC'; var sampleRateHertz = 44100; var languageCode = 'en-US'; var config = { - encoding : encoding, - sampleRateHertz : sampleRateHertz, - languageCode : languageCode + encoding: encoding, + sampleRateHertz: sampleRateHertz, + languageCode: languageCode, }; var uri = 'gs://bucket_name/file_name.flac'; var audio = { - uri : uri + uri: uri, }; var request = { - config : config, - audio : audio + config: config, + audio: audio, }; // Mock response var expectedResponse = {}; // Mock Grpc layer - client._longRunningRecognize = mockLongRunningGrpcMethod(request, expectedResponse); + client._innerApiCalls.longRunningRecognize = mockLongRunningGrpcMethod( + request, + expectedResponse + ); + + client + .longRunningRecognize(request) + .then(responses => { + var operation = responses[0]; + return operation.promise(); + }) + .then(responses => { + assert.deepStrictEqual(responses[0], expectedResponse); + done(); + }) + .catch(err => { + done(err); + }); + }); - client.longRunningRecognize(request).then(function(responses) { - var operation = responses[0]; - return operation.promise(); - }).then(function(responses) { - assert.deepStrictEqual(responses[0], expectedResponse); - done(); - }).catch(function(err) { - done(err); + it('invokes longRunningRecognize with error', done => { + var client = new speechModule.v1.SpeechClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', }); - }); - it('invokes longRunningRecognize with error', function(done) { - var client = speechV1.speechClient(); // Mock request - var encoding = speechV1.RecognitionConfig.AudioEncoding.FLAC; + var encoding = 'FLAC'; var sampleRateHertz = 44100; var languageCode = 'en-US'; var config = { - encoding : encoding, - sampleRateHertz : sampleRateHertz, - languageCode : languageCode + encoding: encoding, + sampleRateHertz: sampleRateHertz, + languageCode: languageCode, }; var uri = 'gs://bucket_name/file_name.flac'; var audio = { - uri : uri + uri: uri, }; var request = { - config : config, - audio : audio + config: config, + audio: audio, }; // Mock Grpc layer - client._longRunningRecognize = mockLongRunningGrpcMethod(request, null, error); - - client.longRunningRecognize(request).then(function(responses) { - var operation = responses[0]; - return operation.promise(); - }).then(function(responses) { - assert.fail(); - }).catch(function(err) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - - describe('streamingRecognize', function() { - it('invokes streamingRecognize without error', function(done) { - var client = speechV1.speechClient(); - // Mock request - var request = {}; - - // Mock response - var expectedResponse = {}; - - // Mock Grpc layer - client._streamingRecognize = mockBidiStreamingGrpcMethod(request, expectedResponse); - - var stream = client.streamingRecognize().on('data', function(response) { - assert.deepStrictEqual(response, expectedResponse); - done() - }).on('error', function(err) { - done(err); - }); - - stream.write(request); + client._innerApiCalls.longRunningRecognize = mockLongRunningGrpcMethod( + request, + null, + error + ); + + client + .longRunningRecognize(request) + .then(responses => { + var operation = responses[0]; + return operation.promise(); + }) + .then(() => { + assert.fail(); + }) + .catch(err => { + assert(err instanceof Error); + assert.equal(err.code, FAKE_STATUS_CODE); + done(); + }); }); - it('invokes streamingRecognize with error', function(done) { - var client = speechV1.speechClient(); - // Mock request - var request = {}; - - // Mock Grpc layer - client._streamingRecognize = mockBidiStreamingGrpcMethod(request, null, error); - - var stream = client.streamingRecognize().on('data', function(response) { - assert.fail(); - }).on('error', function(err) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); + it('has longrunning decoder functions', () => { + var client = new speechModule.v1.SpeechClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', }); - - stream.write(request); + assert( + client._descriptors.longrunning.longRunningRecognize + .responseDecoder instanceof Function + ); + assert( + client._descriptors.longrunning.longRunningRecognize + .metadataDecoder instanceof Function + ); }); }); - }); function mockSimpleGrpcMethod(expectedRequest, response, error) { @@ -220,33 +230,19 @@ function mockSimpleGrpcMethod(expectedRequest, response, error) { }; } -function mockBidiStreamingGrpcMethod(expectedRequest, response, error) { - return function() { - var mockStream = through2.obj(function (chunk, enc, callback) { - assert.deepStrictEqual(chunk, expectedRequest); - if (error) { - callback(error); - } else { - callback(null, response); - } - }); - return mockStream; - } -} - function mockLongRunningGrpcMethod(expectedRequest, response, error) { - return function(request) { + return request => { assert.deepStrictEqual(request, expectedRequest); var mockOperation = { promise: function() { - return new Promise(function(resolve, reject) { + return new Promise((resolve, reject) => { if (error) { reject(error); } else { resolve([response]); } }); - } + }, }; return Promise.resolve([mockOperation]); }; diff --git a/packages/google-cloud-node/test/helpers.test.js b/packages/google-cloud-node/test/helpers.test.js index effdeefece04..89d5afc6d5e6 100644 --- a/packages/google-cloud-node/test/helpers.test.js +++ b/packages/google-cloud-node/test/helpers.test.js @@ -17,17 +17,18 @@ 'use strict'; var assert = require('assert'); +var Buffer = require('safe-buffer').Buffer; var sinon = require('sinon'); var stream = require('stream'); -var Speech = require('../'); +var speech = require('../'); describe('Speech helper methods', () => { var sandbox = sinon.sandbox.create(); - var speech; + var client; beforeEach(() => { - speech = Speech.v1(); + client = new speech.v1.SpeechClient(); }); afterEach(() => { @@ -35,19 +36,22 @@ describe('Speech helper methods', () => { }); describe('streamingRecognize', () => { - var CONFIG = {config: {languageCode: 'en-us'}}; + var CONFIG = { + config: {encoding: 'LINEAR16', languageCode: 'en-us', sampleRate: 16000}, + }; var OPTIONS = {timeout: Infinity}; - it('writes the config to the resulting stream', (done) => { + it('writes the config to the resulting stream', done => { // Stub the underlying _streamingRecognize method to just return // a bogus stream. - var requestStream = new stream.PassThrough({ objectMode: true }); - var sr = sandbox.stub(speech, '_streamingRecognize') + var requestStream = new stream.PassThrough({objectMode: true}); + var sr = sandbox + .stub(client._innerApiCalls, 'streamingRecognize') .returns(requestStream); // Call the new helper method and establish that the config was // forwarded as expected. - var userStream = speech.streamingRecognize(CONFIG, OPTIONS); + var userStream = client.streamingRecognize(CONFIG, OPTIONS); // Establish that the underlying streamingRecognize was called with // the options. @@ -56,7 +60,7 @@ describe('Speech helper methods', () => { requestStream._write = (data, enc, next) => { assert.deepStrictEqual(data, { - streamingConfig: CONFIG + streamingConfig: CONFIG, }); setImmediate(done); next(null, data); @@ -68,11 +72,12 @@ describe('Speech helper methods', () => { it('does not require options', () => { // Stub the underlying _streamingRecognize method to just return // a bogus stream. - var requestStream = new stream.PassThrough({ objectMode: true }); - var sr = sandbox.stub(speech, '_streamingRecognize') + var requestStream = new stream.PassThrough({objectMode: true}); + var sr = sandbox + .stub(client._innerApiCalls, 'streamingRecognize') .returns(requestStream); - var userStream = speech.streamingRecognize(CONFIG); + var userStream = client.streamingRecognize(CONFIG); userStream.emit('writing'); @@ -80,17 +85,19 @@ describe('Speech helper methods', () => { assert(sr.calledWithExactly({})); }); - it('destroys the user stream when the request stream errors', (done) => { + it('destroys the user stream when the request stream errors', done => { // Stub the underlying _streamingRecognize method to just return // a bogus stream. - var requestStream = new stream.PassThrough({ objectMode: true }); - sandbox.stub(speech, '_streamingRecognize').returns(requestStream); + var requestStream = new stream.PassThrough({objectMode: true}); + sandbox + .stub(client._innerApiCalls, 'streamingRecognize') + .returns(requestStream); - var userStream = speech.streamingRecognize(CONFIG, OPTIONS); + var userStream = client.streamingRecognize(CONFIG, OPTIONS); var error = new Error('Request stream error'); - userStream.once('error', (err) => { + userStream.once('error', err => { assert.strictEqual(err, error); done(); }); @@ -100,17 +107,19 @@ describe('Speech helper methods', () => { requestStream.emit('error', error); }); - it('re-emits response from the request stream', (done) => { + it('re-emits response from the request stream', done => { // Stub the underlying _streamingRecognize method to just return // a bogus stream. - var requestStream = new stream.PassThrough({ objectMode: true }); - sandbox.stub(speech, '_streamingRecognize').returns(requestStream); + var requestStream = new stream.PassThrough({objectMode: true}); + sandbox + .stub(client._innerApiCalls, 'streamingRecognize') + .returns(requestStream); - var userStream = speech.streamingRecognize(CONFIG, OPTIONS); + var userStream = client.streamingRecognize(CONFIG, OPTIONS); var response = {}; - userStream.on('response', (_response) => { + userStream.on('response', _response => { assert.strictEqual(_response, response); done(); }); @@ -119,18 +128,20 @@ describe('Speech helper methods', () => { requestStream.emit('response', response); }); - it('wraps incoming audio data', (done) => { + it('wraps incoming audio data', done => { // Stub the underlying _streamingRecognize method to just return // a bogus stream. - var requestStream = new stream.PassThrough({ objectMode: true }); - sandbox.stub(speech, '_streamingRecognize').returns(requestStream); + var requestStream = new stream.PassThrough({objectMode: true}); + sandbox + .stub(client._innerApiCalls, 'streamingRecognize') + .returns(requestStream); - var userStream = speech.streamingRecognize(CONFIG, OPTIONS); - var audioContent = new Buffer('audio content'); + var userStream = client.streamingRecognize(CONFIG, OPTIONS); + var audioContent = Buffer.from('audio content'); requestStream._write = (data, enc, next) => { if (data && data.streamingConfig !== CONFIG) { - assert.deepStrictEqual(data, { audioContent }); + assert.deepStrictEqual(data, {audioContent}); setImmediate(done); }