diff --git a/README.md b/README.md index 0435e0ddd2..96e1fe4361 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ on Google Cloud Platform. * [Google Cloud Prediction API](#google-cloud-prediction-api) * [Google Cloud Speech API (Beta)](#google-cloud-speech-api-beta) * [Google Translate API](#google-translate-api) + * [Google Video Intelligence API](#google-video-intelligence-api) * [Google Cloud Vision API](#google-cloud-vision-api) * [**Management Tools**](#management-tools) * [Stackdriver Debugger](#stackdriver-debugger) @@ -236,7 +237,7 @@ consistent and scalable relational database service. View the [Cloud Spanner Node.js samples][spanner_samples]. [spanner_docs]: https://cloud.google.com/spanner/docs/ -[spanner_samples]: spanner +[spanner_samples]: https://github.com/googleapis/nodejs-spanner/tree/master/samples #### Google Cloud Datastore @@ -332,7 +333,17 @@ text between thousands of language pairs. View the [Translate API Node.js samples][translate_samples]. [translate_docs]: https://cloud.google.com/translate/docs/ -[translate_samples]: translate +[translate_samples]: https://github.com/googleapis/nodejs-translate/tree/master/samples + +#### Google Cloud Video Intelligence API + +The [Cloud Video Intelligence API][video_intelligence_docs] allows developers to +use Google video analysis technology as part of their applications. + +View the [Cloud Video Intelligence API Node.js samples][video_intelligence_samples]. + +[video_intelligence_docs]: https://cloud.google.com/video-intelligence/docs/ +[video_intelligence_samples]: https://github.com/googleapis/nodejs-video-intelligence/tree/master/samples #### Google Cloud Vision API diff --git a/circle.yml b/circle.yml index e04fddfc2e..bdd2194d09 100644 --- a/circle.yml +++ b/circle.yml @@ -103,11 +103,7 @@ deployment: - node scripts/build "prediction" - node scripts/build "pubsub" - node scripts/build "resource" - - node scripts/build "spanner" - node scripts/build "speech" - node scripts/build "storage-transfer" - node scripts/build "trace" - - node scripts/build "translate" - # TODO: This build times out. Does video need more than 10 minutes? - # - node scripts/build "video" - node scripts/build "vision" diff --git a/spanner/README.md b/spanner/README.md index 596369ff6a..b3dfac7bf8 100644 --- a/spanner/README.md +++ b/spanner/README.md @@ -1,141 +1,5 @@ -Google Cloud Platform logo - -# Cloud Spanner: Node.js Samples - -[![Build](https://storage.googleapis.com/.svg)]() - -[Cloud Spanner](https://cloud.google.com/spanner/docs/) is a fully managed, mission-critical, relational database service that offers transactional consistency at global scale, schemas, SQL (ANSI 2011 with extensions), and automatic, synchronous replication for high availability. - -## Table of Contents - -* [Setup](#setup) -* [Samples](#samples) - * [Schema](#schema) - * [CRUD](#crud) - * [Indexing](#indexing) - * [Transactions](#transactions) -* [Running the tests](#running-the-tests) - -## Setup - - -## Samples - -### Schema - -View the [documentation][schema_0_docs] or the [source code][schema_0_code]. - -__Usage:__ `node schema.js --help` - -``` -Commands: - createDatabase Creates an example database with two tables in a Cloud Spanner instance. - addColumn Adds an example MarketingBudget column to an example Cloud Spanner - table. - queryNewColumn Executes a read-only SQL query against an example Cloud Spanner table - with an additional column (MarketingBudget) added by addColumn. - -Options: - --help Show help [boolean] - -Examples: - node schema.js createDatabase "my-instance" "my-database" - node schema.js addColumn "my-instance" "my-database" - node schema.js queryNewColumn "my-instance" "my-database" - -For more information, see https://cloud.google.com/spanner/docs -``` - -[schema_0_docs]: https://cloud.google.com/spanner/docs -[schema_0_code]: schema.js - -### CRUD - -View the [documentation][crud_1_docs] or the [source code][crud_1_code]. - -__Usage:__ `node crud.js --help` - -``` -Commands: - update Modifies existing rows of data in an example Cloud Spanner table. - query Executes a read-only SQL query against an example Cloud Spanner table. - insert Inserts new rows of data into an example Cloud Spanner table. - read Reads data in an example Cloud Spanner table. - read-stale Reads data in an example Cloud Spanner table. - -Options: - --help Show help [boolean] - -Examples: - node crud.js update "my-instance" "my-database" - node crud.js query "my-instance" "my-database" - node crud.js insert "my-instance" "my-database" - node crud.js read "my-instance" "my-database" - -For more information, see https://cloud.google.com/spanner/docs -``` - -[crud_1_docs]: https://cloud.google.com/spanner/docs -[crud_1_code]: crud.js - -### Indexing - -View the [documentation][indexing_2_docs] or the [source code][indexing_2_code]. - -__Usage:__ `node indexing.js --help` - -``` -Commands: - createIndex Creates a new index in an example Cloud Spanner table. - createStoringIndex Creates a new value-storing index in an example Cloud Spanner table. - queryIndex Executes a read-only SQL query against an example Cloud Spanner - table using an existing index. - Returns results with titles between a start title (default: - 'Ardvark') and an end title (default: 'Goo'). - readIndex Reads data from an example Cloud Spanner table using an existing - index. - readStoringIndex Reads data from an example Cloud Spanner table using an existing - storing index. - -Options: - --help Show help [boolean] - -Examples: - node indexing.js createIndex "my-instance" "my-database" - node indexing.js createStoringIndex "my-instance" "my-database" - node indexing.js queryIndex "my-instance" "my-database" - node indexing.js readIndex "my-instance" "my-database" - node indexing.js readStoringIndex "my-instance" "my-database" - -For more information, see https://cloud.google.com/spanner/docs -``` - -[indexing_2_docs]: https://cloud.google.com/spanner/docs -[indexing_2_code]: indexing.js - -### Transactions - -View the [documentation][transaction_3_docs] or the [source code][transaction_3_code]. - -__Usage:__ `node transaction.js --help` - -``` -Commands: - readOnly Execute a read-only transaction on an example Cloud Spanner table. - readWrite Execute a read-write transaction on an example Cloud Spanner table. - -Options: - --help Show help [boolean] - -Examples: - node transaction.js readOnly "my-instance" "my-database" - node transaction.js readWrite "my-instance" "my-database" - -For more information, see https://cloud.google.com/spanner/docs -``` - -[transaction_3_docs]: https://cloud.google.com/spanner/docs -[transaction_3_code]: transaction.js - -## Running the tests +Samples for the [Google Cloud Spanner Node.js Client][client] have moved to +[github.com/googleapis/nodejs-spanner/tree/master/samples/][samples]. +[client]: https://github.com/googleapis/nodejs-spanner +[samples]: https://github.com/googleapis/nodejs-spanner/tree/master/samples diff --git a/spanner/crud.js b/spanner/crud.js deleted file mode 100644 index 696c6cae14..0000000000 --- a/spanner/crud.js +++ /dev/null @@ -1,256 +0,0 @@ -/** - * 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. - */ - -'use strict'; - -function updateData (instanceId, databaseId) { - // [START update_data] - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Gets a reference to a Cloud Spanner instance and database - const instance = spanner.instance(instanceId); - const database = instance.database(databaseId); - - // Update a row in the Albums table - // Note: Cloud Spanner interprets Node.js numbers as FLOAT64s, so they - // must be converted to strings before being inserted as INT64s - const albumsTable = database.table('Albums'); - - albumsTable.update([ - { SingerId: '1', AlbumId: '1', MarketingBudget: '100000' }, - { SingerId: '2', AlbumId: '2', MarketingBudget: '500000' } - ]) - .then(() => { - console.log('Updated data.'); - }); - // [END update_data] -} - -function insertData (instanceId, databaseId) { - // [START insert_data] - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Gets a reference to a Spanner instance and database - const instance = spanner.instance(instanceId); - const database = instance.database(databaseId); - - // Instantiate Spanner table objects - const singersTable = database.table('Singers'); - const albumsTable = database.table('Albums'); - - // Inserts rows into the Singers table - // Note: Cloud Spanner interprets Node.js numbers as FLOAT64s, so - // they must be converted to strings before being inserted as INT64s - singersTable.insert([ - { SingerId: '1', FirstName: 'Marc', LastName: 'Richards' }, - { SingerId: '2', FirstName: 'Catalina', LastName: 'Smith' }, - { SingerId: '3', FirstName: 'Alice', LastName: 'Trentor' }, - { SingerId: '4', FirstName: 'Lea', LastName: 'Martin' }, - { SingerId: '5', FirstName: 'David', LastName: 'Lomond' } - ]) - .then(() => { - // Inserts rows into the Albums table - albumsTable.insert([ - { SingerId: '1', AlbumId: '1', AlbumTitle: 'Go, Go, Go' }, - { SingerId: '1', AlbumId: '2', AlbumTitle: 'Total Junk' }, - { SingerId: '2', AlbumId: '1', AlbumTitle: 'Green' }, - { SingerId: '2', AlbumId: '2', AlbumTitle: 'Forever Hold your Peace' }, - { SingerId: '2', AlbumId: '3', AlbumTitle: 'Terrified' } - ]); - }) - .then(() => { - console.log('Inserted data.'); - }); - // [END insert_data] -} - -function queryData (instanceId, databaseId) { - // [START query_data] - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Gets a reference to a Cloud Spanner instance and database - const instance = spanner.instance(instanceId); - const database = instance.database(databaseId); - - const query = { - sql: 'SELECT SingerId, AlbumId, AlbumTitle FROM Albums' - }; - - // Queries rows from the Albums table - database.run(query) - .then((results) => { - const rows = results[0]; - - rows.forEach((row) => { - const json = row.toJSON(); - console.log(`SingerId: ${json.SingerId.value}, AlbumId: ${json.AlbumId.value}, AlbumTitle: ${json.AlbumTitle}`); - }); - }); - // [END query_data] -} - -function readData (instanceId, databaseId) { - // [START read_data] - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Gets a reference to a Cloud Spanner instance and database - const instance = spanner.instance(instanceId); - const database = instance.database(databaseId); - - // Reads rows from the Albums table - const albumsTable = database.table('Albums'); - - const query = { - columns: ['SingerId', 'AlbumId', 'AlbumTitle'], - keySet: { - all: true - } - }; - - albumsTable.read(query) - .then((results) => { - const rows = results[0]; - - rows.forEach((row) => { - const json = row.toJSON(); - console.log(`SingerId: ${json.SingerId.value}, AlbumId: ${json.AlbumId.value}, AlbumTitle: ${json.AlbumTitle}`); - }); - }); - // [END read_data] -} - -function readStaleData (instanceId, databaseId) { - // [START read_stale_data] - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Gets a reference to a Cloud Spanner instance and database - const instance = spanner.instance(instanceId); - const database = instance.database(databaseId); - - // Reads rows from the Albums table - const albumsTable = database.table('Albums'); - - const query = { - columns: ['SingerId', 'AlbumId', 'AlbumTitle', 'MarketingBudget'], - keySet: { - all: true - } - }; - - const options = { - // Guarantees that all writes committed more than 10 seconds ago are visible - exactStaleness: 10 - }; - - albumsTable.read(query, options) - .then((results) => { - const rows = results[0]; - - rows.forEach((row) => { - const json = row.toJSON(); - const id = json.SingerId.value; - const album = json.AlbumId.value; - const title = json.AlbumTitle; - const budget = json.MarketingBudget ? json.MarketingBudget.value : ''; - console.log(`SingerId: ${id}, AlbumId: ${album}, AlbumTitle: ${title}, MarketingBudget: ${budget}`); - }); - }); - // [END read_stale_data] -} - -const cli = require(`yargs`) - .demand(1) - .command( - `update `, - `Modifies existing rows of data in an example Cloud Spanner table.`, - {}, - (opts) => updateData(opts.instanceName, opts.databaseName) - ) - .command( - `query `, - `Executes a read-only SQL query against an example Cloud Spanner table.`, - {}, - (opts) => queryData(opts.instanceName, opts.databaseName) - ) - .command( - `insert `, - `Inserts new rows of data into an example Cloud Spanner table.`, - {}, - (opts) => insertData(opts.instanceName, opts.databaseName) - ) - .command( - `read `, - `Reads data in an example Cloud Spanner table.`, - {}, - (opts) => readData(opts.instanceName, opts.databaseName) - ) - .command( - `read-stale `, - `Reads stale data in an example Cloud Spanner table.`, - {}, - (opts) => readStaleData(opts.instanceName, opts.databaseName) - ) - .example(`node $0 update "my-instance" "my-database"`) - .example(`node $0 query "my-instance" "my-database"`) - .example(`node $0 insert "my-instance" "my-database"`) - .example(`node $0 read "my-instance" "my-database"`) - .example(`node $0 read-stale "my-instance" "my-database"`) - .wrap(120) - .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/spanner/docs`); - -if (module === require.main) { - cli.help().strict().argv; // eslint-disable-line -} diff --git a/spanner/indexing.js b/spanner/indexing.js deleted file mode 100644 index a9b23f4397..0000000000 --- a/spanner/indexing.js +++ /dev/null @@ -1,273 +0,0 @@ -/** - * 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. - */ - -'use strict'; - -function createIndex (instanceId, databaseId) { - // [START create_index] - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Gets a reference to a Cloud Spanner instance and database - const instance = spanner.instance(instanceId); - const database = instance.database(databaseId); - - const request = [ - 'CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)' - ]; - - // Creates a new index in the database - database.updateSchema(request) - .then((results) => { - const operation = results[0]; - - console.log('Waiting for operation to complete...'); - return operation.promise(); - }) - .then(() => { - console.log('Added the AlbumsByAlbumTitle index.'); - }); - // [END create_index] -} - -function createStoringIndex (instanceId, databaseId) { - // [START create_storing_index] - // "Storing" indexes store copies of the columns they index - // This speeds up queries, but takes more space compared to normal indexes - // See the link below for more information: - // https://cloud.google.com/spanner/docs/secondary-indexes#storing_clause - - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Gets a reference to a Cloud Spanner instance and database - const instance = spanner.instance(instanceId); - const database = instance.database(databaseId); - - const request = [ - 'CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) STORING (MarketingBudget)' - ]; - - // Creates a new index in the database - database.updateSchema(request) - .then((results) => { - const operation = results[0]; - - console.log('Waiting for operation to complete...'); - return operation.promise(); - }) - .then(() => { - console.log('Added the AlbumsByAlbumTitle2 index.'); - }); - // [END create_storing_index] -} - -function queryDataWithIndex (instanceId, databaseId, startTitle, endTitle) { - // [START query_data_with_index] - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Uncomment these lines to specify the start and end title(s) - // const startTitle = 'Ardvark'; - // const endTitle = 'Goo'; - - // Gets a reference to a Cloud Spanner instance and database - const instance = spanner.instance(instanceId); - const database = instance.database(databaseId); - - const query = { - sql: `SELECT AlbumId, AlbumTitle, MarketingBudget - FROM Albums@{FORCE_INDEX=AlbumsByAlbumTitle} - WHERE AlbumTitle >= @startTitle AND AlbumTitle <= @endTitle`, - params: { - startTitle: startTitle, - endTitle: endTitle - } - }; - - // Queries rows from the Albums table - database.run(query) - .then((results) => { - const rows = results[0]; - - rows.forEach((row) => { - const json = row.toJSON(); - const marketingBudget = json.MarketingBudget ? json.MarketingBudget.value : null; // This value is nullable - console.log(`AlbumId: ${json.AlbumId.value}, AlbumTitle: ${json.AlbumTitle}, MarketingBudget: ${marketingBudget}`); - }); - }); - // [END query_data_with_index] -} - -function readDataWithIndex (instanceId, databaseId) { - // [START read_data_with_index] - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Gets a reference to a Cloud Spanner instance and database - const instance = spanner.instance(instanceId); - const database = instance.database(databaseId); - - const albumsTable = database.table('Albums'); - - const query = { - columns: ['AlbumId', 'AlbumTitle'], - keySet: { - all: true - }, - index: 'AlbumsByAlbumTitle' - }; - - // Reads the Albums table using an index - albumsTable.read(query) - .then((results) => { - const rows = results[0]; - - rows.forEach((row) => { - const json = row.toJSON(); - console.log(`AlbumId: ${json.AlbumId.value}, AlbumTitle: ${json.AlbumTitle}`); - }); - }); - // [END read_data_with_index] -} - -function readDataWithStoringIndex (instanceId, databaseId) { - // [START read_data_with_storing_index] - // "Storing" indexes store copies of the columns they index - // This speeds up queries, but takes more space compared to normal indexes - // See the link below for more information: - // https://cloud.google.com/spanner/docs/secondary-indexes#storing_clause - - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Gets a reference to a Cloud Spanner instance and database - const instance = spanner.instance(instanceId); - const database = instance.database(databaseId); - - const albumsTable = database.table('Albums'); - - const query = { - columns: ['AlbumId', 'AlbumTitle', 'MarketingBudget'], - keySet: { - all: true - }, - index: 'AlbumsByAlbumTitle2' - }; - - // Reads the Albums table using a storing index - albumsTable.read(query) - .then((results) => { - const rows = results[0]; - - rows.forEach((row) => { - const json = row.toJSON(); - console.log(`AlbumId: ${json.AlbumId.value}, AlbumTitle: ${json.AlbumTitle}, MarketingBudget: ${json.MarketingBudget.value}`); - }); - }); - // [END read_data_with_storing_index] -} - -const cli = require(`yargs`) - .demand(1) - .command( - `createIndex `, - `Creates a new index in an example Cloud Spanner table.`, - {}, - (opts) => createIndex(opts.instanceName, opts.databaseName) - ) - .command( - `createStoringIndex `, - `Creates a new value-storing index in an example Cloud Spanner table.`, - {}, - (opts) => createStoringIndex(opts.instanceName, opts.databaseName) - ) - .command( - `queryIndex `, - `Executes a read-only SQL query against an example Cloud Spanner table using an existing index. - Returns results with titles between a start title (default: 'Ardvark') and an end title (default: 'Goo').`, - { - startTitle: { - type: 'string', - alias: 's', - default: 'Ardvark' - }, - endTitle: { - type: 'string', - alias: 'e', - default: 'Goo' - } - }, - (opts) => queryDataWithIndex(opts.instanceName, opts.databaseName, opts.startTitle, opts.endTitle) - ) - .command( - `readIndex `, - `Reads data from an example Cloud Spanner table using an existing index.`, - {}, - (opts) => readDataWithIndex(opts.instanceName, opts.databaseName) - ) - .command( - `readStoringIndex `, - `Reads data from an example Cloud Spanner table using an existing storing index.`, - {}, - (opts) => readDataWithStoringIndex(opts.instanceName, opts.databaseName) - ) - .example(`node $0 createIndex "my-instance" "my-database"`) - .example(`node $0 createStoringIndex "my-instance" "my-database"`) - .example(`node $0 queryIndex "my-instance" "my-database"`) - .example(`node $0 readIndex "my-instance" "my-database"`) - .example(`node $0 readStoringIndex "my-instance" "my-database"`) - .wrap(120) - .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/spanner/docs`); - -if (module === require.main) { - cli.help().strict().argv; // eslint-disable-line -} diff --git a/spanner/package.json b/spanner/package.json deleted file mode 100644 index cc2c3db35f..0000000000 --- a/spanner/package.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "name": "nodejs-docs-samples-spanner", - "version": "0.0.1", - "private": true, - "license": "Apache-2.0", - "author": "Google Inc.", - "repository": { - "type": "git", - "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git" - }, - "engines": { - "node": ">=4.3.2" - }, - "scripts": { - "lint": "samples lint", - "pretest": "npm run lint", - "test": "samples test run --cmd ava -- -T 5m --verbose system-test/*.test.js" - }, - "dependencies": { - "@google-cloud/spanner": "0.7.1", - "yargs": "8.0.2" - }, - "devDependencies": { - "@google-cloud/nodejs-repo-tools": "1.4.17", - "ava": "0.22.0", - "proxyquire": "1.8.0", - "sinon": "3.2.1" - }, - "cloud-repo-tools": { - "requiresKeyFile": true, - "requiresProjectId": true, - "product": "spanner", - "samples": [ - { - "id": "schema", - "name": "Schema", - "file": "schema.js", - "docs_link": "https://cloud.google.com/spanner/docs", - "usage": "node schema.js --help" - }, - { - "id": "crud", - "name": "CRUD", - "file": "crud.js", - "docs_link": "https://cloud.google.com/spanner/docs", - "usage": "node crud.js --help" - }, - { - "id": "indexing", - "name": "Indexing", - "file": "indexing.js", - "docs_link": "https://cloud.google.com/spanner/docs", - "usage": "node indexing.js --help" - }, - { - "id": "transaction", - "name": "Transactions", - "file": "transaction.js", - "docs_link": "https://cloud.google.com/spanner/docs", - "usage": "node transaction.js --help" - } - ] - } -} diff --git a/spanner/quickstart.js b/spanner/quickstart.js deleted file mode 100644 index 5e5d744267..0000000000 --- a/spanner/quickstart.js +++ /dev/null @@ -1,52 +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'; - -// [START spanner_quickstart] -// Imports the Google Cloud client library -const Spanner = require('@google-cloud/spanner'); - -// Your Google Cloud Platform project ID -const projectId = 'YOUR_PROJECT_ID'; - -// Instantiates a client -const spanner = Spanner({ - projectId: projectId -}); - -// Your Cloud Spanner instance ID -const instanceId = 'my-instance'; - -// Your Cloud Spanner database ID -const databaseId = 'my-database'; - -// Gets a reference to a Cloud Spanner instance and database -const instance = spanner.instance(instanceId); -const database = instance.database(databaseId); - -// The query to execute -const query = { - sql: 'SELECT 1' -}; - -// Execute a simple SQL statement -database.run(query) - .then((results) => { - const rows = results[0]; - - rows.forEach((row) => console.log(row)); - }); -// [END spanner_quickstart] diff --git a/spanner/schema.js b/spanner/schema.js deleted file mode 100644 index 767d23d14b..0000000000 --- a/spanner/schema.js +++ /dev/null @@ -1,169 +0,0 @@ -/** - * 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. - */ - -'use strict'; - -function createDatabase (instanceId, databaseId) { - // [START create_database] - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Gets a reference to a Cloud Spanner instance - const instance = spanner.instance(instanceId); - - // Note: Cloud Spanner interprets Node.js numbers as FLOAT64s, so they - // must be converted to strings before being inserted as INT64s - const request = { - schema: [ - `CREATE TABLE Singers ( - SingerId INT64 NOT NULL, - FirstName STRING(1024), - LastName STRING(1024), - SingerInfo BYTES(MAX) - ) PRIMARY KEY (SingerId)`, - `CREATE TABLE Albums ( - SingerId INT64 NOT NULL, - AlbumId INT64 NOT NULL, - AlbumTitle STRING(MAX) - ) PRIMARY KEY (SingerId, AlbumId), - INTERLEAVE IN PARENT Singers ON DELETE CASCADE` - ] - }; - - // Creates a database - instance.createDatabase(databaseId, request) - .then((results) => { - const database = results[0]; - const operation = results[1]; - - console.log(`Waiting for operation on ${database.id} to complete...`); - return operation.promise(); - }) - .then(() => { - console.log(`Created database ${databaseId} on instance ${instanceId}.`); - }); - // [END create_database] -} - -function addColumn (instanceId, databaseId) { - // [START add_column] - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Gets a reference to a Cloud Spanner instance and database - const instance = spanner.instance(instanceId); - const database = instance.database(databaseId); - - const request = [ - 'ALTER TABLE Albums ADD COLUMN MarketingBudget INT64' - ]; - - // Creates a new index in the database - database.updateSchema(request) - .then((results) => { - const operation = results[0]; - - console.log('Waiting for operation to complete...'); - return operation.promise(); - }) - .then(() => { - console.log('Added the MarketingBudget column.'); - }); - // [END add_column] -} - -function queryDataWithNewColumn (instanceId, databaseId) { - // [START query_data_with_new_column] - // This sample uses the `MarketingBudget` column. You can add the column - // by running the `add_column` sample or by running this DDL statement against - // your database: - // ALTER TABLE Albums ADD COLUMN MarketingBudget INT64 - - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Gets a reference to a Cloud Spanner instance and database - const instance = spanner.instance(instanceId); - const database = instance.database(databaseId); - - const query = { - sql: `SELECT SingerId, AlbumId, MarketingBudget FROM Albums` - }; - - // Queries rows from the Albums table - database.run(query) - .then((results) => { - const rows = results[0]; - - rows.forEach((row) => { - const json = row.toJSON(); - - console.log(`SingerId: ${json.SingerId.value}, AlbumId: ${json.AlbumId.value}, MarketingBudget: ${json.MarketingBudget ? json.MarketingBudget.value : null}`); - }); - }); - // [END query_data_with_new_column] -} - -const cli = require(`yargs`) - .demand(1) - .command( - `createDatabase `, - `Creates an example database with two tables in a Cloud Spanner instance.`, - {}, - (opts) => createDatabase(opts.instanceName, opts.databaseName) - ) - .command( - `addColumn `, - `Adds an example MarketingBudget column to an example Cloud Spanner table.`, - {}, - (opts) => addColumn(opts.instanceName, opts.databaseName) - ) - .command( - `queryNewColumn `, - `Executes a read-only SQL query against an example Cloud Spanner table with an additional column (MarketingBudget) added by addColumn.`, - {}, - (opts) => queryDataWithNewColumn(opts.instanceName, opts.databaseName) - ) - .example(`node $0 createDatabase "my-instance" "my-database"`) - .example(`node $0 addColumn "my-instance" "my-database"`) - .example(`node $0 queryNewColumn "my-instance" "my-database"`) - .wrap(120) - .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/spanner/docs`); - -if (module === require.main) { - cli.help().strict().argv; // eslint-disable-line -} diff --git a/spanner/system-test/quickstart.test.js b/spanner/system-test/quickstart.test.js deleted file mode 100644 index a5af9f72d5..0000000000 --- a/spanner/system-test/quickstart.test.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * 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. - */ - -'use strict'; - -const proxyquire = require(`proxyquire`).noPreserveCache(); -const sinon = require(`sinon`); -const test = require(`ava`); -const tools = require(`@google-cloud/nodejs-repo-tools`); - -test.before(tools.stubConsole); -test.after.always(tools.restoreConsole); - -test.cb(`should query a table`, (t) => { - const databaseMock = { - run: (_query) => { - t.deepEqual(_query, { - sql: `SELECT 1` - }); - setTimeout(() => { - try { - t.deepEqual(console.log.getCall(0).args, [`test`]); - t.end(); - } catch (err) { - t.end(err); - } - }, 200); - return Promise.resolve([['test']]); - } - }; - const instanceMock = { - database: sinon.stub().returns(databaseMock) - }; - const spannerMock = { - instance: sinon.stub().returns(instanceMock) - }; - - proxyquire(`../quickstart`, { - '@google-cloud/spanner': sinon.stub().returns(spannerMock) - }); - - t.deepEqual(spannerMock.instance.getCall(0).args, [`my-instance`]); - t.deepEqual(instanceMock.database.getCall(0).args, [`my-database`]); -}); diff --git a/spanner/system-test/spanner.test.js b/spanner/system-test/spanner.test.js deleted file mode 100644 index ae505e2d37..0000000000 --- a/spanner/system-test/spanner.test.js +++ /dev/null @@ -1,185 +0,0 @@ -/** - * 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. - */ - -'use strict'; - -const path = require(`path`); -const spanner = require(`@google-cloud/spanner`)(); -const test = require(`ava`); -const tools = require(`@google-cloud/nodejs-repo-tools`); - -const crudCmd = `node crud.js`; -const schemaCmd = `node schema.js`; -const indexingCmd = `node indexing.js`; -const transactionCmd = `node transaction.js`; - -const cwd = path.join(__dirname, `..`); - -const INSTANCE_ID = `test-instance`; -const DATABASE_ID = `test-database-${Date.now()}`; - -test.before(tools.checkCredentials); -test.before(async (t) => { - const instance = spanner.instance(INSTANCE_ID); - const database = instance.database(DATABASE_ID); - try { - await database.delete(); - } catch (err) { - // Ignore error - } -}); - -test.after.always(async (t) => { - const instance = spanner.instance(INSTANCE_ID); - const database = instance.database(DATABASE_ID); - try { - await database.delete(); - } catch (err) { - // Ignore error - } -}); - -// create_database -test.serial(`should create an example database`, async (t) => { - const results = await tools.runAsyncWithIO(`${schemaCmd} createDatabase "${INSTANCE_ID}" "${DATABASE_ID}"`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, new RegExp(`Waiting for operation on ${DATABASE_ID} to complete...`)); - t.regex(output, new RegExp(`Created database ${DATABASE_ID} on instance ${INSTANCE_ID}.`)); -}); - -// insert_data -test.serial(`should insert rows into an example table`, async (t) => { - const results = await tools.runAsyncWithIO(`${crudCmd} insert ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, /Inserted data\./); -}); - -// query_data -test.serial(`should query an example table and return matching rows`, async (t) => { - const results = await tools.runAsyncWithIO(`${crudCmd} query ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, /SingerId: 1, AlbumId: 1, AlbumTitle: Go, Go, Go/); -}); - -// read_data -test.serial(`should read an example table`, async (t) => { - const results = await tools.runAsyncWithIO(`${crudCmd} read ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, /SingerId: 1, AlbumId: 1, AlbumTitle: Go, Go, Go/); -}); - -// add_column -test.serial(`should add a column to a table`, async (t) => { - const results = await tools.runAsyncWithIO(`${schemaCmd} addColumn ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, /Waiting for operation to complete\.\.\./); - t.regex(output, /Added the MarketingBudget column\./); -}); - -// update_data -test.serial(`should update existing rows in an example table`, async (t) => { - const results = await tools.runAsyncWithIO(`${crudCmd} update ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, /Updated data\./); -}); - -// read_stale_data -test.serial(`should read stale data from an example table`, (t) => { - t.plan(2); - // read-stale-data reads data that is exactly 10 seconds old. So, make sure - // 10 seconds have elapsed since the update_data test. - return (new Promise((resolve) => setTimeout(resolve, 11000))) - .then(async () => { - const results = await tools.runAsyncWithIO(`${crudCmd} read-stale ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, /SingerId: 1, AlbumId: 1, AlbumTitle: Go, Go, Go, MarketingBudget: 100000/); - t.regex(output, /SingerId: 2, AlbumId: 2, AlbumTitle: Forever Hold your Peace, MarketingBudget: 500000/); - }); -}); - -// query_data_with_new_column -test.serial(`should query an example table with an additional column and return matching rows`, async (t) => { - const results = await tools.runAsyncWithIO(`${schemaCmd} queryNewColumn ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, /SingerId: 1, AlbumId: 1, MarketingBudget: 100000/); - t.regex(output, /SingerId: 2, AlbumId: 2, MarketingBudget: 500000/); -}); - -// create_index -test.serial(`should create an index in an example table`, async (t) => { - const results = await tools.runAsyncWithIO(`${indexingCmd} createIndex ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, /Waiting for operation to complete\.\.\./); - t.regex(output, /Added the AlbumsByAlbumTitle index\./); -}); - -// create_storing_index -test.serial(`should create a storing index in an example table`, async (t) => { - const results = await tools.runAsyncWithIO(`${indexingCmd} createStoringIndex ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, /Waiting for operation to complete\.\.\./); - t.regex(output, /Added the AlbumsByAlbumTitle2 index\./); -}); - -// query_data_with_index -test.serial(`should query an example table with an index and return matching rows`, async (t) => { - const results = await tools.runAsyncWithIO(`${indexingCmd} queryIndex ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, /AlbumId: 1, AlbumTitle: Go, Go, Go, MarketingBudget:/); - t.false(output.includes(`AlbumId: 2, AlbumTitle: Total Junk, MarketingBudget:`)); -}); - -test.serial(`should respect query boundaries when querying an example table with an index`, async (t) => { - const results = await tools.runAsyncWithIO(`${indexingCmd} queryIndex ${INSTANCE_ID} ${DATABASE_ID} -s Ardvark -e Zoo`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, /AlbumId: 1, AlbumTitle: Go, Go, Go, MarketingBudget:/); - t.regex(output, /AlbumId: 2, AlbumTitle: Total Junk, MarketingBudget:/); -}); - -// read_data_with_index -test.serial(`should read an example table with an index`, async (t) => { - const results = await tools.runAsyncWithIO(`${indexingCmd} readIndex ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, /AlbumId: 1, AlbumTitle: Go, Go, Go/); -}); - -// read_data_with_storing_index -test.serial(`should read an example table with a storing index`, async (t) => { - const results = await tools.runAsyncWithIO(`${indexingCmd} readStoringIndex ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, /AlbumId: 1, AlbumTitle: Go, Go, Go/); -}); - -// read_only_transaction -test.serial(`should read an example table using transactions`, async (t) => { - const results = await tools.runAsyncWithIO(`${transactionCmd} readOnly ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - const output = results.stdout + results.stderr; - t.regex(output, /SingerId: 1, AlbumId: 1, AlbumTitle: Go, Go, Go/); - t.regex(output, /Successfully executed read-only transaction\./); -}); - -// read_write_transaction -test.serial(`should read from and write to an example table using transactions`, async (t) => { - let results = await tools.runAsyncWithIO(`${transactionCmd} readWrite ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - let output = results.stdout + results.stderr; - t.regex(output, /The first album's marketing budget: 100000/); - t.regex(output, /The second album's marketing budget: 500000/); - t.regex(output, /Successfully executed read-write transaction to transfer 200000 from Album 2 to Album 1./); - - results = await tools.runAsyncWithIO(`${schemaCmd} queryNewColumn ${INSTANCE_ID} ${DATABASE_ID}`, cwd); - output = results.stdout + results.stderr; - t.regex(output, /SingerId: 1, AlbumId: 1, MarketingBudget: 300000/); - t.regex(output, /SingerId: 2, AlbumId: 2, MarketingBudget: 300000/); -}); diff --git a/spanner/transaction.js b/spanner/transaction.js deleted file mode 100644 index e2189229a5..0000000000 --- a/spanner/transaction.js +++ /dev/null @@ -1,189 +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'; - -function readOnlyTransaction (instanceId, databaseId) { - // [START read_only_transaction] - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Gets a reference to a Cloud Spanner instance and database - const instance = spanner.instance(instanceId); - const database = instance.database(databaseId); - - // Gets a transaction object that captures the database state - // at a specific point in time - database.runTransaction({readOnly: true}, (err, transaction) => { - if (err) { - console.error(err); - return; - } - const queryOne = 'SELECT SingerId, AlbumId, AlbumTitle FROM Albums'; - - // Read #1, using SQL - transaction.run(queryOne) - .then((results) => { - const rows = results[0]; - rows.forEach((row) => { - const json = row.toJSON(); - console.log(`SingerId: ${json.SingerId.value}, AlbumId: ${json.AlbumId.value}, AlbumTitle: ${json.AlbumTitle}`); - }); - const queryTwo = { - columns: ['SingerId', 'AlbumId', 'AlbumTitle'], - keySet: { - all: true - } - }; - - // Read #2, using the `read` method. Even if changes occur - // in-between the reads, the transaction ensures that both - // return the same data. - return transaction.read('Albums', queryTwo); - }) - .then((results) => { - const rows = results[0]; - rows.forEach((row) => { - const json = row.toJSON(); - console.log(`SingerId: ${json.SingerId.value}, AlbumId: ${json.AlbumId.value}, AlbumTitle: ${json.AlbumTitle}`); - }); - console.log('Successfully executed read-only transaction.'); - transaction.end(); - }); - }); - // [END read_only_transaction] -} - -function readWriteTransaction (instanceId, databaseId) { - // [START read_write_transaction] - // This sample transfers 200,000 from the MarketingBudget field - // of the second Album to the first Album. Make sure to run the - // addColumn and updateData samples first (in that order). - - // Imports the Google Cloud client library - const Spanner = require('@google-cloud/spanner'); - - // Instantiates a client - const spanner = Spanner(); - - // Uncomment these lines to specify the instance and database to use - // const instanceId = 'my-instance'; - // const databaseId = 'my-database'; - - // Gets a reference to a Cloud Spanner instance and database - const instance = spanner.instance(instanceId); - const database = instance.database(databaseId); - - const transferAmount = 200000; - const minimumAmountToTransfer = 300000; - - database.runTransaction((err, transaction) => { - if (err) { - console.error(err); - return; - } - let firstBudget, secondBudget; - const queryOne = { - columns: [`MarketingBudget`], - keys: [[2, 2]] // SingerId: 2, AlbumId: 2 - }; - - const queryTwo = { - columns: ['MarketingBudget'], - keys: [[1, 1]] // SingerId: 1, AlbumId: 1 - }; - - Promise.all([ - // Reads the second album's budget - transaction.read('Albums', queryOne).then((results) => { - // Gets second album's budget - // Note: MarketingBudget is an INT64, which comes from Cloud Spanner - // as a string - so we convert it to a number with parseInt() - const rows = results[0].map((row) => row.toJSON()); - secondBudget = parseInt(rows[0].MarketingBudget.value); - console.log(`The second album's marketing budget: ${secondBudget}`); - - // Makes sure the second album's budget is sufficient - if (secondBudget < minimumAmountToTransfer) { - throw new Error(`The second album's budget (${secondBudget}) is less than the minimum required amount to transfer.`); - } - }), - - // Reads the first album's budget - transaction.read('Albums', queryTwo).then((results) => { - // Gets first album's budget - // As above, MarketingBudget is an INT64 and comes as a string - const rows = results[0].map((row) => row.toJSON()); - firstBudget = parseInt(rows[0].MarketingBudget.value); - console.log(`The first album's marketing budget: ${firstBudget}`); - }) - ]).then(() => { - // Transfer the budgets between the albums - console.log(firstBudget, secondBudget); - firstBudget += transferAmount; - secondBudget -= transferAmount; - - console.log(firstBudget, secondBudget); - - // Update the database - // Note: Cloud Spanner interprets Node.js numbers as FLOAT64s, so they - // must be converted (back) to strings before being inserted as INT64s. - transaction.update('Albums', [ - { SingerId: '1', AlbumId: '1', MarketingBudget: firstBudget.toString() }, - { SingerId: '2', AlbumId: '2', MarketingBudget: secondBudget.toString() } - ]); - }) - // Commits the transaction and send the changes to the database - .then(() => transaction.commit((err) => { - if (err) { - console.error(err); - } else { - console.log(`Successfully executed read-write transaction to transfer ${transferAmount} from Album 2 to Album 1.`); - } - })); - }); - // [END read_write_transaction] -} - -const cli = require(`yargs`) - .demand(1) - .command( - `readOnly `, - `Execute a read-only transaction on an example Cloud Spanner table.`, - {}, - (opts) => readOnlyTransaction(opts.instanceName, opts.databaseName) - ) - .command( - `readWrite `, - `Execute a read-write transaction on an example Cloud Spanner table.`, - {}, - (opts) => readWriteTransaction(opts.instanceName, opts.databaseName) - ) - .example(`node $0 readOnly "my-instance" "my-database"`) - .example(`node $0 readWrite "my-instance" "my-database"`) - .wrap(120) - .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/spanner/docs`); - -if (module === require.main) { - cli.help().strict().argv; // eslint-disable-line -} diff --git a/translate/README.md b/translate/README.md index eb94019b15..8631236de0 100644 --- a/translate/README.md +++ b/translate/README.md @@ -1,82 +1,5 @@ -Google Cloud Platform logo +Samples for the [Google Cloud Translate API Node.js Client][client] have moved to +[github.com/googleapis/nodejs-translate/tree/master/samples/][samples]. -# Google Cloud Translation API Node.js Samples - -[![Build](https://storage.googleapis.com/cloud-docs-samples-badges/GoogleCloudPlatform/nodejs-docs-samples/nodejs-docs-samples-translate.svg)]() - -The [Cloud Translation API](https://cloud.google.com/translate/docs), can dynamically translate text between thousands of language pairs. The Cloud Translation API lets websites and programs integrate with the translation service programmatically. The Cloud Translation API is part of the larger Cloud Machine Learning API family. - -## Table of Contents - -* [Setup](#setup) -* [Samples](#samples) - * [Translate](#translate) -* [Running the tests](#running-the-tests) - -## Setup - -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 - -## Samples - -### Translate - -View the [documentation][translate_0_docs] or the [source code][translate_0_code]. - -__Usage:__ `node translate.js --help` - -``` -Commands: - detect Detects the language of one or more strings. - list [target] Lists available translation languages. To language names in a language - other than English, specify a target language. - translate Translates one or more strings into the target language. - translate-with-model Translates one or more strings into the target language using the - specified model. - -Options: - --help Show help [boolean] - -Examples: - 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.js translate ru "Good morning!" Translates a string into Russian. - node translate.js translate ru "Good morning!" "Good night!" Translates multiple strings into Russian. - node translate.js translate-with-model ru nmt "Good Translates multiple strings into Russian using the - morning!" "Good night!" Premium model. - -For more information, see https://cloud.google.com/translate/docs -``` - -[translate_0_docs]: https://cloud.google.com/translate/docs -[translate_0_code]: translate.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 +[client]: https://github.com/googleapis/nodejs-translate +[samples]: https://github.com/googleapis/nodejs-translate/tree/master/samples diff --git a/translate/package.json b/translate/package.json deleted file mode 100644 index 3cd11dc889..0000000000 --- a/translate/package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "nodejs-docs-samples-translate", - "version": "0.0.1", - "private": true, - "license": "Apache-2.0", - "author": "Google Inc.", - "repository": { - "type": "git", - "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git" - }, - "engines": { - "node": ">=4.3.2" - }, - "scripts": { - "lint": "samples lint", - "pretest": "npm run lint", - "test": "samples test run --cmd ava -- -T 20s --verbose system-test/*.test.js" - }, - "dependencies": { - "@google-cloud/translate": "1.0.0", - "yargs": "8.0.2" - }, - "devDependencies": { - "@google-cloud/nodejs-repo-tools": "1.4.17", - "ava": "0.21.0", - "proxyquire": "1.8.0", - "sinon": "3.2.0" - }, - "cloud-repo-tools": { - "requiresKeyFile": true, - "requiresProjectId": true, - "product": "translate", - "samples": [ - { - "id": "translate", - "name": "Translate", - "file": "translate.js", - "docs_link": "https://cloud.google.com/translate/docs", - "usage": "node translate.js --help" - } - ] - } -} diff --git a/translate/quickstart.js b/translate/quickstart.js deleted file mode 100644 index 473201dc21..0000000000 --- a/translate/quickstart.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 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. - */ - -'use strict'; - -// [START translate_quickstart] -// Imports the Google Cloud client library -const Translate = require('@google-cloud/translate'); - -// Your Google Cloud Platform project ID -const projectId = 'YOUR_PROJECT_ID'; - -// Instantiates a client -const translateClient = Translate({ - projectId: projectId -}); - -// The text to translate -const text = 'Hello, world!'; -// The target language -const target = 'ru'; - -// Translates some text into Russian -translateClient.translate(text, target) - .then((results) => { - const translation = results[0]; - - console.log(`Text: ${text}`); - console.log(`Translation: ${translation}`); - }) - .catch((err) => { - console.error('ERROR:', err); - }); -// [END translate_quickstart] diff --git a/translate/system-test/quickstart.test.js b/translate/system-test/quickstart.test.js deleted file mode 100644 index 408d722e46..0000000000 --- a/translate/system-test/quickstart.test.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * 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. - */ - -'use strict'; - -const proxyquire = require(`proxyquire`).noPreserveCache(); -const sinon = require(`sinon`); -const test = require(`ava`); -const tools = require(`@google-cloud/nodejs-repo-tools`); -const translate = proxyquire(`@google-cloud/translate`, {})(); - -test.before(tools.checkCredentials); -test.before(tools.stubConsole); -test.after.always(tools.restoreConsole); - -test.cb(`should translate a string`, (t) => { - const string = `Hello, world!`; - const expectedTranslation = `Привет мир!`; - const targetLanguage = `ru`; - const translateMock = { - translate: (_string, _targetLanguage) => { - t.is(_string, string); - t.is(_targetLanguage, targetLanguage); - - return translate.translate(_string, _targetLanguage) - .then(([translation]) => { - t.is(translation, expectedTranslation); - - setTimeout(() => { - try { - t.is(console.log.callCount, 2); - t.deepEqual(console.log.getCall(0).args, [`Text: ${string}`]); - t.deepEqual(console.log.getCall(1).args, [`Translation: ${expectedTranslation}`]); - t.end(); - } catch (err) { - t.end(err); - } - }, 200); - - return [translation]; - }); - } - }; - - proxyquire(`../quickstart`, { - '@google-cloud/translate': sinon.stub().returns(translateMock) - }); -}); diff --git a/translate/system-test/translate.test.js b/translate/system-test/translate.test.js deleted file mode 100644 index 206dbf3325..0000000000 --- a/translate/system-test/translate.test.js +++ /dev/null @@ -1,84 +0,0 @@ -/** - * 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. - */ - -'use strict'; - -const path = require(`path`); -const test = require(`ava`); -const tools = require(`@google-cloud/nodejs-repo-tools`); -const translate = require(`@google-cloud/translate`)(); - -const cwd = path.join(__dirname, `..`); -const cmd = `node translate.js`; -const text = `Hello world!`; -const text2 = `Goodbye!`; -const model = `nmt`; -const toLang = `ru`; - -test.before(tools.checkCredentials); - -test(`should detect language of a single string`, async (t) => { - const output = await tools.runAsync(`${cmd} detect "${text}"`, cwd); - const [detection] = await translate.detect(text); - const expected = `Detections:\n${text} => ${detection.language}`; - t.is(output, expected); -}); - -test(`should detect language of multiple strings`, async (t) => { - const output = await tools.runAsync(`${cmd} detect "${text}" "${text2}"`, cwd); - const [detections] = await translate.detect([text, text2]); - const expected = `Detections:\n${text} => ${detections[0].language}\n${text2} => ${detections[1].language}`; - t.is(output, expected); -}); - -test(`should list languages`, async (t) => { - const output = await tools.runAsync(`${cmd} list`, cwd); - t.true(output.includes(`Languages:`)); - t.true(output.includes(`{ code: 'af', name: 'Afrikaans' }`)); -}); - -test(`should list languages with a target`, async (t) => { - const output = await tools.runAsync(`${cmd} list es`, cwd); - t.true(output.includes(`Languages:`)); - t.true(output.includes(`{ code: 'af', name: 'afrikáans' }`)); -}); - -test(`should translate a single string`, async (t) => { - const output = await tools.runAsync(`${cmd} translate ${toLang} "${text}"`, cwd); - const [translation] = await translate.translate(text, toLang); - const expected = `Translations:\n${text} => (${toLang}) ${translation}`; - t.is(output, expected); -}); - -test(`should translate multiple strings`, async (t) => { - const output = await tools.runAsync(`${cmd} translate ${toLang} "${text}" "${text2}"`, cwd); - const [translations] = await translate.translate([text, text2], toLang); - const expected = `Translations:\n${text} => (${toLang}) ${translations[0]}\n${text2} => (${toLang}) ${translations[1]}`; - t.is(output, expected); -}); - -test(`should translate a single string with a model`, async (t) => { - const output = await tools.runAsync(`${cmd} translate-with-model ${toLang} ${model} "${text}"`, cwd); - const [translation] = await translate.translate(text, toLang); - const expected = `Translations:\n${text} => (${toLang}) ${translation}`; - t.is(output, expected); -}); - -test(`should translate multiple strings with a model`, async (t) => { - const output = await tools.runAsync(`${cmd} translate-with-model ${toLang} ${model} "${text}" "${text2}"`, cwd); - const [translations] = await translate.translate([text, text2], toLang); - const expected = `Translations:\n${text} => (${toLang}) ${translations[0]}\n${text2} => (${toLang}) ${translations[1]}`; - t.is(output, expected); -}); diff --git a/translate/translate.js b/translate/translate.js deleted file mode 100644 index c1145ce0d9..0000000000 --- a/translate/translate.js +++ /dev/null @@ -1,216 +0,0 @@ -/** - * 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. - */ - -'use strict'; - -function detectLanguage (text) { - // [START translate_detect_language] - // Imports the Google Cloud client library - const Translate = require('@google-cloud/translate'); - - // Instantiates a client - const translate = Translate(); - - // The text for which to detect language, e.g. "Hello, world!" - // const text = 'Hello, world!'; - - // Detects the language. "text" 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(text) - .then((results) => { - let detections = results[0]; - detections = Array.isArray(detections) ? detections : [detections]; - - console.log('Detections:'); - detections.forEach((detection) => { - console.log(`${detection.input} => ${detection.language}`); - }); - }) - .catch((err) => { - console.error('ERROR:', err); - }); - // [END translate_detect_language] -} - -function listLanguages () { - // [START translate_list_codes] - // Imports the Google Cloud client library - const Translate = require('@google-cloud/translate'); - - // Instantiates a client - const translate = Translate(); - - // Lists available translation language with their names in English (the default). - translate.getLanguages() - .then((results) => { - const languages = results[0]; - - console.log('Languages:'); - languages.forEach((language) => console.log(language)); - }) - .catch((err) => { - console.error('ERROR:', err); - }); - // [END translate_list_codes] -} - -function listLanguagesWithTarget (target) { - // [START translate_list_language_names] - // Imports the Google Cloud client library - const Translate = require('@google-cloud/translate'); - - // Instantiates a client - const translate = Translate(); - - // The target language for language names, e.g. "ru" - // const target = 'ru'; - - // Lists available translation language with their names in a target language - translate.getLanguages(target) - .then((results) => { - const languages = results[0]; - - console.log('Languages:'); - languages.forEach((language) => console.log(language)); - }) - .catch((err) => { - console.error('ERROR:', err); - }); - // [END translate_list_language_names] -} - -function translateText (text, target) { - // [START translate_translate_text] - // Imports the Google Cloud client library - const Translate = require('@google-cloud/translate'); - - // Instantiates a client - const translate = Translate(); - - // The text to translate, e.g. "Hello, world!" - // const text = 'Hello, world!'; - - // The target language, e.g. "ru" - // const target = 'ru'; - - // Translates the text into the target language. "text" can be a string for - // translating a single piece of text, or an array of strings for translating - // multiple texts. - translate.translate(text, target) - .then((results) => { - let translations = results[0]; - translations = Array.isArray(translations) ? translations : [translations]; - - console.log('Translations:'); - translations.forEach((translation, i) => { - console.log(`${text[i]} => (${target}) ${translation}`); - }); - }) - .catch((err) => { - console.error('ERROR:', err); - }); - // [END translate_translate_text] -} - -function translateTextWithModel (text, target, model) { - // [START translate_text_with_model] - // Imports the Google Cloud client library - const Translate = require('@google-cloud/translate'); - - // Instantiates a client - const translate = Translate(); - - // The text to translate, e.g. "Hello, world!" - // const text = 'Hello, world!'; - - // The target language, e.g. "ru" - // const target = 'ru'; - - // The model to use, e.g. "nmt" - // const model = 'nmt'; - - const options = { - // The target language, e.g. "ru" - to: target, - // Make sure your project is whitelisted. - // Possible values are "base" and "nmt" - model: model - }; - - // Translates the text into the target language. "text" can be a string for - // translating a single piece of text, or an array of strings for translating - // multiple texts. - translate.translate(text, options) - .then((results) => { - let translations = results[0]; - translations = Array.isArray(translations) ? translations : [translations]; - - console.log('Translations:'); - translations.forEach((translation, i) => { - console.log(`${text[i]} => (${target}) ${translation}`); - }); - }) - .catch((err) => { - console.error('ERROR:', err); - }); - // [END translate_text_with_model] -} - -require(`yargs`) // eslint-disable-line - .demand(1) - .command( - `detect `, - `Detects the language of one or more strings.`, - {}, - (opts) => detectLanguage(opts.text) - ) - .command( - `list [target]`, - `Lists available translation languages. To language names in a language other than English, specify a target language.`, - {}, - (opts) => { - if (opts.target) { - listLanguagesWithTarget(opts.target); - } else { - listLanguages(); - } - } - ) - .command( - `translate `, - `Translates one or more strings into the target language.`, - {}, - (opts) => translateText(opts.text, opts.toLang) - ) - .command( - `translate-with-model `, - `Translates one or more strings into the target language using the specified model.`, - {}, - (opts) => translateTextWithModel(opts.text, opts.toLang, opts.model) - ) - .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 a string into Russian.`) - .example(`node $0 translate ru "Good morning!" "Good night!"`, `Translates multiple strings into Russian.`) - .example(`node $0 translate-with-model ru nmt "Good morning!" "Good night!"`, `Translates multiple strings into Russian using the Premium model.`) - .wrap(120) - .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/translate/docs`) - .help() - .strict() - .argv; diff --git a/video/README.md b/video/README.md index 05da66feb4..8d997187cc 100644 --- a/video/README.md +++ b/video/README.md @@ -1,77 +1,5 @@ -Google Cloud Platform logo +Samples for the [Google Cloud Video Intelligence API Node.js Client][client] +have moved to [github.com/googleapis/nodejs-video-intelligence/tree/master/samples/][samples]. -# Google Cloud Video Intelligence API Node.js Samples - -[![Build](https://storage.googleapis.com/cloud-docs-samples-badges/GoogleCloudPlatform/nodejs-docs-samples/nodejs-docs-samples-videointelligence.svg)]() - -The [Cloud Video Intelligence API](https://cloud.google.com/video-intelligence) allows developers to use Google video analysis technology as part of their applications. - -## Table of Contents - -* [Setup](#setup) -* [Samples](#samples) - * [Video Intelligence](#video-intelligence) -* [Running the tests](#running-the-tests) - -## Setup - -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 - -## Samples - -### Video Intelligence - -View the [documentation][video_0_docs] or the [source code][video_0_code]. - -__Usage:__ `node analyze.js --help` - -``` -Commands: - faces Analyzes faces in a video stored in Google Cloud Storage using the Cloud Video Intelligence API. - shots Analyzes shot angles in a video stored in Google Cloud Storage using the Cloud Video - Intelligence API. - labels-gcs Labels objects in a video stored in Google Cloud Storage using the Cloud Video Intelligence API. - labels-file Labels objects in a video stored locally using the Cloud Video Intelligence API. - safe-search Detects explicit content in a video stored in Google Cloud Storage. - -Options: - --help Show help [boolean] - -Examples: - node analyze.js faces gs://demomaker/larry_sergey_ice_bucket_short.mp4 - node analyze.js shots gs://demomaker/sushi.mp4 - node analyze.js labels-gcs gs://demomaker/tomatoes.mp4 - node analyze.js labels-file resources/cat.mp4 - node analyze.js safe-search gs://demomaker/tomatoes.mp4 - -For more information, see https://cloud.google.com/video-intelligence/docs -``` - -[video_0_docs]: https://cloud.google.com/video-intelligence/docs -[video_0_code]: analyze.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 +[client]: https://github.com/googleapis/nodejs-video-intelligence +[samples]: https://github.com/googleapis/nodejs-video-intelligence/tree/master/samples diff --git a/video/analyze.js b/video/analyze.js deleted file mode 100644 index f82c904a8c..0000000000 --- a/video/analyze.js +++ /dev/null @@ -1,357 +0,0 @@ -/** - * 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. - */ - -'use strict'; - -function analyzeFaces (gcsUri) { - // [START analyze_faces] - // Imports the Google Cloud Video Intelligence library - const Video = require('@google-cloud/video-intelligence'); - - // Instantiates a client - const video = Video(); - - // The GCS filepath of the video to analyze - // const gcsUri = 'gs://my-bucket/my-video.mp4'; - - const request = { - inputUri: gcsUri, - features: ['FACE_DETECTION'] - }; - - // Detects faces in a video - video.annotateVideo(request) - .then((results) => { - const operation = results[0]; - console.log('Waiting for operation to complete...'); - return operation.promise(); - }) - .then((results) => { - // Gets faces - const faces = results[0].annotationResults[0].faceAnnotations; - faces.forEach((face, faceIdx) => { - console.log(`Face #${faceIdx}`); - console.log(`\tThumbnail size: ${face.thumbnail.length}`); - face.segments.forEach((segment, segmentIdx) => { - segment = segment.segment; - if (segment.startTimeOffset.seconds === undefined) { - segment.startTimeOffset.seconds = 0; - } - if (segment.startTimeOffset.nanos === undefined) { - segment.startTimeOffset.nanos = 0; - } - if (segment.endTimeOffset.seconds === undefined) { - segment.endTimeOffset.seconds = 0; - } - if (segment.endTimeOffset.nanos === undefined) { - segment.endTimeOffset.nanos = 0; - } - console.log(`\tAppearance #${segmentIdx}:`); - console.log(`\t\tStart: ${segment.startTimeOffset.seconds}` + - `.${(segment.startTimeOffset.nanos / 1e6).toFixed(0)}s`); - console.log(`\t\tEnd: ${segment.endTimeOffset.seconds}.` + - `${(segment.endTimeOffset.nanos / 1e6).toFixed(0)}s`); - }); - console.log(`\tLocations:`); - }); - }) - .catch((err) => { - console.error('ERROR:', err); - }); - // [END analyze_faces] -} - -function analyzeLabelsGCS (gcsUri) { - // [START analyze_labels_gcs] - // Imports the Google Cloud Video Intelligence library - const Video = require('@google-cloud/video-intelligence'); - - // Instantiates a client - const video = Video({ - servicePath: `videointelligence.googleapis.com` - }); - - // The GCS filepath of the video to analyze - // const gcsUri = 'gs://my-bucket/my-video.mp4'; - - const request = { - inputUri: gcsUri, - features: ['LABEL_DETECTION'] - }; - - // Detects labels in a video - video.annotateVideo(request) - .then((results) => { - const operation = results[0]; - console.log('Waiting for operation to complete...'); - return operation.promise(); - }) - .then((results) => { - // Gets annotations for video - const annotations = results[0].annotationResults[0]; - - const labels = annotations.segmentLabelAnnotations; - labels.forEach((label) => { - console.log(`Label ${label.entity.description} occurs at:`); - label.segments.forEach((segment) => { - let time = segment.segment; - if (time.startTimeOffset.seconds === undefined) { - time.startTimeOffset.seconds = 0; - } - if (time.startTimeOffset.nanos === undefined) { - time.startTimeOffset.nanos = 0; - } - if (time.endTimeOffset.seconds === undefined) { - time.endTimeOffset.seconds = 0; - } - if (time.endTimeOffset.nanos === undefined) { - time.endTimeOffset.nanos = 0; - } - console.log(`\tStart: ${time.startTimeOffset.seconds}` + - `.${(time.startTimeOffset.nanos / 1e6).toFixed(0)}s`); - console.log(`\tEnd: ${time.endTimeOffset.seconds}.` + - `${(time.endTimeOffset.nanos / 1e6).toFixed(0)}s`); - console.log(`\tConfidence: ${segment.confidence}`); - }); - }); - }) - .catch((err) => { - console.error('ERROR:', err); - }); - // [END analyze_labels_gcs] -} - -function analyzeLabelsLocal (path) { - // [START analyze_labels_local] - // Imports the Google Cloud Video Intelligence library + Node's fs library - const Video = require('@google-cloud/video-intelligence'); - const fs = require('fs'); - - // Instantiates a client - const video = Video(); - - // The local filepath of the video to analyze - // const path = 'my-file.mp4'; - - // Reads a local video file and converts it to base64 - const file = fs.readFileSync(path); - const inputContent = file.toString('base64'); - - // Constructs request - const request = { - inputContent: inputContent, - features: ['LABEL_DETECTION'] - }; - - // Detects labels in a video - video.annotateVideo(request) - .then((results) => { - const operation = results[0]; - console.log('Waiting for operation to complete...'); - return operation.promise(); - }) - .then((results) => { - // Gets annotations for video - const annotations = results[0].annotationResults[0]; - - const labels = annotations.segmentLabelAnnotations; - labels.forEach((label) => { - console.log(`Label ${label.entity.description} occurs at:`); - label.segments.forEach((segment) => { - let time = segment.segment; - if (time.startTimeOffset.seconds === undefined) { - time.startTimeOffset.seconds = 0; - } - if (time.startTimeOffset.nanos === undefined) { - time.startTimeOffset.nanos = 0; - } - if (time.endTimeOffset.seconds === undefined) { - time.endTimeOffset.seconds = 0; - } - if (time.endTimeOffset.nanos === undefined) { - time.endTimeOffset.nanos = 0; - } - console.log(`\tStart: ${time.startTimeOffset.seconds}` + - `.${(time.startTimeOffset.nanos / 1e6).toFixed(0)}s`); - console.log(`\tEnd: ${time.endTimeOffset.seconds}.` + - `${(time.endTimeOffset.nanos / 1e6).toFixed(0)}s`); - console.log(`\tConfidence: ${segment.confidence}`); - }); - }); - }) - .catch((err) => { - console.error('ERROR:', err); - }); - // [END analyze_labels_local] -} - -function analyzeShots (gcsUri) { - // [START analyze_shots] - // Imports the Google Cloud Video Intelligence library - const Video = require('@google-cloud/video-intelligence'); - - // Instantiates a client - const video = Video(); - - // The GCS filepath of the video to analyze - // const gcsUri = 'gs://my-bucket/my-video.mp4'; - - const request = { - inputUri: gcsUri, - features: ['SHOT_CHANGE_DETECTION'] - }; - - // Detects camera shot changes - video.annotateVideo(request) - .then((results) => { - const operation = results[0]; - console.log('Waiting for operation to complete...'); - return operation.promise(); - }) - .then((results) => { - // Gets shot changes - const shotChanges = results[0].annotationResults[0].shotAnnotations; - console.log('Shot changes:'); - - if (shotChanges.length === 1) { - console.log(`The entire video is one shot.`); - } else { - shotChanges.forEach((shot, shotIdx) => { - console.log(`Scene ${shotIdx} occurs from:`); - if (shot.startTimeOffset === undefined) { - shot.startTimeOffset = {}; - } - if (shot.endTimeOffset === undefined) { - shot.endTimeOffset = {}; - } - if (shot.startTimeOffset.seconds === undefined) { - shot.startTimeOffset.seconds = 0; - } - if (shot.startTimeOffset.nanos === undefined) { - shot.startTimeOffset.nanos = 0; - } - if (shot.endTimeOffset.seconds === undefined) { - shot.endTimeOffset.seconds = 0; - } - if (shot.endTimeOffset.nanos === undefined) { - shot.endTimeOffset.nanos = 0; - } - console.log(`\tStart: ${shot.startTimeOffset.seconds}` + - `.${(shot.startTimeOffset.nanos / 1e6).toFixed(0)}s`); - console.log(`\tEnd: ${shot.endTimeOffset.seconds}.` + - `${(shot.endTimeOffset.nanos / 1e6).toFixed(0)}s`); - }); - } - }) - .catch((err) => { - console.error('ERROR:', err); - }); - // [END analyze_shots] -} - -function analyzeSafeSearch (gcsUri) { - // [START analyze_safe_search] - // Imports the Google Cloud Video Intelligence library - const Video = require('@google-cloud/video-intelligence'); - - // Instantiates a client - const video = Video(); - - // The GCS filepath of the video to analyze - // const gcsUri = 'gs://my-bucket/my-video.mp4'; - - const request = { - inputUri: gcsUri, - features: ['EXPLICIT_CONTENT_DETECTION'] - }; - - // Human-readable likelihoods - const likelihoods = ['UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE', 'LIKELY', 'VERY_LIKELY']; - - // Detects unsafe content - video.annotateVideo(request) - .then((results) => { - const operation = results[0]; - console.log('Waiting for operation to complete...'); - return operation.promise(); - }) - .then((results) => { - // Gets unsafe content - const explicitContentResults = results[0].annotationResults[0].explicitAnnotation; - console.log('Explicit annotation results:'); - explicitContentResults.frames.forEach((result) => { - if (result.timeOffset === undefined) { - result.timeOffset = {}; - } - if (result.timeOffset.seconds === undefined) { - result.timeOffset.seconds = 0; - } - if (result.timeOffset.nanos === undefined) { - result.timeOffset.nanos = 0; - } - console.log(`\tTime: ${result.timeOffset.seconds}` + - `.${(result.timeOffset.nanos / 1e6).toFixed(0)}s`); - console.log(`\t\tPornography liklihood: ${likelihoods[result.pornographyLikelihood]}`); - }); - }) - .catch((err) => { - console.error('ERROR:', err); - }); - // [END analyze_safe_search] -} - -require(`yargs`) // eslint-disable-line - .demand(1) - .command( - `faces `, - `Analyzes faces in a video stored in Google Cloud Storage using the Cloud Video Intelligence API.`, - {}, - (opts) => analyzeFaces(opts.gcsUri) - ) - .command( - `shots `, - `Analyzes shot angles in a video stored in Google Cloud Storage using the Cloud Video Intelligence API.`, - {}, - (opts) => analyzeShots(opts.gcsUri) - ) - .command( - `labels-gcs `, - `Labels objects in a video stored in Google Cloud Storage using the Cloud Video Intelligence API.`, - {}, - (opts) => analyzeLabelsGCS(opts.gcsUri) - ) - .command( - `labels-file `, - `Labels objects in a video stored locally using the Cloud Video Intelligence API.`, - {}, - (opts) => analyzeLabelsLocal(opts.gcsUri) - ) - .command( - `safe-search `, - `Detects explicit content in a video stored in Google Cloud Storage.`, - {}, - (opts) => analyzeSafeSearch(opts.gcsUri) - ) - .example(`node $0 faces gs://demomaker/larry_sergey_ice_bucket_short.mp4`) - .example(`node $0 shots gs://demomaker/sushi.mp4`) - .example(`node $0 labels-gcs gs://demomaker/tomatoes.mp4`) - .example(`node $0 labels-file cat.mp4`) - .example(`node $0 safe-search gs://demomaker/tomatoes.mp4`) - .wrap(120) - .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/video-intelligence/docs`) - .help() - .strict() - .argv; diff --git a/video/package.json b/video/package.json deleted file mode 100644 index e17c092aa4..0000000000 --- a/video/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "nodejs-docs-samples-videointelligence", - "version": "0.0.1", - "private": true, - "license": "Apache-2.0", - "author": "Google Inc.", - "repository": { - "type": "git", - "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git" - }, - "engines": { - "node": ">=4.3.2" - }, - "scripts": { - "lint": "samples lint", - "pretest": "npm run lint", - "test": "samples test run --cmd ava -- -T 5m --verbose system-test/*.test.js" - }, - "dependencies": { - "@google-cloud/video-intelligence": "^0.3.2", - "long": "^3.2.0", - "safe-buffer": "5.1.1", - "yargs": "8.0.2" - }, - "devDependencies": { - "@google-cloud/nodejs-repo-tools": "1.4.17", - "ava": "0.22.0", - "proxyquire": "1.8.0" - }, - "cloud-repo-tools": { - "requiresKeyFile": true, - "requiresProjectId": true, - "product": "video", - "samples": [ - { - "id": "video", - "name": "Video Intelligence", - "file": "analyze.js", - "docs_link": "https://cloud.google.com/video-intelligence/docs", - "usage": "node analyze.js --help" - } - ] - } -} diff --git a/video/quickstart.js b/video/quickstart.js deleted file mode 100644 index bb40eafe9f..0000000000 --- a/video/quickstart.js +++ /dev/null @@ -1,73 +0,0 @@ -/** - * 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. - */ - -'use strict'; - -// [START videointelligence_quickstart] -// Imports the Google Cloud Video Intelligence library -const Video = require('@google-cloud/video-intelligence'); - -// Instantiates a client -const video = Video(); - -// The GCS filepath of the video to analyze -const gcsUri = 'gs://nodejs-docs-samples-video/quickstart_short.mp4'; - -// Construct request -const request = { - inputUri: gcsUri, - features: ['LABEL_DETECTION'] -}; - -// Execute request -video.annotateVideo(request) - .then((results) => { - const operation = results[0]; - console.log('Waiting for operation to complete... (this may take a few minutes)'); - return operation.promise(); - }) - .then((results) => { - // Gets annotations for video - const annotations = results[0].annotationResults[0]; - - // Gets labels for video from its annotations - const labels = annotations.segmentLabelAnnotations; - labels.forEach((label) => { - console.log(`Label ${label.entity.description} occurs at:`); - label.segments.forEach((segment) => { - segment = segment.segment; - if (segment.startTimeOffset.seconds === undefined) { - segment.startTimeOffset.seconds = 0; - } - if (segment.startTimeOffset.nanos === undefined) { - segment.startTimeOffset.nanos = 0; - } - if (segment.endTimeOffset.seconds === undefined) { - segment.endTimeOffset.seconds = 0; - } - if (segment.endTimeOffset.nanos === undefined) { - segment.endTimeOffset.nanos = 0; - } - console.log(`\tStart: ${segment.startTimeOffset.seconds}` + - `.${(segment.startTimeOffset.nanos / 1e6).toFixed(0)}s`); - console.log(`\tEnd: ${segment.endTimeOffset.seconds}.` + - `${(segment.endTimeOffset.nanos / 1e6).toFixed(0)}s`); - }); - }); - }) - .catch((err) => { - console.error('ERROR:', err); - }); -// [END videointelligence_quickstart] diff --git a/video/resources/cat.mp4 b/video/resources/cat.mp4 deleted file mode 100644 index 0e071b9ec6..0000000000 Binary files a/video/resources/cat.mp4 and /dev/null differ diff --git a/video/system-test/analyze.test.js b/video/system-test/analyze.test.js deleted file mode 100644 index ce54904743..0000000000 --- a/video/system-test/analyze.test.js +++ /dev/null @@ -1,77 +0,0 @@ -/** - * 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. - */ - -// https://cloud.google.com/video-intelligence/docs/ - -'use strict'; - -const path = require(`path`); -const test = require(`ava`); -const tools = require(`@google-cloud/nodejs-repo-tools`); - -const cmd = `node analyze.js`; -const cwd = path.join(__dirname, `..`); - -const url = `gs://nodejs-docs-samples-video/quickstart.mp4`; -const shortUrl = `gs://nodejs-docs-samples-video/quickstart_short.mp4`; -const file = `resources/cat.mp4`; - -// analyze_faces -test.serial(`should analyze faces in a GCS file`, async (t) => { - const output = await tools.runAsync(`${cmd} faces ${url}`, cwd); - t.regex(output, /Thumbnail size: \d+/); - t.regex(output, /Start:.*\d+\.\d+s/); - t.regex(output, /End:.*\d+\.\d+s/); -}); - -// analyze_labels_gcs (one scene) -test.serial(`should analyze labels in a GCS file with one scene`, async (t) => { - const output = await tools.runAsync(`${cmd} labels-gcs ${shortUrl}`, cwd); - t.regex(output, /Label shirt occurs at:/); - t.regex(output, /Confidence: \d+\.\d+/); -}); - -// analyze_labels_gcs (multiple scenes) -test.serial(`should analyze labels in a GCS file with multiple scenes`, async (t) => { - const output = await tools.runAsync(`${cmd} labels-gcs ${url}`, cwd); - t.regex(output, /Label shirt occurs at:/); - t.regex(output, /Confidence: \d+\.\d+/); -}); - -// analyze_labels_local -test.serial(`should analyze labels in a local file`, async (t) => { - const output = await tools.runAsync(`${cmd} labels-file ${file}`, cwd); - t.regex(output, /Label whiskers occurs at:/); - t.regex(output, /Confidence: \d+\.\d+/); -}); - -// analyze_shots (multiple shots) -test.serial(`should analyze shots in a GCS file with multiple shots`, async (t) => { - const output = await tools.runAsync(`${cmd} shots ${url}`, cwd); - t.regex(output, /Scene 0 occurs from:/); -}); - -// analyze_shots (one shot) -test.serial(`should analyze shots in a GCS file with one shot`, async (t) => { - const output = await tools.runAsync(`${cmd} shots ${shortUrl}`, cwd); - t.regex(output, /The entire video is one shot./); -}); - -// analyze_safe_search -test.serial(`should analyze safe search results in a GCS file`, async (t) => { - const output = await tools.runAsync(`${cmd} safe-search ${url}`, cwd); - t.regex(output, /Time: \d+\.\d+s/); - t.regex(output, /Explicit annotation results:/); -}); diff --git a/video/system-test/quickstart.test.js b/video/system-test/quickstart.test.js deleted file mode 100644 index 20965be0c6..0000000000 --- a/video/system-test/quickstart.test.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * 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. - */ - -'use strict'; - -const path = require(`path`); -const test = require(`ava`); -const tools = require(`@google-cloud/nodejs-repo-tools`); - -const cmd = `node quickstart.js`; -const cwd = path.join(__dirname, `..`); - -test(`should analyze a hardcoded video`, async (t) => { - const output = await tools.runAsync(cmd, cwd); - t.regex(output, /Label standing occurs at:/); -});