Skip to content

Commit 97c5379

Browse files
authored
samples: moving autoML samples from nodejs-translate and refactored them (#432)
1 parent ba51f44 commit 97c5379

File tree

7 files changed

+362
-129
lines changed

7 files changed

+362
-129
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Copyright 2020 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
async function main(operationFullId) {
18+
// [START automl_cancel_operation_beta]
19+
20+
/**
21+
* TODO(developer): Uncomment these variables before running the sample.
22+
*/
23+
// const operationFullId = 'projects/YOUR_PROJECT_ID/locations/YOUR_LOCATIOIN/operations/OPERATION_ID';
24+
25+
// Imports the Google Cloud AutoML library
26+
const {AutoMlClient} = require('@google-cloud/automl').v1beta1;
27+
28+
// Instantiates a client
29+
const client = new AutoMlClient();
30+
31+
async function cancelOperation() {
32+
client.operationsClient.cancelOperation({
33+
name: operationFullId,
34+
});
35+
36+
// Wait for operation to complete.
37+
console.log('Cancelled operation');
38+
}
39+
40+
cancelOperation();
41+
// [END automl_cancel_operation_beta]
42+
}
43+
44+
main(...process.argv.slice(2)).catch(err => {
45+
console.error(err.message);
46+
process.exitCode = 1;
47+
});
48+
process.on('unhandledRejection', err => {
49+
console.error(err.message);
50+
process.exitCode = 1;
51+
});
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
// Copyright 2020 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
const {assert} = require('chai');
18+
const {describe, it} = require('mocha');
19+
const cp = require('child_process');
20+
const uuid = require('uuid');
21+
22+
const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});
23+
24+
const automl = require('@google-cloud/automl');
25+
26+
const cmdDataset = 'node translate/automlTranslateCreateDataset.js';
27+
const cmdModel = 'node translate/automlTranslateCreateModel.js';
28+
const cmdPredict = 'node translate/automlTranslatePredict.js';
29+
30+
const projectId = process.env.AUTOML_PROJECT_ID;
31+
const datasetId = process.env.TRANSLATION_DATASET_ID;
32+
const modelId = process.env.TRANSLATION_MODEL_ID;
33+
34+
const samplePredictionText = './translate/resources/testInput.txt';
35+
36+
describe('Translate AutoML sample tests', () => {
37+
it('should create and delete a dataset', async () => {
38+
const datasetDisplayName = `test_${uuid
39+
.v4()
40+
.replace(/-/g, '_')
41+
.substring(0, 20)}`;
42+
43+
// Create dataset
44+
let output = execSync(
45+
`${cmdDataset} "${projectId}" "${datasetDisplayName}"`
46+
);
47+
48+
//extract dataset id from the output
49+
const newDatasetId = output.split('\n')[1].split(':')[1].trim();
50+
assert.match(output, /Dataset id:/);
51+
52+
// Delete the created dataset
53+
output = execSync(
54+
`node delete_dataset.js ${projectId} us-central1 ${newDatasetId}`
55+
);
56+
assert.match(output, /Dataset deleted/);
57+
});
58+
59+
it('should create model and cancel the training operation', async () => {
60+
// create a model with pre-existing dataset
61+
let output = execSync(
62+
`${cmdModel} ${projectId} us-central1 ${datasetId} translate_test_model`
63+
);
64+
assert.match(output, /Training started../);
65+
const operationFullId = output
66+
.split('Training operation name:')[1]
67+
.split('\n')[0]
68+
.trim();
69+
70+
assert.include(output, operationFullId);
71+
72+
// cancel the training LRO.
73+
output = execSync(`node beta/cancel_operation.js ${operationFullId}`);
74+
assert.match(output, /Cancelled/);
75+
});
76+
77+
it('should run Prediction from translation model', async () => {
78+
// Verify the model is deployed before trying to predict
79+
const client = new automl.AutoMlClient();
80+
81+
const modelFullId = {
82+
name: client.modelPath(projectId, 'us-central1', modelId),
83+
};
84+
85+
const [response] = await client.getModel(modelFullId);
86+
if (response.deploymentState !== 'DEPLOYED') {
87+
// Deploy model if it is not deployed
88+
const [operation] = await client.deployModel(modelFullId);
89+
90+
// Wait for operation to complete.
91+
const [response] = await operation.promise();
92+
console.log(`Model deployment finished. ${response}`);
93+
}
94+
95+
// Run prediction on 'testInput.txt' in resources folder
96+
const output = execSync(
97+
`${cmdPredict} "${projectId}" us-central1 "${modelId}" "${samplePredictionText}" "False"`
98+
);
99+
assert.match(output, /Translated Content:/);
100+
});
101+
});

automl/snippets/test/automlTranslation.v1beta1.test.js

Lines changed: 0 additions & 129 deletions
This file was deleted.
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Copyright 2020 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
async function main(projectId, displayName) {
18+
// [START automl_translation_create_dataset]
19+
20+
/**
21+
* Demonstrates using the AutoML client to request to create dataset for
22+
* automl translation.
23+
* TODO(developer): Uncomment the following lines before running the sample.
24+
*/
25+
// const projectId = '[PROJECT_ID]' e.g., "my-gcloud-project";
26+
// const displayName = '[DATASET_DISPLAY_NAME]' e.g., "my-dataset-name";
27+
28+
const automl = require('@google-cloud/automl');
29+
30+
// Create client for automl service.
31+
const client = new automl.AutoMlClient();
32+
const computeRegion = 'us-central1';
33+
const source = 'en';
34+
const target = 'ja';
35+
36+
// A resource that represents Google Cloud Platform location.
37+
const projectLocation = client.locationPath(projectId, computeRegion);
38+
39+
async function createDataset() {
40+
// Specify the source and target language.
41+
const datasetSpec = {
42+
sourceLanguageCode: source,
43+
targetLanguageCode: target,
44+
};
45+
46+
// Set dataset name and dataset specification.
47+
const datasetInfo = {
48+
displayName: displayName,
49+
translationDatasetMetadata: datasetSpec,
50+
};
51+
52+
// Create a dataset with the dataset specification in the region.
53+
const [operation] = await client.createDataset({
54+
parent: projectLocation,
55+
dataset: datasetInfo,
56+
});
57+
58+
// wait for lro to finish
59+
const [dataset] = await operation.promise();
60+
// Display the dataset information
61+
console.log(`Dataset name: ${dataset.name}`);
62+
console.log(`Dataset id: ${dataset.name.split('/').pop(-1)}`);
63+
}
64+
65+
createDataset();
66+
// [END automl_translation_create_dataset]
67+
}
68+
69+
main(...process.argv.slice(2)).catch(err => {
70+
console.error(err.message);
71+
process.exitCode = 1;
72+
});
73+
process.on('unhandledRejection', err => {
74+
console.error(err.message);
75+
process.exitCode = 1;
76+
});

0 commit comments

Comments
 (0)