diff --git a/language/README.md b/language/README.md index fb7ec57303..c07335b54a 100644 --- a/language/README.md +++ b/language/README.md @@ -31,30 +31,30 @@ Learning API. View the [documentation][analyze_docs] or the [source code][analyze_code]. -__Usage:__ `node analyze --help` +__Usage:__ `node analyze.js --help` ``` Commands: - sentimentOfText Detect the sentiment of a block of text. - sentimentInFile Detect the sentiment of text in a GCS file. - entitiesOfText Detect the entities of a block of text. - entitiesInFile Detect the entities of text in a GCS file. - syntaxOfText Detect the syntax of a block of text. - syntaxInFile Detect the syntax of text in a GCS file. + sentiment-text Detects sentiment of a string. + sentiment-file Detects sentiment in a file in Google Cloud Storage. + entities-text Detects entities in a string. + entities-file Detects entities in a file in Google Cloud Storage. + syntax-text Detects syntax of a string. + syntax-file Detects syntax in a file in Google Cloud Storage. Options: --help Show help [boolean] Examples: - node analyze sentimentOfText "President Obama is speaking at + node analyze.js sentiment-text "President Obama is speaking + at the White House." + node analyze.js sentiment-file my-bucket file.txt Detects sentiment in gs://my-bucket/file.txt + node analyze.js entities-text "President Obama is speaking + at the White House." + node analyze.js entities-file my-bucket file.txt Detects entities in gs://my-bucket/file.txt + node analyze.js syntax-text "President Obama is speaking at the White House." - node analyze sentimentInFile my-bucket file.txt - node analyze entitiesOfText "President Obama is speaking at - the White House." - node analyze entitiesInFile my-bucket file.txt - node analyze syntaxOfText "President Obama is speaking at - the White House." - node analyze syntaxInFile my-bucket file.txt + node analyze.js syntax-file my-bucket file.txt Detects syntax in gs://my-bucket/file.txt For more information, see https://cloud.google.com/natural-language/docs ``` diff --git a/language/analyze.js b/language/analyze.js index ffae71ffaa..5b2aae8905 100644 --- a/language/analyze.js +++ b/language/analyze.js @@ -33,7 +33,9 @@ function analyzeSentimentOfText (text) { return document.detectSentiment() .then((results) => { const sentiment = results[0]; + console.log(`Sentiment: ${sentiment >= 0 ? 'positive' : 'negative'}.`); + return sentiment; }); } @@ -60,7 +62,9 @@ function analyzeSentimentInFile (bucketName, fileName) { return document.detectSentiment() .then((results) => { const sentiment = results[0]; + console.log(`Sentiment: ${sentiment >= 0 ? 'positive' : 'negative'}.`); + return sentiment; }); } @@ -81,10 +85,12 @@ function analyzeEntitiesOfText (text) { return document.detectEntities() .then((results) => { const entities = results[0]; + console.log('Entities:'); for (let type in entities) { console.log(`${type}:`, entities[type]); } + return entities; }); } @@ -111,10 +117,12 @@ function analyzeEntitiesInFile (bucketName, fileName) { return document.detectEntities() .then((results) => { const entities = results[0]; + console.log('Entities:'); for (let type in entities) { console.log(`${type}:`, entities[type]); } + return entities; }); } @@ -135,8 +143,10 @@ function analyzeSyntaxOfText (text) { return document.detectSyntax() .then((results) => { const syntax = results[0]; + console.log('Tags:'); syntax.forEach((part) => console.log(part.tag)); + return syntax; }); } @@ -163,59 +173,62 @@ function analyzeSyntaxInFile (bucketName, fileName) { return document.detectSyntax() .then((results) => { const syntax = results[0]; + console.log('Tags:'); syntax.forEach((part) => console.log(part.tag)); + return syntax; }); } // [END language_syntax_file] -// The command-line program -const cli = require(`yargs`); - -const program = module.exports = { - analyzeSentimentOfText, - analyzeSentimentInFile, - analyzeEntitiesOfText, - analyzeEntitiesInFile, - analyzeSyntaxOfText, - analyzeSyntaxInFile, - main: (args) => { - // Run the command-line program - cli.help().strict().parse(args).argv; - } -}; - -cli +require(`yargs`) .demand(1) - .command(`sentimentOfText `, `Detect the sentiment of a block of text.`, {}, (opts) => { - program.analyzeSentimentOfText(opts.text); - }) - .command(`sentimentInFile `, `Detect the sentiment of text in a GCS file.`, {}, (opts) => { - program.analyzeSentimentInFile(opts.bucket, opts.filename); - }) - .command(`entitiesOfText `, `Detect the entities of a block of text.`, {}, (opts) => { - program.analyzeEntitiesOfText(opts.text); - }) - .command(`entitiesInFile `, `Detect the entities of text in a GCS file.`, {}, (opts) => { - program.analyzeEntitiesInFile(opts.bucket, opts.filename); - }) - .command(`syntaxOfText `, `Detect the syntax of a block of text.`, {}, (opts) => { - program.analyzeSyntaxOfText(opts.text); - }) - .command(`syntaxInFile `, `Detect the syntax of text in a GCS file.`, {}, (opts) => { - program.analyzeSyntaxInFile(opts.bucket, opts.filename); - }) - .example(`node $0 sentimentOfText "President Obama is speaking at the White House."`, ``) - .example(`node $0 sentimentInFile my-bucket file.txt`, ``) - .example(`node $0 entitiesOfText "President Obama is speaking at the White House."`, ``) - .example(`node $0 entitiesInFile my-bucket file.txt`, ``) - .example(`node $0 syntaxOfText "President Obama is speaking at the White House."`, ``) - .example(`node $0 syntaxInFile my-bucket file.txt`, ``) + .command( + `sentiment-text `, + `Detects sentiment of a string.`, + {}, + (opts) => analyzeSentimentOfText(opts.text) + ) + .command( + `sentiment-file `, + `Detects sentiment in a file in Google Cloud Storage.`, + {}, + (opts) => analyzeSentimentInFile(opts.bucket, opts.filename) + ) + .command( + `entities-text `, + `Detects entities in a string.`, + {}, + (opts) => analyzeEntitiesOfText(opts.text) + ) + .command( + `entities-file `, + `Detects entities in a file in Google Cloud Storage.`, + {}, + (opts) => analyzeEntitiesInFile(opts.bucket, opts.filename) + ) + .command( + `syntax-text `, + `Detects syntax of a string.`, + {}, + (opts) => analyzeSyntaxOfText(opts.text) + ) + .command( + `syntax-file `, + `Detects syntax in a file in Google Cloud Storage.`, + {}, + (opts) => analyzeSyntaxInFile(opts.bucket, opts.filename) + ) + .example(`node $0 sentiment-text "President Obama is speaking at the White House."`) + .example(`node $0 sentiment-file my-bucket file.txt`, `Detects sentiment in gs://my-bucket/file.txt`) + .example(`node $0 entities-text "President Obama is speaking at the White House."`) + .example(`node $0 entities-file my-bucket file.txt`, `Detects entities in gs://my-bucket/file.txt`) + .example(`node $0 syntax-text "President Obama is speaking at the White House."`) + .example(`node $0 syntax-file my-bucket file.txt`, `Detects syntax in gs://my-bucket/file.txt`) .wrap(120) .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/natural-language/docs`); - -if (module === require.main) { - program.main(process.argv.slice(2)); -} + .epilogue(`For more information, see https://cloud.google.com/natural-language/docs`) + .help() + .strict() + .argv; diff --git a/language/system-test/analyze.test.js b/language/system-test/analyze.test.js index 7030f9a425..dc34430e42 100644 --- a/language/system-test/analyze.test.js +++ b/language/system-test/analyze.test.js @@ -1,15 +1,17 @@ -// Copyright 2016, 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. +/** + * Copyright 2016, 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. + */ 'use strict'; @@ -37,29 +39,29 @@ describe(`language:analyze`, () => { }); it(`should analyze sentiment in text`, () => { - assert.equal(run(`${cmd} sentimentOfText "${text}"`, cwd), `Sentiment: positive.`); + assert.equal(run(`${cmd} sentiment-text "${text}"`, cwd), `Sentiment: positive.`); }); it(`should analyze sentiment in a file`, () => { - assert.equal(run(`${cmd} sentimentInFile ${bucketName} ${fileName}`, cwd), `Sentiment: positive.`); + assert.equal(run(`${cmd} sentiment-file ${bucketName} ${fileName}`, cwd), `Sentiment: positive.`); }); it(`should analyze entities in text`, () => { - const output = run(`${cmd} entitiesOfText "${text}"`, cwd); + const output = run(`${cmd} entities-text "${text}"`, cwd); assert.equal(output.includes(`Entities:`), true); assert.equal(output.includes(`people:`), true); assert.equal(output.includes(`places:`), true); }); it('should analyze entities in a file', () => { - const output = run(`${cmd} entitiesInFile ${bucketName} ${fileName}`, cwd); + const output = run(`${cmd} entities-file ${bucketName} ${fileName}`, cwd); assert.equal(output.includes(`Entities:`), true); assert.equal(output.includes(`people:`), true); assert.equal(output.includes(`places:`), true); }); it(`should analyze syntax in text`, () => { - const output = run(`${cmd} syntaxOfText "${text}"`, cwd); + const output = run(`${cmd} syntax-text "${text}"`, cwd); assert.equal(output.includes(`Tags:`), true); assert.equal(output.includes(`NOUN`), true); assert.equal(output.includes(`VERB`), true); @@ -67,7 +69,7 @@ describe(`language:analyze`, () => { }); it('should analyze syntax in a file', () => { - const output = run(`${cmd} syntaxInFile ${bucketName} ${fileName}`, cwd); + const output = run(`${cmd} syntax-file ${bucketName} ${fileName}`, cwd); assert.equal(output.includes(`Tags:`), true); assert.equal(output.includes(`NOUN`), true); assert.equal(output.includes(`VERB`), true); diff --git a/language/system-test/quickstart.test.js b/language/system-test/quickstart.test.js index 85214485c5..6b02ea0357 100644 --- a/language/system-test/quickstart.test.js +++ b/language/system-test/quickstart.test.js @@ -19,12 +19,9 @@ const proxyquire = require(`proxyquire`).noPreserveCache(); const language = proxyquire(`@google-cloud/language`, {})(); describe(`language:quickstart`, () => { - let languageMock, LanguageMock; - it(`should detect sentiment`, (done) => { const expectedText = `Hello, world!`; - - languageMock = { + const languageMock = { detectSentiment: (_text) => { assert.equal(_text, expectedText); @@ -34,9 +31,9 @@ describe(`language:quickstart`, () => { assert.equal(typeof sentiment, `number`); setTimeout(() => { - assert.equal(console.log.calledTwice, true); - assert.deepEqual(console.log.firstCall.args, [`Text: ${expectedText}`]); - assert.deepEqual(console.log.secondCall.args, [`Sentiment: ${sentiment}`]); + assert.equal(console.log.callCount, 2); + assert.deepEqual(console.log.getCall(0).args, [`Text: ${expectedText}`]); + assert.deepEqual(console.log.getCall(1).args, [`Sentiment: ${sentiment}`]); done(); }, 200); @@ -44,10 +41,9 @@ describe(`language:quickstart`, () => { }); } }; - LanguageMock = sinon.stub().returns(languageMock); proxyquire(`../quickstart`, { - '@google-cloud/language': LanguageMock + '@google-cloud/language': sinon.stub().returns(languageMock) }); }); }); diff --git a/translate/README.md b/translate/README.md index feb5dc35b3..2f2e32de72 100644 --- a/translate/README.md +++ b/translate/README.md @@ -29,32 +29,29 @@ text between thousands of language pairs. View the [documentation][translate_docs] or the [source code][translate_code]. -__Usage:__ `node translate --help` +__Usage:__ `node translate.js --help` ``` Commands: - detect Detect the language of the provided text or texts - list [target] List available translation languages. To return language names in a language other than - English, specify a target language. - translate Translate the provided text or texts to the target language, optionally specifying the - source language. + detect Detects the language of one or more strings. + list [target] Lists available translation languages. To return + language names in a language other thanEnglish, + specify a target language. + translate Translates one or more strings into the target + language. Options: - --apiKey, -k Your Translate API key. Defaults to the value of the TRANSLATE_API_KEY environment variable. [string] - --help Show help [boolean] + --help Show help [boolean] Examples: - node translate detect "Hello world!" Detect the language of "Hello world!". - node translate detect -k your-api-key "Hello world!" Detect the language of "Hello world!" and "Goodbye", - "Goodbye" supplying the API key inline.. - node translate list -k your-api-key List available translation languages with names in - English, supplying the API key inline.. - node translate list es List available translation languages with names in + node translate.js detect "Hello world!" Detects the language of a string. + node translate.js detect "Hello world!" "Goodbye" Detects the languages of multiple strings. + node translate.js list Lists available translation languages with names in + English. + node translate.js list es Lists available translation languages with names in Spanish. - node translate translate ru "Good morning!" Translate "Good morning!" to Russian, auto-detecting the - source language. - node translate translate ru "Good morning!" -f en -k Translate "Good morning!" to Russian from English, - your-api-key supplying the API key inline. + node translate.js translate ru "Good morning!" Translates a string into Russian. + node translate.js translate ru "Good morning!" "Good night!" Translates multiple strings into Russian. For more information, see https://cloud.google.com/translate/docs ``` diff --git a/translate/package.json b/translate/package.json index b7b1f93805..ef36037b91 100644 --- a/translate/package.json +++ b/translate/package.json @@ -5,16 +5,12 @@ "license": "Apache Version 2.0", "author": "Google Inc.", "scripts": { - "test": "mocha -R spec --require intelli-espower-loader ../test/_setup.js test/*.test.js", - "system-test": "mocha -R spec --require intelli-espower-loader ../system-test/_setup.js system-test/*.test.js" + "test": "cd ..; npm run st -- translate/system-test/*.test.js" }, "dependencies": { - "@google-cloud/translate": "^0.4.0", + "@google-cloud/translate": "^0.5.0", "yargs": "^6.4.0" }, - "devDependencies": { - "mocha": "^3.1.2" - }, "engines": { "node": ">=4.3.2" } diff --git a/translate/quickstart.js b/translate/quickstart.js index 2ed38c9ba5..7bb0715b24 100644 --- a/translate/quickstart.js +++ b/translate/quickstart.js @@ -19,12 +19,12 @@ // Imports the Google Cloud client library const Translate = require('@google-cloud/translate'); -// Your Translate API key -const apiKey = 'YOUR_API_KEY'; +// Your Google Cloud Platform project ID +const projectId = 'YOUR_PROJECT_ID'; // Instantiates a client const translateClient = Translate({ - key: apiKey + projectId: projectId }); // The text to translate @@ -33,13 +33,11 @@ const text = 'Hello, world!'; const target = 'ru'; // Translates some text into Russian -translateClient.translate(text, target, (err, translation) => { - if (err) { - console.error(err); - return; - } +translateClient.translate(text, target) + .then((results) => { + const translation = results[0]; - console.log(`Text: ${text}`); - console.log(`Translation: ${translation}`); -}); + console.log(`Text: ${text}`); + console.log(`Translation: ${translation}`); + }); // [END translate_quickstart] diff --git a/translate/system-test/quickstart.test.js b/translate/system-test/quickstart.test.js index 640b1afeb7..d41753da33 100644 --- a/translate/system-test/quickstart.test.js +++ b/translate/system-test/quickstart.test.js @@ -16,39 +16,37 @@ 'use strict'; const proxyquire = require(`proxyquire`).noPreserveCache(); -const translate = proxyquire(`@google-cloud/translate`, {})({ - key: process.env.TRANSLATE_API_KEY -}); -const string = `Hello, world!`; -const expectedTranslation = `Привет мир!`; -const targetLanguage = `ru`; +const translate = proxyquire(`@google-cloud/translate`, {})(); describe(`translate:quickstart`, () => { - let translateMock, TranslateMock; - it(`should translate a string`, (done) => { - translateMock = { - translate: (_string, _targetLanguage, _callback) => { + const string = `Hello, world!`; + const expectedTranslation = `Привет мир!`; + const targetLanguage = `ru`; + const translateMock = { + translate: (_string, _targetLanguage) => { assert.equal(_string, string); assert.equal(_targetLanguage, targetLanguage); - assert.equal(typeof _callback, 'function'); - translate.translate(_string, _targetLanguage, (err, translation, apiResponse) => { - _callback(err, translation, apiResponse); - assert.ifError(err); - assert.equal(translation, expectedTranslation); - assert.notEqual(apiResponse, undefined); - assert.equal(console.log.calledTwice, true); - assert.deepEqual(console.log.firstCall.args, [`Text: ${string}`]); - assert.deepEqual(console.log.secondCall.args, [`Translation: ${expectedTranslation}`]); - done(); - }); + return translate.translate(_string, _targetLanguage) + .then((results) => { + const translation = results[0]; + assert.equal(translation, expectedTranslation); + + setTimeout(() => { + assert.equal(console.log.callCount, 2); + assert.deepEqual(console.log.getCall(0).args, [`Text: ${string}`]); + assert.deepEqual(console.log.getCall(1).args, [`Translation: ${expectedTranslation}`]); + done(); + }, 200); + + return results; + }); } }; - TranslateMock = sinon.stub().returns(translateMock); proxyquire(`../quickstart`, { - '@google-cloud/translate': TranslateMock + '@google-cloud/translate': sinon.stub().returns(translateMock) }); }); }); diff --git a/translate/system-test/translate.test.js b/translate/system-test/translate.test.js index acfb60678d..8d49dd92f3 100644 --- a/translate/system-test/translate.test.js +++ b/translate/system-test/translate.test.js @@ -22,45 +22,57 @@ const run = require(`../../utils`).run; const cwd = path.join(__dirname, `..`); const cmd = `node translate.js`; const text = `Hello world!`; +const text2 = `Goodbye!`; const toLang = `ru`; describe(`translate:translate`, () => { - const translate = Translate({ - key: process.env.TRANSLATE_API_KEY - }); - if (!process.env.TRANSLATE_API_KEY) { - process.stdout.write(`Skipping Translate API tests...\n`); - return; - } + const translate = Translate(); - it(`should detect language`, (done) => { + it(`should detect language of a single string`, () => { const output = run(`${cmd} detect "${text}"`, cwd); - translate.detect(text, (err, result) => { - assert.ifError(err); - assert.equal(output, `Detected: ${JSON.stringify(result)}`); - done(); - }); + return translate.detect(text) + .then((results) => { + const expected = `Detections:\n${text} => ${results[0].language}`; + assert.equal(output, expected); + }); + }); + + it(`should detect language of multiple strings`, () => { + const output = run(`${cmd} detect "${text}" "${text2}"`, cwd); + return translate.detect([text, text2]) + .then((results) => { + const expected = `Detections:\n${text} => ${results[0][0].language}\n${text2} => ${results[0][1].language}`; + assert.equal(output, expected); + }); }); it(`should list languages`, () => { const output = run(`${cmd} list`, cwd); - assert.notEqual(output.indexOf(`Languages:`), -1); - assert.notEqual(output.indexOf(`{ code: 'af', name: 'Afrikaans' }`), -1); + assert.equal(output.includes(`Languages:`), true); + assert.equal(output.includes(`{ code: 'af', name: 'Afrikaans' }`), true); }); it(`should list languages with a target`, () => { const output = run(`${cmd} list es`, cwd); - assert.notEqual(output.indexOf(`Languages:`), -1); - assert.notEqual(output.indexOf(`{ code: 'af', name: 'afrikáans' }`), -1); + assert.equal(output.includes(`Languages:`), true); + assert.equal(output.includes(`{ code: 'af', name: 'afrikáans' }`), true); }); - it(`should translate text`, (done) => { + it(`should translate a single string`, () => { const output = run(`${cmd} translate ${toLang} "${text}"`, cwd); - translate.translate(text, toLang, (err, translation) => { - assert.ifError(err); - assert.notEqual(output.indexOf(`Text: ["${text}"]`), -1); - assert.notEqual(output.indexOf(`Translation: "${translation}"`), -1); - done(); - }); + return translate.translate(text, toLang) + .then((results) => { + const expected = `Translations:\n${text} => (${toLang}) ${results[0]}`; + assert.equal(output, expected); + }); + }); + + it(`should translate multiple strings`, () => { + const output = run(`${cmd} translate ${toLang} "${text}" "${text2}"`, cwd); + return translate.translate([text, text2], toLang) + .then((results) => { + const expected = `Translations:\n${text} => (${toLang}) ${results[0][0]}\n${text2} => (${toLang}) ${results[0][1]}`; + assert.equal(output, expected); + }); }); }); diff --git a/translate/test/quickstart.test.js b/translate/test/quickstart.test.js deleted file mode 100644 index e9c3dd683d..0000000000 --- a/translate/test/quickstart.test.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright 2016, 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. - */ - -'use strict'; - -const proxyquire = require(`proxyquire`).noCallThru(); - -describe(`translate:quickstart`, () => { - let translateMock, TranslateMock; - const error = new Error(`error`); - - before(() => { - translateMock = { - translate: sinon.stub().yields(error) - }; - TranslateMock = sinon.stub().returns(translateMock); - }); - - it(`should handle error`, () => { - proxyquire(`../quickstart`, { - '@google-cloud/translate': TranslateMock - }); - - assert.equal(TranslateMock.calledOnce, true); - assert.deepEqual(TranslateMock.firstCall.args, [{ key: 'YOUR_API_KEY' }]); - assert.equal(translateMock.translate.calledOnce, true); - assert.deepEqual(translateMock.translate.firstCall.args.slice(0, -1), ['Hello, world!', 'ru']); - assert.equal(console.error.calledOnce, true); - assert.deepEqual(console.error.firstCall.args, [error]); - }); -}); diff --git a/translate/test/translate.test.js b/translate/test/translate.test.js deleted file mode 100644 index 91b296c3c0..0000000000 --- a/translate/test/translate.test.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright 2016, 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. - */ - -'use strict'; - -const proxyquire = require(`proxyquire`).noCallThru(); - -describe(`translate:translate`, () => { - it(`should handle errors`, () => { - const error = new Error(`error`); - const text = `Hello world!`; - const toLang = `ru`; - const callback = sinon.spy(); - const translateMock = { - getLanguages: sinon.stub().yields(error), - detect: sinon.stub().yields(error), - translate: sinon.stub().yields(error) - }; - const TranslateMock = sinon.stub().returns(translateMock); - const program = proxyquire(`../translate`, { - '@google-cloud/translate': TranslateMock - }); - - program.detectLanguage(text, callback); - program.listLanguages(callback); - program.listLanguagesWithTarget(toLang, callback); - program.translateText(text, toLang, callback); - - assert.equal(callback.callCount, 4); - assert.equal(callback.alwaysCalledWithExactly(error), true); - }); -}); diff --git a/translate/translate.js b/translate/translate.js index bc3e108702..1f7b316654 100644 --- a/translate/translate.js +++ b/translate/translate.js @@ -18,156 +18,130 @@ const Translate = require('@google-cloud/translate'); // [START translate_detect_language] -function detectLanguage (input, callback) { +function detectLanguage (input) { // Instantiates a client - const translate = Translate({ - // The Translate API uses an API key for authentication. This sample looks - // for the key in an environment variable. - key: process.env.TRANSLATE_API_KEY - }); + const translate = Translate(); // Detects the language. "input" can be a string for detecting the language of // a single piece of text, or an array of strings for detecting the languages // of multiple texts. - translate.detect(input, (err, result) => { - if (err) { - callback(err); - return; - } + return translate.detect(input) + .then((results) => { + let detections = results[0]; + + if (!Array.isArray(detections)) { + detections = [detections]; + } + + console.log('Detections:'); + detections.forEach((detection) => { + console.log(`${detection.input} => ${detection.language}`); + }); - console.log('Detected: %j', result); - callback(); - }); + return detections; + }); } // [END translate_detect_language] // [START translate_list_codes] -function listLanguages (callback) { +function listLanguages () { // Instantiates a client - const translate = Translate({ - // The Translate API uses an API key for authentication. This sample looks - // for the key in an environment variable. - key: process.env.TRANSLATE_API_KEY - }); + const translate = Translate(); // Lists available translation language with their names in English (the default). - translate.getLanguages((err, languages) => { - if (err) { - callback(err); - return; - } + return translate.getLanguages() + .then((results) => { + const languages = results[0]; + + console.log('Languages:'); + languages.forEach((language) => console.log(language)); - console.log('Languages:'); - languages.forEach((language) => console.log(language)); - callback(); - }); + return languages; + }); } // [END translate_list_codes] // [START translate_list_language_names] -function listLanguagesWithTarget (target, callback) { +function listLanguagesWithTarget (target) { // Instantiates a client - const translate = Translate({ - // The Translate API uses an API key for authentication. This sample looks - // for the key in an environment variable. - key: process.env.TRANSLATE_API_KEY - }); - - // Lists available translation language with their names in a target language - translate.getLanguages(target, (err, languages) => { - if (err) { - callback(err); - return; - } + const translate = Translate(); + + // Lists available translation language with their names in a target language, + // e.g. "ru" + return translate.getLanguages(target) + .then((results) => { + const languages = results[0]; + + console.log('Languages:'); + languages.forEach((language) => console.log(language)); - console.log('Languages:'); - languages.forEach((language) => console.log(language)); - callback(); - }); + return languages; + }); } // [END translate_list_language_names] // [START translate_translate_text] -function translateText (input, target, callback) { +function translateText (input, target) { + if (!Array.isArray(input)) { + input = [input]; + } + // Instantiates a client - const translate = Translate({ - // The Translate API uses an API key for authentication. This sample looks - // for the key in an environment variable. - key: process.env.TRANSLATE_API_KEY - }); + const translate = Translate(); // Translates the text into the target language. "input" can be a string for // translating a single piece of text, or an array of strings for translating // multiple texts. - translate.translate(input, target, (err, translation) => { - if (err) { - callback(err); - return; - } - - console.log('Text: %j', input); - console.log('Translation: %j', translation); - callback(); - }); + return translate.translate(input, target) + .then((results) => { + let translations = results[0]; + translations = Array.isArray(translations) ? translations : [translations]; + + console.log('Translations:'); + translations.forEach((translation, i) => { + console.log(`${input[i]} => (${target}) ${translation}`); + }); + + return translations; + }); } // [END translate_translate_text] -// The command-line program -const cli = require(`yargs`); -const noop = require(`../utils`).noop; - -const program = module.exports = { - detectLanguage: detectLanguage, - listLanguages: listLanguages, - listLanguagesWithTarget: listLanguagesWithTarget, - translateText: translateText, - main: (args) => { - // Run the command-line program - cli.help().strict().parse(args).argv; - } -}; - -cli +require(`yargs`) .demand(1) - .command(`detect `, `Detects the language of the provided text or texts`, {}, (opts) => { - if (!process.env.TRANSLATE_API_KEY) { - process.env.TRANSLATE_API_KEY = opts.apiKey; - } - program.detectLanguage(opts.input, noop); - }) - .command(`list [target]`, `Lists available translation languages. To return language names in a language other than English, specify a target language.`, {}, (opts) => { - if (!process.env.TRANSLATE_API_KEY) { - process.env.TRANSLATE_API_KEY = opts.apiKey; + .command( + `detect `, + `Detects the language of one or more strings.`, + {}, + (opts) => detectLanguage(opts.input) + ) + .command( + `list [target]`, + `Lists available translation languages. To return language names in a language other than English, specify a target language.`, + {}, + (opts) => { + if (opts.target) { + listLanguagesWithTarget(opts.target); + } else { + listLanguages(); + } } - if (opts.target) { - program.listLanguagesWithTarget(opts.target, noop); - } else { - program.listLanguages(noop); - } - }) - .command(`translate `, `Translates the provided text or texts to the target language.`, {}, (opts) => { - if (!process.env.TRANSLATE_API_KEY) { - process.env.TRANSLATE_API_KEY = opts.apiKey; - } - program.translateText(opts.input, opts.toLang, noop); - }) - .option(`apiKey`, { - alias: `k`, - global: true, - requiresArg: true, - default: process.env.TRANSLATE_API_KEY, - type: `string`, - description: `Your Translate API key. Defaults to the value of the TRANSLATE_API_KEY environment variable.` - }) - .example(`node $0 detect "Hello world!"`, `Detects the language of "Hello world!".`) - .example(`node $0 detect -k YOUR_API_KEY "Hello world!" "Goodbye"`, `Detects the language of "Hello world!" and "Goodbye", supplying the API key inline.`) - .example(`node $0 list -k YOUR_API_KEY`, `Lists available translation languages with names in English, supplying the API key inline.`) + ) + .command( + `translate `, + `Translates one or more strings into the target language.`, + {}, + (opts) => translateText(opts.input, opts.toLang) + ) + .example(`node $0 detect "Hello world!"`, `Detects the language of a string.`) + .example(`node $0 detect "Hello world!" "Goodbye"`, `Detects the languages of multiple strings.`) + .example(`node $0 list`, `Lists available translation languages with names in English.`) .example(`node $0 list es`, `Lists available translation languages with names in Spanish.`) - .example(`node $0 translate ru "Good morning!"`, `Translates "Good morning!" to Russian, auto-detecting the source language.`) + .example(`node $0 translate ru "Good morning!"`, `Translates a string into Russian.`) + .example(`node $0 translate ru "Good morning!" "Good night!"`, `Translates multiple strings into Russian.`) .wrap(120) .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/translate/docs`); - -if (module === require.main) { - program.main(process.argv.slice(2)); -} + .epilogue(`For more information, see https://cloud.google.com/translate/docs`) + .help() + .strict() + .argv;