diff --git a/translate/automl/automlTranslationDataset.js b/translate/automl/automlTranslationDataset.js index 5f0fb40e2aa..0528a45d52c 100755 --- a/translate/automl/automlTranslationDataset.js +++ b/translate/automl/automlTranslationDataset.js @@ -23,7 +23,13 @@ `use strict`; -function createDataset(projectId, computeRegion, datasetName, source, target) { +async function createDataset( + projectId, + computeRegion, + datasetName, + source, + target +) { // [START automl_translation_create_dataset] const automl = require(`@google-cloud/automl`).v1beta1; @@ -48,44 +54,40 @@ function createDataset(projectId, computeRegion, datasetName, source, target) { }; // Set dataset name and dataset specification. - const dataset = { + const datasetInfo = { displayName: datasetName, translationDatasetMetadata: datasetSpec, }; // Create a dataset with the dataset specification in the region. - client - .createDataset({parent: projectLocation, dataset: dataset}) - .then(responses => { - const dataset = responses[0]; - - // Display the dataset information - console.log(`Dataset name: ${dataset.name}`); - console.log(`Dataset id: ${dataset.name.split(`/`).pop(-1)}`); - console.log(`Dataset display name: ${dataset.displayName}`); - console.log(`Dataset example count: ${dataset.exampleCount}`); - console.log(`Translation dataset specification:`); - console.log( - `\tSource language code: ${ - dataset.translationDatasetMetadata.sourceLanguageCode - }` - ); - console.log( - `\tTarget language code: ${ - dataset.translationDatasetMetadata.targetLanguageCode - }` - ); - console.log(`Dataset create time:`); - console.log(`\tseconds: ${dataset.createTime.seconds}`); - console.log(`\tnanos: ${dataset.createTime.nanos}`); - }) - .catch(err => { - console.error(err); - }); + const [dataset] = await client.createDataset({ + parent: projectLocation, + dataset: datasetInfo, + }); + + // Display the dataset information + console.log(`Dataset name: ${dataset.name}`); + console.log(`Dataset id: ${dataset.name.split(`/`).pop(-1)}`); + console.log(`Dataset display name: ${dataset.displayName}`); + console.log(`Dataset example count: ${dataset.exampleCount}`); + console.log(`Translation dataset specification:`); + console.log( + `\tSource language code: ${ + dataset.translationDatasetMetadata.sourceLanguageCode + }` + ); + console.log( + `\tTarget language code: ${ + dataset.translationDatasetMetadata.targetLanguageCode + }` + ); + console.log(`Dataset create time:`); + console.log(`\tseconds: ${dataset.createTime.seconds}`); + console.log(`\tnanos: ${dataset.createTime.nanos}`); // [END automl_translation_create_dataset] } -function listDatasets(projectId, computeRegion, filter) { +async function listDatasets(projectId, computeRegion, filter) { // [START automl_translation_list_datasets] const automl = require(`@google-cloud/automl`); @@ -102,41 +104,38 @@ function listDatasets(projectId, computeRegion, filter) { const projectLocation = client.locationPath(projectId, computeRegion); // List all the datasets available in the region by applying filter. - client - .listDatasets({parent: projectLocation, filter: filter}) - .then(responses => { - const datasets = responses[0]; - - // Display the dataset information. - console.log(`List of datasets:`); - datasets.forEach(dataset => { - console.log(`Dataset name: ${dataset.name}`); - console.log(`Dataset id: ${dataset.name.split(`/`).pop(-1)}`); - console.log(`Dataset display name: ${dataset.displayName}`); - console.log(`Dataset example count: ${dataset.exampleCount}`); - console.log(`Translation dataset specification:`); - console.log( - `\tSource language code: ${ - dataset.translationDatasetMetadata.sourceLanguageCode - }` - ); - console.log( - `\tTarget language code: ${ - dataset.translationDatasetMetadata.targetLanguageCode - }` - ); - console.log(`Dataset create time:`); - console.log(`\tseconds: ${dataset.createTime.seconds}`); - console.log(`\tnanos: ${dataset.createTime.nanos}`); - }); - }) - .catch(err => { - console.error(err); - }); + const [datasets] = await client.listDatasets({ + parent: projectLocation, + filter: filter, + }); + + // Display the dataset information. + console.log(`List of datasets:`); + datasets.forEach(dataset => { + console.log(`Dataset name: ${dataset.name}`); + console.log(`Dataset id: ${dataset.name.split(`/`).pop(-1)}`); + console.log(`Dataset display name: ${dataset.displayName}`); + console.log(`Dataset example count: ${dataset.exampleCount}`); + console.log(`Translation dataset specification:`); + console.log( + `\tSource language code: ${ + dataset.translationDatasetMetadata.sourceLanguageCode + }` + ); + console.log( + `\tTarget language code: ${ + dataset.translationDatasetMetadata.targetLanguageCode + }` + ); + console.log(`Dataset create time:`); + console.log(`\tseconds: ${dataset.createTime.seconds}`); + console.log(`\tnanos: ${dataset.createTime.nanos}`); + }); + // [END automl_translation_list_datasets] } -function getDataset(projectId, computeRegion, datasetId) { +async function getDataset(projectId, computeRegion, datasetId) { // [START automl_translation_get_dataset] const automl = require(`@google-cloud/automl`).v1beta1; @@ -153,38 +152,32 @@ function getDataset(projectId, computeRegion, datasetId) { const datasetFullId = client.datasetPath(projectId, computeRegion, datasetId); // Get complete detail of the dataset. - client - .getDataset({name: datasetFullId}) - .then(responses => { - const dataset = responses[0]; - - // Display the dataset information. - console.log(`Dataset name: ${dataset.name}`); - console.log(`Dataset id: ${dataset.name.split(`/`).pop(-1)}`); - console.log(`Dataset display name: ${dataset.displayName}`); - console.log(`Dataset example count: ${dataset.exampleCount}`); - console.log(`Translation dataset specification:`); - console.log( - `\tSource language code: ${ - dataset.translationDatasetMetadata.sourceLanguageCode - }` - ); - console.log( - `\tTarget language code: ${ - dataset.translationDatasetMetadata.targetLanguageCode - }` - ); - console.log(`Dataset create time:`); - console.log(`\tseconds: ${dataset.createTime.seconds}`); - console.log(`\tnanos: ${dataset.createTime.nanos}`); - }) - .catch(err => { - console.error(err); - }); + const [dataset] = await client.getDataset({name: datasetFullId}); + + // Display the dataset information. + console.log(`Dataset name: ${dataset.name}`); + console.log(`Dataset id: ${dataset.name.split(`/`).pop(-1)}`); + console.log(`Dataset display name: ${dataset.displayName}`); + console.log(`Dataset example count: ${dataset.exampleCount}`); + console.log(`Translation dataset specification:`); + console.log( + `\tSource language code: ${ + dataset.translationDatasetMetadata.sourceLanguageCode + }` + ); + console.log( + `\tTarget language code: ${ + dataset.translationDatasetMetadata.targetLanguageCode + }` + ); + console.log(`Dataset create time:`); + console.log(`\tseconds: ${dataset.createTime.seconds}`); + console.log(`\tnanos: ${dataset.createTime.nanos}`); + // [END automl_translation_get_dataset] } -function importData(projectId, computeRegion, datasetId, path) { +async function importData(projectId, computeRegion, datasetId, path) { // [START automl_translation_import_data] const automl = require(`@google-cloud/automl`).v1beta1; @@ -210,26 +203,21 @@ function importData(projectId, computeRegion, datasetId, path) { }; // Import data from the input URI. - client - .importData({name: datasetFullId, inputConfig: inputConfig}) - .then(responses => { - const operation = responses[0]; - console.log(`Processing import...`); - return operation.promise(); - }) - .then(responses => { - // The final result of the operation. - if (responses[2].done === true) { - console.log(`Data imported.`); - } - }) - .catch(err => { - console.error(err); - }); + const [operation] = await client.importData({ + name: datasetFullId, + inputConfig: inputConfig, + }); + console.log(`Processing import...`); + const operationResponses = await operation.promise(); + // The final result of the operation. + if (operationResponses[2].done === true) { + console.log(`Data imported.`); + } + // [END automl_translation_import_data] } -function deleteDataset(projectId, computeRegion, datasetId) { +async function deleteDataset(projectId, computeRegion, datasetId) { // [START automl_translation_delete_dataset] const automl = require(`@google-cloud/automl`).v1beta1; @@ -246,19 +234,11 @@ function deleteDataset(projectId, computeRegion, datasetId) { const datasetFullId = client.datasetPath(projectId, computeRegion, datasetId); // Delete a dataset. - client - .deleteDataset({name: datasetFullId}) - .then(responses => { - const operation = responses[0]; - return operation.promise(); - }) - .then(responses => { - // The final result of the operation. - if (responses[2].done === true) console.log(`Dataset deleted.`); - }) - .catch(err => { - console.error(err); - }); + const [operations] = await client.deleteDataset({name: datasetFullId}); + const operationResponses = await operations.promise(); + // The final result of the operation. + if (operationResponses[2].done === true) console.log(`Dataset deleted.`); + // [END automl_translation_delete_dataset] } @@ -335,26 +315,61 @@ require(`yargs`) description: `The target language to be translated to`, }, }) - .command(`createDataset`, `creates a new Dataset`, {}, opts => - createDataset( - opts.projectId, - opts.computeRegion, - opts.datasetName, - opts.source, - opts.target - ) + .command( + `createDataset`, + `creates a new Dataset`, + {}, + async opts => + await createDataset( + opts.projectId, + opts.computeRegion, + opts.datasetName, + opts.source, + opts.target + ).catch(console.error) ) - .command(`list-datasets`, `list all Datasets`, {}, opts => - listDatasets(opts.projectId, opts.computeRegion, opts.filter) + .command( + `list-datasets`, + `list all Datasets`, + {}, + async opts => + await listDatasets(opts.projectId, opts.computeRegion, opts.filter).catch( + console.error + ) ) - .command(`get-dataset`, `Get a Dataset`, {}, opts => - getDataset(opts.projectId, opts.computeRegion, opts.datasetId) + .command( + `get-dataset`, + `Get a Dataset`, + {}, + async opts => + await getDataset( + opts.projectId, + opts.computeRegion, + opts.datasetId + ).catch(console.error) ) - .command(`delete-dataset`, `Delete a dataset`, {}, opts => - deleteDataset(opts.projectId, opts.computeRegion, opts.datasetId) + .command( + `delete-dataset`, + `Delete a dataset`, + {}, + async opts => + await deleteDataset( + opts.projectId, + opts.computeRegion, + opts.datasetId + ).catch(console.error) ) - .command(`import-data`, `Import labeled items into dataset`, {}, opts => - importData(opts.projectId, opts.computeRegion, opts.datasetId, opts.path) + .command( + `import-data`, + `Import labeled items into dataset`, + {}, + async opts => + await importData( + opts.projectId, + opts.computeRegion, + opts.datasetId, + opts.path + ).catch(console.error) ) .example(`node $0 create-dataset -n "newDataSet" -s "en" -t "ja"`) .example(`node $0 list-datasets -f "translationDatasetMetadata:*"`) diff --git a/translate/automl/automlTranslationModel.js b/translate/automl/automlTranslationModel.js index 09caec34986..b3df6301d95 100755 --- a/translate/automl/automlTranslationModel.js +++ b/translate/automl/automlTranslationModel.js @@ -23,7 +23,7 @@ `use strict`; -function createModel(projectId, computeRegion, datasetId, modelName) { +async function createModel(projectId, computeRegion, datasetId, modelName) { // [START automl_translation_create_model] const automl = require(`@google-cloud/automl`).v1beta1; @@ -48,44 +48,37 @@ function createModel(projectId, computeRegion, datasetId, modelName) { }; // Create a model with the model metadata in the region. - client - .createModel({parent: projectLocation, model: myModel}) - .then(responses => { - const operation = responses[0]; - const initialApiResponse = responses[1]; - - console.log(`Training operation name: `, initialApiResponse.name); - console.log(`Training started...`); - return operation.promise(); - }) - .then(responses => { - // The final result of the operation. - const model = responses[0]; - console.log(model); - // Retrieve deployment state. - let deploymentState = ``; - if (model.deploymentState === 1) { - deploymentState = `deployed`; - } else if (model.deploymentState === 2) { - deploymentState = `undeployed`; - } - - // Display the model information. - console.log(`Model name: ${model.name}`); - console.log(`Model id: ${model.name.split(`/`).pop(-1)}`); - console.log(`Model display name: ${model.displayName}`); - console.log(`Model create time:`); - console.log(`\tseconds: ${model.createTime.seconds}`); - console.log(`\tnanos: ${model.createTime.nanos}`); - console.log(`Model deployment state: ${deploymentState}`); - }) - .catch(err => { - console.error(err); - }); + const [operation, response] = await client.createModel({ + parent: projectLocation, + model: myModel, + }); + const initialApiResponse = response; + console.log(`Training operation name: `, initialApiResponse.name); + console.log(`Training started...`); + const [model] = await operation.promise(); + // The final result of the operation. + console.log(model); + // Retrieve deployment state. + let deploymentState = ``; + if (model.deploymentState === 1) { + deploymentState = `deployed`; + } else if (model.deploymentState === 2) { + deploymentState = `undeployed`; + } + + // Display the model information. + console.log(`Model name: ${model.name}`); + console.log(`Model id: ${model.name.split(`/`).pop(-1)}`); + console.log(`Model display name: ${model.displayName}`); + console.log(`Model create time:`); + console.log(`\tseconds: ${model.createTime.seconds}`); + console.log(`\tnanos: ${model.createTime.nanos}`); + console.log(`Model deployment state: ${deploymentState}`); + // [END automl_translation_create_model] } -function listModels(projectId, computeRegion, filter) { +async function listModels(projectId, computeRegion, filter) { // [START automl_translation_list_models] const automl = require(`@google-cloud/automl`).v1beta1; @@ -102,35 +95,32 @@ function listModels(projectId, computeRegion, filter) { const projectLocation = client.locationPath(projectId, computeRegion); // List all the models available in the region by applying filter. - client - .listModels({parent: projectLocation, filter: filter}) - .then(responses => { - const models = responses[0]; - - // Display the model information. - console.log(`List of models:`); - models.forEach(model => { - console.log(`Model name: ${model.name}`); - console.log(`Model id: ${model.name.split(`/`).pop(-1)}`); - console.log(`Model display name: ${model.displayName}`); - console.log(`Model dataset id: ${model.datasetId}`); - console.log(`Model create time:`); - console.log(`\tseconds: ${model.createTime.seconds}`); - console.log(`\tnanos: ${model.createTime.nanos}`); - console.log(`Model update time:`); - console.log(`\tseconds: ${model.updateTime.seconds}`); - console.log(`\tnanos: ${model.updateTime.nanos}`); - console.log(`Model deployment state: ${model.deploymentState}`); - console.log(`\n`); - }); - }) - .catch(err => { - console.error(err); - }); + const [models] = await client.listModels({ + parent: projectLocation, + filter: filter, + }); + + // Display the model information. + console.log(`List of models:`); + models.forEach(model => { + console.log(`Model name: ${model.name}`); + console.log(`Model id: ${model.name.split(`/`).pop(-1)}`); + console.log(`Model display name: ${model.displayName}`); + console.log(`Model dataset id: ${model.datasetId}`); + console.log(`Model create time:`); + console.log(`\tseconds: ${model.createTime.seconds}`); + console.log(`\tnanos: ${model.createTime.nanos}`); + console.log(`Model update time:`); + console.log(`\tseconds: ${model.updateTime.seconds}`); + console.log(`\tnanos: ${model.updateTime.nanos}`); + console.log(`Model deployment state: ${model.deploymentState}`); + console.log(`\n`); + }); + // [END automl_translation_list_models] } -function getModel(projectId, computeRegion, modelId) { +async function getModel(projectId, computeRegion, modelId) { // [START automl_translation_get_model] const automl = require(`@google-cloud/automl`).v1beta1; @@ -147,71 +137,59 @@ function getModel(projectId, computeRegion, modelId) { const modelFullId = client.modelPath(projectId, computeRegion, modelId); // Get complete detail of the model. - client - .getModel({name: modelFullId}) - .then(responses => { - const model = responses[0]; - - // Display the model information. - console.log(`Model name: ${model.name}`); - console.log(`Model id: ${model.name.split(`/`).pop(-1)}`); - console.log(`Model display name: ${model.displayName}`); - console.log(`Model dataset id: ${model.datasetId}`); - if (model.modelMetadata === `translationModelMetadata`) { - console.log(`Translation model metadata:`); - console.log( - `\tBase model: ${model.translationModelMetadata.baseModel}` - ); - console.log( - `\tSource language code: ${ - model.translationModelMetadata.sourceLanguageCode - }` - ); - console.log( - `\tTarget language code: ${ - model.translationModelMetadata.targetLanguageCode - }` - ); - } else if (model.modelMetadata === `textClassificationModelMetadata`) { - console.log( - `Text classification model metadata: ${ - model.textClassificationModelMetadata - }` - ); - } else if (model.modelMetadata === `imageClassificationModelMetadata`) { - console.log(`Image classification model metadata:`); - console.log( - `\tBase model id: ${ - model.imageClassificationModelMetadata.baseModelId - }` - ); - console.log( - `\tTrain budget: ${ - model.imageClassificationModelMetadata.trainBudget - }` - ); - console.log( - `\tTrain cost: ${model.imageClassificationModelMetadata.trainCost}` - ); - console.log( - `\tStop reason: ${model.imageClassificationModelMetadata.stopReason}` - ); - } - console.log(`Model create time:`); - console.log(`\tseconds: ${model.createTime.seconds}`); - console.log(`\tnanos: ${model.createTime.nanos}`); - console.log(`Model update time:`); - console.log(`\tseconds: ${model.updateTime.seconds}`); - console.log(`\tnanos: ${model.updateTime.nanos}`); - console.log(`Model deployment state: ${model.deploymentState}`); - }) - .catch(err => { - console.error(err); - }); + const [model] = await client.getModel({name: modelFullId}); + + // Display the model information. + console.log(`Model name: ${model.name}`); + console.log(`Model id: ${model.name.split(`/`).pop(-1)}`); + console.log(`Model display name: ${model.displayName}`); + console.log(`Model dataset id: ${model.datasetId}`); + if (model.modelMetadata === `translationModelMetadata`) { + console.log(`Translation model metadata:`); + console.log(`\tBase model: ${model.translationModelMetadata.baseModel}`); + console.log( + `\tSource language code: ${ + model.translationModelMetadata.sourceLanguageCode + }` + ); + console.log( + `\tTarget language code: ${ + model.translationModelMetadata.targetLanguageCode + }` + ); + } else if (model.modelMetadata === `textClassificationModelMetadata`) { + console.log( + `Text classification model metadata: ${ + model.textClassificationModelMetadata + }` + ); + } else if (model.modelMetadata === `imageClassificationModelMetadata`) { + console.log(`Image classification model metadata:`); + console.log( + `\tBase model id: ${model.imageClassificationModelMetadata.baseModelId}` + ); + console.log( + `\tTrain budget: ${model.imageClassificationModelMetadata.trainBudget}` + ); + console.log( + `\tTrain cost: ${model.imageClassificationModelMetadata.trainCost}` + ); + console.log( + `\tStop reason: ${model.imageClassificationModelMetadata.stopReason}` + ); + } + console.log(`Model create time:`); + console.log(`\tseconds: ${model.createTime.seconds}`); + console.log(`\tnanos: ${model.createTime.nanos}`); + console.log(`Model update time:`); + console.log(`\tseconds: ${model.updateTime.seconds}`); + console.log(`\tnanos: ${model.updateTime.nanos}`); + console.log(`Model deployment state: ${model.deploymentState}`); + // [END automl_translation_get_model] } -function listModelEvaluations(projectId, computeRegion, modelId, filter) { +async function listModelEvaluations(projectId, computeRegion, modelId, filter) { // [START automl_translation_list_model_evaluations] const automl = require(`@google-cloud/automl`).v1beta1; @@ -226,25 +204,22 @@ function listModelEvaluations(projectId, computeRegion, modelId, filter) { // const filter = `filter expressions, must specify field, e.g. “imageClassificationModelMetadata:*”`; // Get the full path of the model. - const modelFullId = client.modelPath(projectId, computeRegion, modelId); + const modelFullId = await client.modelPath(projectId, computeRegion, modelId); // List all the model evaluations in the model by applying filter. - client - .listModelEvaluations({parent: modelFullId, filter: filter}) - .then(responses => { - const elements = responses[0]; - console.log(`List of model evaluations:`); - elements.forEach(element => { - console.log(element); - }); - }) - .catch(err => { - console.error(err); - }); + const [elements] = client.listModelEvaluations({ + parent: modelFullId, + filter: filter, + }); + console.log(`List of model evaluations:`); + elements.forEach(element => { + console.log(element); + }); + // [END automl_translation_list_model_evaluations] } -function getModelEvaluation( +async function getModelEvaluation( projectId, computeRegion, modelId, @@ -272,19 +247,15 @@ function getModelEvaluation( ); // Get complete detail of the model evaluation. - client - .getModelEvaluation({name: modelEvaluationFullId}) - .then(responses => { - const response = responses[0]; - console.log(response); - }) - .catch(err => { - console.error(err); - }); + const [response] = await client.getModelEvaluation({ + name: modelEvaluationFullId, + }); + console.log(response); + // [END automl_translation_get_model_evaluation] } -function deleteModel(projectId, computeRegion, modelId) { +async function deleteModel(projectId, computeRegion, modelId) { // [START automl_translation_delete_model] const automl = require(`@google-cloud/automl`).v1beta1; @@ -301,23 +272,15 @@ function deleteModel(projectId, computeRegion, modelId) { const modelFullId = client.modelPath(projectId, computeRegion, modelId); // Delete a model. - client - .deleteModel({name: modelFullId}) - .then(responses => { - const operation = responses[0]; - return operation.promise(); - }) - .then(responses => { - // The final result of the operation. - if (responses[2].done === true) console.log(`Model deleted.`); - }) - .catch(err => { - console.error(err); - }); + const [operation] = await client.deleteModel({name: modelFullId}); + const operationResponse = await operation.promise(); + // The final result of the operation. + if (operationResponse[2].done === true) console.log(`Model deleted.`); + // [END automl_translation_delete_model] } -function getOperationStatus(operationFullId) { +async function getOperationStatus(operationFullId) { // [START automl_translation_get_operation_status] const automl = require(`@google-cloud/automl`).v1beta1; @@ -329,10 +292,10 @@ function getOperationStatus(operationFullId) { // const operationFullId = `Full name of an operation, eg. “Projects//locations/us-central1/operations/ // Get the latest state of a long-running operation. - client.operationsClient.getOperation(operationFullId).then(responses => { - const response = responses[0]; - console.log(`Operation status: ${response}`); - }); + const [responses] = await client.operationsClient.getOperation( + operationFullId + ); + console.log(`Operation status: ${responses}`); // [END automl_translation_get_operation_status] } @@ -407,32 +370,51 @@ require(`yargs`) `get-operation-status`, `Gets status of current operation`, {}, - opts => getOperationStatus(opts.operationFullId) + async opts => + await getOperationStatus(opts.operationFullId).catch(console.error) ) - .command(`list-models`, `list all Models`, {}, opts => - listModels(opts.projectId, opts.computeRegion, opts.filter) + .command( + `list-models`, + `list all Models`, + {}, + async opts => + await listModels(opts.projectId, opts.computeRegion, opts.filter).catch( + console.error + ) ) .command(`get-model`, `Get a Model`, {}, opts => getModel(opts.projectId, opts.computeRegion, opts.modelId) ) - .command(`list-model-evaluations`, `List model evaluations`, {}, opts => - listModelEvaluations( - opts.projectId, - opts.computeRegion, - opts.modelId, - opts.filter - ) + .command( + `list-model-evaluations`, + `List model evaluations`, + {}, + async opts => + await listModelEvaluations( + opts.projectId, + opts.computeRegion, + opts.modelId, + opts.filter + ).catch(console.error) ) - .command(`get-model-evaluation`, `Get model evaluation`, {}, opts => - getModelEvaluation( - opts.projectId, - opts.computeRegion, - opts.modelId, - opts.modelEvaluationId - ) + .command( + `get-model-evaluation`, + `Get model evaluation`, + {}, + async opts => + await getModelEvaluation( + opts.projectId, + opts.computeRegion, + opts.modelId, + opts.modelEvaluationId + ) ) - .command(`delete-model`, `Delete a Model`, {}, opts => - deleteModel(opts.projectId, opts.computeRegion, opts.modelId) + .command( + `delete-model`, + `Delete a Model`, + {}, + async opts => + await deleteModel(opts.projectId, opts.computeRegion, opts.modelId) ) .example(`node $0 create-model -i "DatasetID" -m "myModelName"`) .example(`node $0 get-operation-status -i "datasetId" -o "OperationFullID"`) diff --git a/translate/automl/automlTranslationPredict.js b/translate/automl/automlTranslationPredict.js index 366660be578..e9e0e38ac74 100755 --- a/translate/automl/automlTranslationPredict.js +++ b/translate/automl/automlTranslationPredict.js @@ -23,7 +23,7 @@ `use strict`; -function predict( +async function predict( projectId, computeRegion, modelId, @@ -68,22 +68,18 @@ function predict( }; } - client - .predict({ - name: modelFullId, - payload: payload, - params: params, - }) - .then(responses => { - const response = responses[0]; - console.log( - `Translated Content: `, - response.payload[0].translation.translatedContent.content - ); - }) - .catch(err => { - console.error(err); - }); + const responses = await client.predict({ + name: modelFullId, + payload: payload, + params: params, + }); + + const response = responses[0]; + console.log( + `Translated Content: `, + response.payload[0].translation.translatedContent.content + ); + // [END automl_translation_predict] } @@ -128,14 +124,18 @@ require(`yargs`) `serve the request. Use false to not use Google translation model.`, }, }) - .command(`predict`, `classify the content`, {}, opts => - predict( - opts.projectId, - opts.computeRegion, - opts.modelId, - opts.filePath, - opts.translationAllowFallback - ) + .command( + `predict`, + `classify the content`, + {}, + async opts => + await predict( + opts.projectId, + opts.computeRegion, + opts.modelId, + opts.filePath, + opts.translationAllowFallback + ) ) .example( `node $0 predict -i "modelId" -f "./resources/testInput.txt" -t "False"` diff --git a/translate/translate.js b/translate/translate.js index bf36c7ffb7a..25f4d4b20bc 100644 --- a/translate/translate.js +++ b/translate/translate.js @@ -15,7 +15,7 @@ 'use strict'; -function detectLanguage(text) { +async function detectLanguage(text) { // [START translate_detect_language] // Imports the Google Cloud client library const {Translate} = require('@google-cloud/translate'); @@ -31,24 +31,17 @@ function detectLanguage(text) { // 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); - }); + let [detections] = await translate.detect(text); + detections = Array.isArray(detections) ? detections : [detections]; + console.log('Detections:'); + detections.forEach(detection => { + console.log(`${detection.input} => ${detection.language}`); + }); + // [END translate_detect_language] } -function listLanguages() { +async function listLanguages() { // [START translate_list_codes] // Imports the Google Cloud client library const {Translate} = require('@google-cloud/translate'); @@ -57,21 +50,14 @@ function listLanguages() { const translate = new 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); - }); + const [languages] = await translate.getLanguages(); + + console.log('Languages:'); + languages.forEach(language => console.log(language)); // [END translate_list_codes] } -function listLanguagesWithTarget(target) { +async function listLanguagesWithTarget(target) { // [START translate_list_language_names] // Imports the Google Cloud client library const {Translate} = require('@google-cloud/translate'); @@ -85,21 +71,15 @@ function listLanguagesWithTarget(target) { // const target = 'The target language for language names, e.g. 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); - }); + const [languages] = await translate.getLanguages(target); + + console.log('Languages:'); + languages.forEach(language => console.log(language)); + // [END translate_list_language_names] } -function translateText(text, target) { +async function translateText(text, target) { // [START translate_translate_text] // Imports the Google Cloud client library const {Translate} = require('@google-cloud/translate'); @@ -116,26 +96,17 @@ function translateText(text, target) { // 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); - }); + let [translations] = await translate.translate(text, target); + translations = Array.isArray(translations) ? translations : [translations]; + console.log('Translations:'); + translations.forEach((translation, i) => { + console.log(`${text[i]} => (${target}) ${translation}`); + }); + // [END translate_translate_text] } -function translateTextWithModel(text, target, model) { +async function translateTextWithModel(text, target, model) { // [START translate_text_with_model] // Imports the Google Cloud client library const {Translate} = require('@google-cloud/translate'); @@ -161,22 +132,12 @@ function translateTextWithModel(text, target, 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); - }); + let [translations] = await translate.translate(text, options); + translations = Array.isArray(translations) ? translations : [translations]; + console.log('Translations:'); + translations.forEach((translation, i) => { + console.log(`${text[i]} => (${target}) ${translation}`); + }); // [END translate_text_with_model] } @@ -186,17 +147,17 @@ require(`yargs`) `detect `, `Detects the language of one or more strings.`, {}, - opts => detectLanguage(opts.text) + async opts => await detectLanguage(opts.text).catch(console.error) ) .command( `list [target]`, `Lists available translation languages. To language names in a language other than English, specify a target language.`, {}, - opts => { + async opts => { if (opts.target) { - listLanguagesWithTarget(opts.target); + await listLanguagesWithTarget(opts.target).catch(console.error); } else { - listLanguages(); + await listLanguages().catch(console.error); } } ) @@ -204,13 +165,17 @@ require(`yargs`) `translate `, `Translates one or more strings into the target language.`, {}, - opts => translateText(opts.text, opts.toLang) + async opts => + await translateText(opts.text, opts.toLang).catch(console.error) ) .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) + async opts => + await translateTextWithModel(opts.text, opts.toLang, opts.model).catch( + console.error + ) ) .example(`node $0 detect "Hello world!"`, `Detects the language of a string.`) .example(