diff --git a/samples/automl/.eslintrc.yml b/samples/automl/.eslintrc.yml index ea05271a..15e704ff 100644 --- a/samples/automl/.eslintrc.yml +++ b/samples/automl/.eslintrc.yml @@ -1,4 +1,6 @@ --- +env: + mocha: true rules: no-console: off node/no-missing-require: off \ No newline at end of file diff --git a/samples/automl/automlVisionDataset.js b/samples/automl/automlVisionDataset.js index 83429c09..3e6931d2 100755 --- a/samples/automl/automlVisionDataset.js +++ b/samples/automl/automlVisionDataset.js @@ -23,7 +23,12 @@ `use strict`; -function createDataset(projectId, computeRegion, datasetName, multiLabel) { +async function createDataset( + projectId, + computeRegion, + datasetName, + multiLabel +) { // [START automl_vision_create_dataset] const automl = require(`@google-cloud/automl`).v1beta1; @@ -58,31 +63,26 @@ function createDataset(projectId, computeRegion, datasetName, multiLabel) { }; // Create a dataset with the dataset metadata in the region. - client - .createDataset({parent: projectLocation, dataset: myDataset}) - .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(`Image Classification type:`); - console.log( - `\t ${dataset.imageClassificationDatasetMetadata.classificationType}` - ); - 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: myDataset, + }); + // 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(`Image Classification type:`); + console.log( + `\t ${dataset.imageClassificationDatasetMetadata.classificationType}` + ); + console.log(`Dataset create time:`); + console.log(`\tseconds: ${dataset.createTime.seconds}`); + console.log(`\tnanos: ${dataset.createTime.nanos}`); // [END automl_vision_create_dataset] } -function listDatasets(projectId, computeRegion, filter) { +async function listDatasets(projectId, computeRegion, filter) { // [START automl_vision_list_datasets] const automl = require(`@google-cloud/automl`).v1beta1; @@ -98,36 +98,30 @@ 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(`Image Classification type:`); - console.log( - `\t`, - dataset.imageClassificationDatasetMetadata.classificationType - ); - console.log(`Dataset create time: `); - console.log(`\tseconds: ${dataset.createTime.seconds}`); - console.log(`\tnanos: ${dataset.createTime.nanos}`); - console.log(`\n`); - }); - }) - .catch(err => { - console.error(err); - }); + const [datasets] = await client.listDatasets({ + parent: projectLocation, + filter: filter, + }); + 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(`Image Classification type:`); + console.log( + `\t`, + dataset.imageClassificationDatasetMetadata.classificationType + ); + console.log(`Dataset create time: `); + console.log(`\tseconds: ${dataset.createTime.seconds}`); + console.log(`\tnanos: ${dataset.createTime.nanos}`); + console.log(`\n`); + }); // [END automl_vision_list_datasets] } -function getDataset(projectId, computeRegion, datasetId) { +async function getDataset(projectId, computeRegion, datasetId) { // [START automl_vision_get_dataset] const automl = require(`@google-cloud/automl`).v1beta1; @@ -144,32 +138,24 @@ 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( - `Classification type: ${ - dataset.imageClassificationDatasetMetadata.classificationType - }` - ); - 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( + `Classification type: ${ + dataset.imageClassificationDatasetMetadata.classificationType + }` + ); + console.log(`Dataset create time: `); + console.log(`\tseconds: ${dataset.createTime.seconds}`); + console.log(`\tnanos: ${dataset.createTime.nanos}`); // [END automl_vision_get_dataset] } -function importData(projectId, computeRegion, datasetId, path) { +async function importData(projectId, computeRegion, datasetId, path) { // [START automl_vision_import_data] const automl = require(`@google-cloud/automl`).v1beta1; @@ -195,26 +181,22 @@ function importData(projectId, computeRegion, datasetId, path) { }; // Import the dataset 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) { - console.log(`Data imported.`); - } - }) - .catch(err => { - console.error(err); - }); + const [operation] = await client.importData({ + name: datasetFullId, + inputConfig: inputConfig, + }); + console.log(`Processing import...`); + + const [, , response] = await operation.promise(); + + // The final result of the operation. + if (response.done) { + console.log(`Data imported.`); + } // [END automl_vision_import_data] } -function exportData(projectId, computeRegion, datasetId, outputUri) { +async function exportData(projectId, computeRegion, datasetId, outputUri) { // [START automl_vision_export_data] const automl = require(`@google-cloud/automl`).v1beta1; @@ -239,26 +221,20 @@ function exportData(projectId, computeRegion, datasetId, outputUri) { }; // Export the data to the output URI. - client - .exportData({name: datasetFullId, outputConfig: outputConfig}) - .then(responses => { - const operation = responses[0]; - console.log(`Processing export...`); - return operation.promise(); - }) - .then(responses => { - // The final result of the operation. - if (responses[2].done) { - console.log(`Data exported.`); - } - }) - .catch(err => { - console.error(err); - }); + const [operation] = await client.exportData({ + name: datasetFullId, + outputConfig: outputConfig, + }); + const [, , response] = await operation.promise(); + + // The final result of the operation. + if (response.done) { + console.log(`Data exported.`); + } // [END automl_vision_export_data] } -function deleteDataset(projectId, computeRegion, datasetId) { +async function deleteDataset(projectId, computeRegion, datasetId) { // [START automl_vision_delete_dataset] const automl = require(`@google-cloud/automl`).v1beta1; @@ -275,21 +251,12 @@ 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) { - console.log(`Dataset deleted.`); - } - }) - .catch(err => { - console.error(err); - }); + const [operation] = await client.deleteDataset({name: datasetFullId}); + const [, , response] = await operation.promise(); + // The final result of the operation. + if (response.done) { + console.log(`Dataset deleted.`); + } // [END automl_vision_delete_dataset] } diff --git a/samples/automl/automlVisionModel.js b/samples/automl/automlVisionModel.js index 1a7c250a..0625bff5 100755 --- a/samples/automl/automlVisionModel.js +++ b/samples/automl/automlVisionModel.js @@ -23,7 +23,7 @@ `use strict`; -function createModel( +async function createModel( projectId, computeRegion, datasetId, @@ -62,44 +62,34 @@ function createModel( }; // 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]; - - // 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, initialApiResponse] = await client.createModel({ + parent: projectLocation, + model: myModel, + }); + console.log(`Training operation name: `, initialApiResponse.name); + console.log(`Training started...`); + const [model] = await operation.promise(); + + // 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_vision_create_model] } -function getOperationStatus(operationFullId) { +async function getOperationStatus(operationFullId) { // [START automl_vision_get_operation_status] const automl = require(`@google-cloud/automl`).v1beta1; @@ -111,14 +101,14 @@ 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 [response] = await client.operationsClient.getOperation( + operationFullId + ); + console.log(`Operation status: `, response); // [END automl_vision_get_operation_status] } -function listModels(projectId, computeRegion, filter) { +async function listModels(projectId, computeRegion, filter) { // [START automl_vision_list_models] const automl = require(`@google-cloud/automl`); @@ -135,77 +125,65 @@ 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}`); - 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}`); - 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}`); + 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}`); + console.log(`\n`); + }); // [END automl_vision_list_models] } -function getModel(projectId, computeRegion, modelId) { +async function getModel(projectId, computeRegion, modelId) { // [START automl_vision_get_model] const automl = require(`@google-cloud/automl`).v1beta1; @@ -222,71 +200,58 @@ 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_vision_get_model] } -function listModelEvaluations(projectId, computeRegion, modelId, filter) { +async function listModelEvaluations(projectId, computeRegion, modelId, filter) { // [START automl_vision_list_model_evaluations] const automl = require(`@google-cloud/automl`).v1beta1; const util = require(`util`); @@ -304,21 +269,17 @@ function listModelEvaluations(projectId, computeRegion, modelId, filter) { const modelFullId = 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]; - elements.forEach(element => { - console.log(util.inspect(element, false, null)); - }); - }) - .catch(err => { - console.error(err); - }); + const [elements] = await client.listModelEvaluations({ + parent: modelFullId, + filter: filter, + }); + elements.forEach(element => { + console.log(util.inspect(element, false, null)); + }); // [END automl_vision_list_model_evaluations] } -function getModelEvaluation( +async function getModelEvaluation( projectId, computeRegion, modelId, @@ -347,19 +308,14 @@ function getModelEvaluation( ); // Get complete detail of the model evaluation. - client - .getModelEvaluation({name: modelEvaluationFullId}) - .then(responses => { - const response = responses[0]; - console.log(util.inspect(response, false, null)); - }) - .catch(err => { - console.error(err); - }); + const [response] = await client.getModelEvaluation({ + name: modelEvaluationFullId, + }); + console.log(util.inspect(response, false, null)); // [END automl_vision_get_model_evaluation] } -function displayEvaluation(projectId, computeRegion, modelId, filter) { +async function displayEvaluation(projectId, computeRegion, modelId, filter) { // [START automl_vision_display_evaluation] const automl = require(`@google-cloud/automl`).v1beta1; const math = require(`mathjs`); @@ -378,82 +334,69 @@ function displayEvaluation(projectId, computeRegion, modelId, filter) { const modelFullId = client.modelPath(projectId, computeRegion, modelId); // List all the model evaluations in the model by applying filter. - client - .listModelEvaluations({parent: modelFullId, filter: filter}) - .then(respond => { - const response = respond[0]; - response.forEach(element => { - // There is evaluation for each class in a model and for overall model. - // Get only the evaluation of overall model. - if (!element.annotationSpecId) { - const modelEvaluationId = element.name.split(`/`).pop(-1); - - // Resource name for the model evaluation. - const modelEvaluationFullId = client.modelEvaluationPath( - projectId, - computeRegion, - modelId, - modelEvaluationId - ); + const [response] = await client.listModelEvaluations({ + parent: modelFullId, + filter: filter, + }); - // Get a model evaluation. - client - .getModelEvaluation({name: modelEvaluationFullId}) - .then(responses => { - const modelEvaluation = responses[0]; - - const classMetrics = - modelEvaluation.classificationEvaluationMetrics; - - const confidenceMetricsEntries = - classMetrics.confidenceMetricsEntry; - - // Showing model score based on threshold of 0.5 - confidenceMetricsEntries.forEach(confidenceMetricsEntry => { - if (confidenceMetricsEntry.confidenceThreshold === 0.5) { - console.log( - `Precision and recall are based on a score threshold of 0.5` - ); - console.log( - `Model Precision: %`, - math.round(confidenceMetricsEntry.precision * 100, 2) - ); - console.log( - `Model Recall: %`, - math.round(confidenceMetricsEntry.recall * 100, 2) - ); - console.log( - `Model F1 score: %`, - math.round(confidenceMetricsEntry.f1Score * 100, 2) - ); - console.log( - `Model Precision@1: %`, - math.round(confidenceMetricsEntry.precisionAt1 * 100, 2) - ); - console.log( - `Model Recall@1: %`, - math.round(confidenceMetricsEntry.recallAt1 * 100, 2) - ); - console.log( - `Model F1 score@1: %`, - math.round(confidenceMetricsEntry.f1ScoreAt1 * 100, 2) - ); - } - }); - }) - .catch(err => { - console.error(err); - }); + response.forEach(async element => { + // There is evaluation for each class in a model and for overall model. + // Get only the evaluation of overall model. + if (!element.annotationSpecId) { + const modelEvaluationId = element.name.split(`/`).pop(-1); + + // Resource name for the model evaluation. + const modelEvaluationFullId = client.modelEvaluationPath( + projectId, + computeRegion, + modelId, + modelEvaluationId + ); + + const [modelEvaluation] = await client.getModelEvaluation({ + name: modelEvaluationFullId, + }); + const classMetrics = modelEvaluation.classificationEvaluationMetrics; + const confidenceMetricsEntries = classMetrics.confidenceMetricsEntry; + + // Showing model score based on threshold of 0.5 + confidenceMetricsEntries.forEach(confidenceMetricsEntry => { + if (confidenceMetricsEntry.confidenceThreshold === 0.5) { + console.log( + `Precision and recall are based on a score threshold of 0.5` + ); + console.log( + `Model Precision: %`, + math.round(confidenceMetricsEntry.precision * 100, 2) + ); + console.log( + `Model Recall: %`, + math.round(confidenceMetricsEntry.recall * 100, 2) + ); + console.log( + `Model F1 score: %`, + math.round(confidenceMetricsEntry.f1Score * 100, 2) + ); + console.log( + `Model Precision@1: %`, + math.round(confidenceMetricsEntry.precisionAt1 * 100, 2) + ); + console.log( + `Model Recall@1: %`, + math.round(confidenceMetricsEntry.recallAt1 * 100, 2) + ); + console.log( + `Model F1 score@1: %`, + math.round(confidenceMetricsEntry.f1ScoreAt1 * 100, 2) + ); } }); - }) - .catch(err => { - console.error(err); - }); + } + }); // [END automl_vision_display_evaluation] } -function deleteModel(projectId, computeRegion, modelId) { +async function deleteModel(projectId, computeRegion, modelId) { // [START automl_vision_delete_model] const automl = require(`@google-cloud/automl`).v1beta1; @@ -470,21 +413,12 @@ 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) { - console.log(`Model deleted.`); - } - }) - .catch(err => { - console.error(err); - }); + const [operation] = await client.deleteModel({name: modelFullId}); + const [, , response] = await operation.promise(); + // The final result of the operation. + if (response.done) { + console.log(`Model deleted.`); + } // [END automl_vision_delete_model] } diff --git a/samples/automl/automlVisionPredict.js b/samples/automl/automlVisionPredict.js index 195cb278..37bfcecf 100755 --- a/samples/automl/automlVisionPredict.js +++ b/samples/automl/automlVisionPredict.js @@ -23,7 +23,13 @@ 'use strict'; -function predict(projectId, computeRegion, modelId, filePath, scoreThreshold) { +async function predict( + projectId, + computeRegion, + modelId, + filePath, + scoreThreshold +) { // [START automl_vision_predict] const automl = require('@google-cloud/automl').v1beta1; const fs = require('fs'); @@ -58,18 +64,16 @@ function predict(projectId, computeRegion, modelId, filePath, scoreThreshold) { // params is additional domain-specific parameters. // currently there is no additional parameters supported. - client - .predict({name: modelFullId, payload: payload, params: params}) - .then(responses => { - console.log(`Prediction results:`); - responses[0].payload.forEach(result => { - console.log(`Predicted class name: ${result.displayName}`); - console.log(`Predicted class score: ${result.classification.score}`); - }); - }) - .catch(err => { - console.error(err); - }); + const [response] = await client.predict({ + name: modelFullId, + payload: payload, + params: params, + }); + console.log(`Prediction results:`); + response.payload.forEach(result => { + console.log(`Predicted class name: ${result.displayName}`); + console.log(`Predicted class score: ${result.classification.score}`); + }); // [END automl_vision_predict] } diff --git a/samples/automl/package.json b/samples/automl/package.json index 42ceab66..011c87ad 100644 --- a/samples/automl/package.json +++ b/samples/automl/package.json @@ -5,7 +5,7 @@ "private": true, "main": "automlVisionDataset.js", "scripts": { - "test": "ava -T 1m --verbose system-test/*.test.js" + "test": "mocha system-test/*.test.js --timeout 600000" }, "engines": { "node": ">=8" @@ -20,7 +20,7 @@ }, "devDependencies": { "@google-cloud/nodejs-repo-tools": "^3.0.0", - "ava": "^0.25.0", + "mocha": "^5.0.0", "proxyquire": "^2.0.1", "sinon": "^7.0.0" } diff --git a/samples/automl/system-test/automlVision.test.js b/samples/automl/system-test/automlVision.test.js index 9bce1adf..51a736fe 100644 --- a/samples/automl/system-test/automlVision.test.js +++ b/samples/automl/system-test/automlVision.test.js @@ -16,7 +16,7 @@ 'use strict'; const path = require(`path`); -const test = require(`ava`); +const assert = require('assert'); const tools = require(`@google-cloud/nodejs-repo-tools`); const cmdDataset = `node automlVisionDataset.js`; const cmdModel = `node automlVisionModel.js`; @@ -27,117 +27,119 @@ const dummyDataSet = `dummyDataSet`; const testModelName = `dummyModel`; const testImgPath = `./resources/`; const sampleImage2 = path.join(testImgPath, `testImage2.jpg`); -test.before(tools.checkCredentials); -// Skipped because it's been taking too long to delete datasets -test.skip(`should create, list, and delete a dataset`, async t => { - // Check to see that this dataset does not yet exist - let output = await tools.runAsync(`${cmdDataset} list-datasets`); - t.false(output.includes(testDataSetName)); - - // Create dataset - output = await tools.runAsync( - `${cmdDataset} create-dataset -n "${testDataSetName}"` - ); - const dataSetId = output - .split(`\n`)[1] - .split(`:`)[1] - .trim(); - t.true(output.includes(`${testDataSetName}`)); - - // Delete dataset - output = await tools.runAsync( - `${cmdDataset} delete-dataset -i "${dataSetId}"` - ); - t.true(output.includes(`Dataset deleted.`)); -}); - -// See : https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/vision/automl/model_test.py -// We make two models running this test, see hard-coded workaround below -test.skip(`should create a dataset, import data, and start making a model`, async t => { - // Check to see that this dataset does not yet exist - let output = await tools.runAsync(`${cmdDataset} list-datasets`); - t.false(output.includes(dummyDataSet)); - - // Create dataset - output = await tools.runAsync( - `${cmdDataset} create-dataset -n "${dummyDataSet}"` - ); - const dataSetId = output - .split(`\n`)[1] - .split(`:`)[1] - .trim(); - t.true(output.includes(`${dummyDataSet}`)); - - // Import Data - output = await tools.runAsync( - `${cmdDataset} import-data -i "${dataSetId}" -p "gs://nodejs-docs-samples-vcm/flowerTraindata20lines.csv"` - ); - t.true(output.includes(`Data imported.`)); - - // Check to make sure model doesn't already exist - output = await tools.runAsync(`${cmdModel} list-models`); - t.false(output.includes(`${testModelName}`)); - - // begin training dataset, getting operation ID for next operation - output = await tools.runAsync( - `${cmdModel} create-model -i "${dataSetId}" -m "${testModelName}" -t "2"` - ); - const operationName = output - .split(`\n`)[0] - .split(`:`)[1] - .split(`/`) - .pop() - .trim(); - t.true(output.includes(`Training started...`)); - - // poll operation status, here confirming that operation is not complete yet - output = await tools.runAsync( - `${cmdModel} get-operation-status -i "${dataSetId}" -o "${operationName}"` - ); - t.true(output.includes(`done: false`)); -}); - -test(`should display evaluation from prexisting model`, async t => { - const flowersModelId = `ICN723541179344731436`; - const flowersDisplayName = `flowersTest`; - - // Confirm dataset exists - let output = await tools.runAsync(`${cmdDataset} list-datasets`); - t.true(output.includes(flowersDisplayName)); - - // List model evaluations, confirm model exists - output = await tools.runAsync( - `${cmdModel} list-model-evaluations -a "${flowersModelId}"` - ); - t.true(output.includes()); - // Display evaluation - output = await tools.runAsync( - `${cmdModel} display-evaluation -a "${flowersModelId}"` - ); - t.true(output.includes(`Model Precision`)); -}); - -test(`should run Prediction from prexisting model`, async t => { - const donotdeleteModelId = `ICN723541179344731436`; - const flowersDisplayName = `flowers`; - - // Confirm dataset exists - let output = await tools.runAsync(`${cmdDataset} list-datasets`); - t.true(output.includes(flowersDisplayName)); - - // List model evaluations, confirm model exists - output = await tools.runAsync( - `${cmdModel} list-model-evaluations -a "${donotdeleteModelId}"` - ); - // Run prediction on 'testImage.jpg' in resources folder - output = await tools.runAsync( - `${cmdPredict} predict -i "${donotdeleteModelId}" -f "${sampleImage2}" -s "0.5"` - ); - t.true(output.includes(`dandelion`)); -}); -// List datasets -test(`should list datasets`, async t => { - const output = await tools.runAsync(`${cmdDataset} list-datasets`); - t.true(output.includes(`List of datasets:`)); +describe(`auto ml vision`, () => { + before(tools.checkCredentials); + + it.skip(`should create, list, and delete a dataset`, async () => { + // Check to see that this dataset does not yet exist + let output = await tools.runAsync(`${cmdDataset} list-datasets`); + assert.strictEqual(output.includes(testDataSetName), false); + + // Create dataset + output = await tools.runAsync( + `${cmdDataset} create-dataset -n "${testDataSetName}"` + ); + const dataSetId = output + .split(`\n`)[1] + .split(`:`)[1] + .trim(); + assert.ok(output.includes(`${testDataSetName}`)); + + // Delete dataset + output = await tools.runAsync( + `${cmdDataset} delete-dataset -i "${dataSetId}"` + ); + assert.ok(output.includes(`Dataset deleted.`)); + }); + + // See : https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/vision/automl/model_test.py + // We make two models running this test, see hard-coded workaround below + it.skip(`should create a dataset, import data, and start making a model`, async () => { + // Check to see that this dataset does not yet exist + let output = await tools.runAsync(`${cmdDataset} list-datasets`); + assert.strictEqual(output.includes(dummyDataSet), false); + + // Create dataset + output = await tools.runAsync( + `${cmdDataset} create-dataset -n "${dummyDataSet}"` + ); + const dataSetId = output + .split(`\n`)[1] + .split(`:`)[1] + .trim(); + assert.ok(output.includes(`${dummyDataSet}`)); + + // Import Data + output = await tools.runAsync( + `${cmdDataset} import-data -i "${dataSetId}" -p "gs://nodejs-docs-samples-vcm/flowerTraindata20lines.csv"` + ); + assert.ok(output.includes(`Data imported.`)); + + // Check to make sure model doesn't already exist + output = await tools.runAsync(`${cmdModel} list-models`); + assert.strictEqual(output.includes(`${testModelName}`), false); + + // begin training dataset, getting operation ID for next operation + output = await tools.runAsync(` + ${cmdModel} create-model -i "${dataSetId}" -m "${testModelName}" -t "2"`); + const operationName = output + .split(`\n`)[0] + .split(`:`)[1] + .split(`/`) + .pop() + .trim(); + assert.ok(output.includes(`Training started...`)); + + // poll operation status, here confirming that operation is not complete yet + output = await tools.runAsync( + `${cmdModel} get-operation-status -i "${dataSetId}" -o "${operationName}"` + ); + assert.ok(output.includes(`done: false`)); + }); + + it(`should display evaluation from prexisting model`, async () => { + const flowersModelId = `ICN723541179344731436`; + const flowersDisplayName = `flowersTest`; + + // Confirm dataset exists + let output = await tools.runAsync(`${cmdDataset} list-datasets`); + assert.ok(output.includes(flowersDisplayName)); + + // List model evaluations, confirm model exists + output = await tools.runAsync( + `${cmdModel} list-model-evaluations -a "${flowersModelId}"` + ); + assert.ok(output.includes()); + // Display evaluation + output = await tools.runAsync( + `${cmdModel} display-evaluation -a "${flowersModelId}"` + ); + assert.ok(output.includes(`Model Precision`)); + }); + + it(`should run Prediction from prexisting model`, async () => { + const donotdeleteModelId = `ICN723541179344731436`; + const flowersDisplayName = `flowers`; + + // Confirm dataset exists + let output = await tools.runAsync(`${cmdDataset} list-datasets`); + assert.ok(output.includes(flowersDisplayName)); + + // List model evaluations, confirm model exists + output = await tools.runAsync( + `${cmdModel} list-model-evaluations -a "${donotdeleteModelId}"` + ); + // Run prediction on 'testImage.jpg' in resources folder + output = await tools.runAsync( + `${cmdPredict} predict -i "${donotdeleteModelId}" -f "${sampleImage2}" -s "0.5"` + ); + assert.ok(output.includes(`dandelion`)); + }); + + // List datasets + it(`should list datasets`, async () => { + const output = await tools.runAsync(`${cmdDataset} list-datasets`); + assert.ok(output.includes(`List of datasets:`)); + }); }); diff --git a/samples/detect.js b/samples/detect.js index 4dc6e55e..ad3e3bd5 100644 --- a/samples/detect.js +++ b/samples/detect.js @@ -15,7 +15,7 @@ 'use strict'; -function detectFaces(fileName) { +async function detectFaces(fileName) { // [START vision_face_detection] // Imports the Google Cloud client library const vision = require('@google-cloud/vision'); @@ -28,27 +28,20 @@ function detectFaces(fileName) { */ // const fileName = 'Local image file, e.g. /path/to/image.png'; - client - .faceDetection(fileName) - .then(results => { - const faces = results[0].faceAnnotations; - - console.log('Faces:'); - faces.forEach((face, i) => { - console.log(` Face #${i + 1}:`); - console.log(` Joy: ${face.joyLikelihood}`); - console.log(` Anger: ${face.angerLikelihood}`); - console.log(` Sorrow: ${face.sorrowLikelihood}`); - console.log(` Surprise: ${face.surpriseLikelihood}`); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.faceDetection(fileName); + const faces = result.faceAnnotations; + console.log('Faces:'); + faces.forEach((face, i) => { + console.log(` Face #${i + 1}:`); + console.log(` Joy: ${face.joyLikelihood}`); + console.log(` Anger: ${face.angerLikelihood}`); + console.log(` Sorrow: ${face.sorrowLikelihood}`); + console.log(` Surprise: ${face.surpriseLikelihood}`); + }); // [END vision_face_detection] } -function detectFacesGCS(bucketName, fileName) { +async function detectFacesGCS(bucketName, fileName) { // [START vision_face_detection_gcs] // Imports the Google Cloud client libraries const vision = require('@google-cloud/vision'); @@ -63,27 +56,20 @@ function detectFacesGCS(bucketName, fileName) { // const fileName = 'Path to file within bucket, e.g. path/to/image.png'; // Performs face detection on the gcs file - client - .faceDetection(`gs://${bucketName}/${fileName}`) - .then(results => { - const faces = results[0].faceAnnotations; - - console.log('Faces:'); - faces.forEach((face, i) => { - console.log(` Face #${i + 1}:`); - console.log(` Joy: ${face.joyLikelihood}`); - console.log(` Anger: ${face.angerLikelihood}`); - console.log(` Sorrow: ${face.sorrowLikelihood}`); - console.log(` Surprise: ${face.surpriseLikelihood}`); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.faceDetection(`gs://${bucketName}/${fileName}`); + const faces = result.faceAnnotations; + console.log('Faces:'); + faces.forEach((face, i) => { + console.log(` Face #${i + 1}:`); + console.log(` Joy: ${face.joyLikelihood}`); + console.log(` Anger: ${face.angerLikelihood}`); + console.log(` Sorrow: ${face.sorrowLikelihood}`); + console.log(` Surprise: ${face.surpriseLikelihood}`); + }); // [END vision_face_detection_gcs] } -function detectLabels(fileName) { +async function detectLabels(fileName) { // [START vision_label_detection] // Imports the Google Cloud client library const vision = require('@google-cloud/vision'); @@ -97,20 +83,14 @@ function detectLabels(fileName) { // const fileName = 'Local image file, e.g. /path/to/image.png'; // Performs label detection on the local file - client - .labelDetection(fileName) - .then(results => { - const labels = results[0].labelAnnotations; - console.log('Labels:'); - labels.forEach(label => console.log(label.description)); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.labelDetection(fileName); + const labels = result.labelAnnotations; + console.log('Labels:'); + labels.forEach(label => console.log(label.description)); // [END vision_label_detection] } -function detectLabelsGCS(bucketName, fileName) { +async function detectLabelsGCS(bucketName, fileName) { // [START vision_label_detection_gcs] // Imports the Google Cloud client libraries const vision = require('@google-cloud/vision'); @@ -125,20 +105,16 @@ function detectLabelsGCS(bucketName, fileName) { // const fileName = 'Path to file within bucket, e.g. path/to/image.png'; // Performs label detection on the gcs file - client - .labelDetection(`gs://${bucketName}/${fileName}`) - .then(results => { - const labels = results[0].labelAnnotations; - console.log('Labels:'); - labels.forEach(label => console.log(label.description)); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.labelDetection( + `gs://${bucketName}/${fileName}` + ); + const labels = result.labelAnnotations; + console.log('Labels:'); + labels.forEach(label => console.log(label.description)); // [END vision_label_detection_gcs] } -function detectLandmarks(fileName) { +async function detectLandmarks(fileName) { // [START vision_landmark_detection] const vision = require('@google-cloud/vision'); @@ -151,20 +127,14 @@ function detectLandmarks(fileName) { // const fileName = 'Local image file, e.g. /path/to/image.png'; // Performs landmark detection on the local file - client - .landmarkDetection(fileName) - .then(results => { - const landmarks = results[0].landmarkAnnotations; - console.log('Landmarks:'); - landmarks.forEach(landmark => console.log(landmark)); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.landmarkDetection(fileName); + const landmarks = result.landmarkAnnotations; + console.log('Landmarks:'); + landmarks.forEach(landmark => console.log(landmark)); // [END vision_landmark_detection] } -function detectLandmarksGCS(bucketName, fileName) { +async function detectLandmarksGCS(bucketName, fileName) { // [START vision_landmark_detection_gcs] // Imports the Google Cloud client libraries const vision = require('@google-cloud/vision'); @@ -179,20 +149,16 @@ function detectLandmarksGCS(bucketName, fileName) { // const fileName = 'Path to file within bucket, e.g. path/to/image.png'; // Performs landmark detection on the gcs file - client - .landmarkDetection(`gs://${bucketName}/${fileName}`) - .then(results => { - const landmarks = results[0].landmarkAnnotations; - console.log('Landmarks:'); - landmarks.forEach(landmark => console.log(landmark)); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.landmarkDetection( + `gs://${bucketName}/${fileName}` + ); + const landmarks = result.landmarkAnnotations; + console.log('Landmarks:'); + landmarks.forEach(landmark => console.log(landmark)); // [END vision_landmark_detection_gcs] } -function detectText(fileName) { +async function detectText(fileName) { // [START vision_text_detection] const vision = require('@google-cloud/vision'); @@ -205,20 +171,14 @@ function detectText(fileName) { // const fileName = 'Local image file, e.g. /path/to/image.png'; // Performs text detection on the local file - client - .textDetection(fileName) - .then(results => { - const detections = results[0].textAnnotations; - console.log('Text:'); - detections.forEach(text => console.log(text)); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.textDetection(fileName); + const detections = result.textAnnotations; + console.log('Text:'); + detections.forEach(text => console.log(text)); // [END vision_text_detection] } -function detectTextGCS(bucketName, fileName) { +async function detectTextGCS(bucketName, fileName) { // [START vision_text_detection_gcs] // Imports the Google Cloud client libraries const vision = require('@google-cloud/vision'); @@ -233,20 +193,14 @@ function detectTextGCS(bucketName, fileName) { // const fileName = 'Path to file within bucket, e.g. path/to/image.png'; // Performs text detection on the gcs file - client - .textDetection(`gs://${bucketName}/${fileName}`) - .then(results => { - const detections = results[0].textAnnotations; - console.log('Text:'); - detections.forEach(text => console.log(text)); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.textDetection(`gs://${bucketName}/${fileName}`); + const detections = result.textAnnotations; + console.log('Text:'); + detections.forEach(text => console.log(text)); // [END vision_text_detection_gcs] } -function detectLogos(fileName) { +async function detectLogos(fileName) { // [START vision_logo_detection] const vision = require('@google-cloud/vision'); @@ -259,20 +213,14 @@ function detectLogos(fileName) { // const fileName = 'Local image file, e.g. /path/to/image.png'; // Performs logo detection on the local file - client - .logoDetection(fileName) - .then(results => { - const logos = results[0].logoAnnotations; - console.log('Logos:'); - logos.forEach(logo => console.log(logo)); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.logoDetection(fileName); + const logos = result.logoAnnotations; + console.log('Logos:'); + logos.forEach(logo => console.log(logo)); // [END vision_logo_detection] } -function detectLogosGCS(bucketName, fileName) { +async function detectLogosGCS(bucketName, fileName) { // [START vision_logo_detection_gcs] // Imports the Google Cloud client libraries const vision = require('@google-cloud/vision'); @@ -287,20 +235,14 @@ function detectLogosGCS(bucketName, fileName) { // const fileName = 'Path to file within bucket, e.g. path/to/image.png'; // Performs logo detection on the gcs file - client - .logoDetection(`gs://${bucketName}/${fileName}`) - .then(results => { - const logos = results[0].logoAnnotations; - console.log('Logos:'); - logos.forEach(logo => console.log(logo)); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.logoDetection(`gs://${bucketName}/${fileName}`); + const logos = result.logoAnnotations; + console.log('Logos:'); + logos.forEach(logo => console.log(logo)); // [END vision_logo_detection_gcs] } -function detectProperties(fileName) { +async function detectProperties(fileName) { // [START vision_image_property_detection] const vision = require('@google-cloud/vision'); @@ -313,20 +255,13 @@ function detectProperties(fileName) { // const fileName = 'Local image file, e.g. /path/to/image.png'; // Performs property detection on the local file - client - .imageProperties(fileName) - .then(results => { - const properties = results[0].imagePropertiesAnnotation; - const colors = properties.dominantColors.colors; - colors.forEach(color => console.log(color)); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.imageProperties(fileName); + const colors = result.imagePropertiesAnnotation.dominantColors.colors; + colors.forEach(color => console.log(color)); // [END vision_image_property_detection] } -function detectPropertiesGCS(bucketName, fileName) { +async function detectPropertiesGCS(bucketName, fileName) { // [START vision_image_property_detection_gcs] // Imports the Google Cloud client libraries const vision = require('@google-cloud/vision'); @@ -341,20 +276,15 @@ function detectPropertiesGCS(bucketName, fileName) { // const fileName = 'Path to file within bucket, e.g. path/to/image.png'; // Performs property detection on the gcs file - client - .imageProperties(`gs://${bucketName}/${fileName}`) - .then(results => { - const properties = results[0].imagePropertiesAnnotation; - const colors = properties.dominantColors.colors; - colors.forEach(color => console.log(color)); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.imageProperties( + `gs://${bucketName}/${fileName}` + ); + const colors = result.imagePropertiesAnnotation.dominantColors.colors; + colors.forEach(color => console.log(color)); // [END vision_image_property_detection_gcs] } -function detectSafeSearch(fileName) { +async function detectSafeSearch(fileName) { // [START vision_safe_search_detection] const vision = require('@google-cloud/vision'); @@ -367,25 +297,18 @@ function detectSafeSearch(fileName) { // const fileName = 'Local image file, e.g. /path/to/image.png'; // Performs safe search detection on the local file - client - .safeSearchDetection(fileName) - .then(results => { - const detections = results[0].safeSearchAnnotation; - - console.log('Safe search:'); - console.log(`Adult: ${detections.adult}`); - console.log(`Medical: ${detections.medical}`); - console.log(`Spoof: ${detections.spoof}`); - console.log(`Violence: ${detections.violence}`); - console.log(`Racy: ${detections.racy}`); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.safeSearchDetection(fileName); + const detections = result.safeSearchAnnotation; + console.log('Safe search:'); + console.log(`Adult: ${detections.adult}`); + console.log(`Medical: ${detections.medical}`); + console.log(`Spoof: ${detections.spoof}`); + console.log(`Violence: ${detections.violence}`); + console.log(`Racy: ${detections.racy}`); // [END vision_safe_search_detection] } -function detectSafeSearchGCS(bucketName, fileName) { +async function detectSafeSearchGCS(bucketName, fileName) { // [START vision_safe_search_detection_gcs] // Imports the Google Cloud client libraries const vision = require('@google-cloud/vision'); @@ -400,23 +323,18 @@ function detectSafeSearchGCS(bucketName, fileName) { // const fileName = 'Path to file within bucket, e.g. path/to/image.png'; // Performs safe search property detection on the remote file - client - .safeSearchDetection(`gs://${bucketName}/${fileName}`) - .then(results => { - const detections = results[0].safeSearchAnnotation; - - console.log(`Adult: ${detections.adult}`); - console.log(`Spoof: ${detections.spoof}`); - console.log(`Medical: ${detections.medical}`); - console.log(`Violence: ${detections.violence}`); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.safeSearchDetection( + `gs://${bucketName}/${fileName}` + ); + const detections = result.safeSearchAnnotation; + console.log(`Adult: ${detections.adult}`); + console.log(`Spoof: ${detections.spoof}`); + console.log(`Medical: ${detections.medical}`); + console.log(`Violence: ${detections.violence}`); // [END vision_safe_search_detection_gcs] } -function detectCropHints(fileName) { +async function detectCropHints(fileName) { // [START vision_crop_hint_detection] // Imports the Google Cloud client library @@ -431,25 +349,18 @@ function detectCropHints(fileName) { // const fileName = 'Local image file, e.g. /path/to/image.png'; // Find crop hints for the local file - client - .cropHints(fileName) - .then(results => { - const cropHints = results[0].cropHintsAnnotation; - - cropHints.cropHints.forEach((hintBounds, hintIdx) => { - console.log(`Crop Hint ${hintIdx}:`); - hintBounds.boundingPoly.vertices.forEach((bound, boundIdx) => { - console.log(` Bound ${boundIdx}: (${bound.x}, ${bound.y})`); - }); - }); - }) - .catch(err => { - console.error('ERROR:', err); + const [result] = await client.cropHints(fileName); + const cropHints = result.cropHintsAnnotation; + cropHints.cropHints.forEach((hintBounds, hintIdx) => { + console.log(`Crop Hint ${hintIdx}:`); + hintBounds.boundingPoly.vertices.forEach((bound, boundIdx) => { + console.log(` Bound ${boundIdx}: (${bound.x}, ${bound.y})`); }); + }); // [END vision_crop_hint_detection] } -function detectCropHintsGCS(bucketName, fileName) { +async function detectCropHintsGCS(bucketName, fileName) { // [START vision_crop_hint_detection_gcs] // Imports the Google Cloud client libraries @@ -465,25 +376,18 @@ function detectCropHintsGCS(bucketName, fileName) { // const fileName = 'Path to file within bucket, e.g. path/to/image.png'; // Find crop hints for the remote file - client - .cropHints(`gs://${bucketName}/${fileName}`) - .then(results => { - const cropHints = results[0].cropHintsAnnotation; - - cropHints.cropHints.forEach((hintBounds, hintIdx) => { - console.log(`Crop Hint ${hintIdx}:`); - hintBounds.boundingPoly.vertices.forEach((bound, boundIdx) => { - console.log(` Bound ${boundIdx}: (${bound.x}, ${bound.y})`); - }); - }); - }) - .catch(err => { - console.error('ERROR:', err); + const [result] = await client.cropHints(`gs://${bucketName}/${fileName}`); + const cropHints = result.cropHintsAnnotation; + cropHints.cropHints.forEach((hintBounds, hintIdx) => { + console.log(`Crop Hint ${hintIdx}:`); + hintBounds.boundingPoly.vertices.forEach((bound, boundIdx) => { + console.log(` Bound ${boundIdx}: (${bound.x}, ${bound.y})`); }); + }); // [END vision_crop_hint_detection_gcs] } -function detectWeb(fileName) { +async function detectWeb(fileName) { // [START vision_web_detection] // Imports the Google Cloud client library @@ -498,55 +402,48 @@ function detectWeb(fileName) { // const fileName = 'Local image file, e.g. /path/to/image.png'; // Detect similar images on the web to a local file - client - .webDetection(fileName) - .then(results => { - const webDetection = results[0].webDetection; - - if (webDetection.fullMatchingImages.length) { - console.log( - `Full matches found: ${webDetection.fullMatchingImages.length}` - ); - webDetection.fullMatchingImages.forEach(image => { - console.log(` URL: ${image.url}`); - console.log(` Score: ${image.score}`); - }); - } - - if (webDetection.partialMatchingImages.length) { - console.log( - `Partial matches found: ${webDetection.partialMatchingImages.length}` - ); - webDetection.partialMatchingImages.forEach(image => { - console.log(` URL: ${image.url}`); - console.log(` Score: ${image.score}`); - }); - } + const [result] = await client.webDetection(fileName); + const webDetection = result.webDetection; + if (webDetection.fullMatchingImages.length) { + console.log( + `Full matches found: ${webDetection.fullMatchingImages.length}` + ); + webDetection.fullMatchingImages.forEach(image => { + console.log(` URL: ${image.url}`); + console.log(` Score: ${image.score}`); + }); + } + + if (webDetection.partialMatchingImages.length) { + console.log( + `Partial matches found: ${webDetection.partialMatchingImages.length}` + ); + webDetection.partialMatchingImages.forEach(image => { + console.log(` URL: ${image.url}`); + console.log(` Score: ${image.score}`); + }); + } - if (webDetection.webEntities.length) { - console.log(`Web entities found: ${webDetection.webEntities.length}`); - webDetection.webEntities.forEach(webEntity => { - console.log(` Description: ${webEntity.description}`); - console.log(` Score: ${webEntity.score}`); - }); - } - - if (webDetection.bestGuessLabels.length) { - console.log( - `Best guess labels found: ${webDetection.bestGuessLabels.length}` - ); - webDetection.bestGuessLabels.forEach(label => { - console.log(` Label: ${label.label}`); - }); - } - }) - .catch(err => { - console.error('ERROR:', err); + if (webDetection.webEntities.length) { + console.log(`Web entities found: ${webDetection.webEntities.length}`); + webDetection.webEntities.forEach(webEntity => { + console.log(` Description: ${webEntity.description}`); + console.log(` Score: ${webEntity.score}`); + }); + } + + if (webDetection.bestGuessLabels.length) { + console.log( + `Best guess labels found: ${webDetection.bestGuessLabels.length}` + ); + webDetection.bestGuessLabels.forEach(label => { + console.log(` Label: ${label.label}`); }); + } // [END vision_web_detection] } -function detectWebGCS(bucketName, fileName) { +async function detectWebGCS(bucketName, fileName) { // [START vision_web_detection_gcs] // Imports the Google Cloud client libraries @@ -562,55 +459,48 @@ function detectWebGCS(bucketName, fileName) { // const fileName = 'Path to file within bucket, e.g. path/to/image.png'; // Detect similar images on the web to a remote file - client - .webDetection(`gs://${bucketName}/${fileName}`) - .then(results => { - const webDetection = results[0].webDetection; - - if (webDetection.fullMatchingImages.length) { - console.log( - `Full matches found: ${webDetection.fullMatchingImages.length}` - ); - webDetection.fullMatchingImages.forEach(image => { - console.log(` URL: ${image.url}`); - console.log(` Score: ${image.score}`); - }); - } - - if (webDetection.partialMatchingImages.length) { - console.log( - `Partial matches found: ${webDetection.partialMatchingImages.length}` - ); - webDetection.partialMatchingImages.forEach(image => { - console.log(` URL: ${image.url}`); - console.log(` Score: ${image.score}`); - }); - } + const [result] = await client.webDetection(`gs://${bucketName}/${fileName}`); + const webDetection = result.webDetection; + if (webDetection.fullMatchingImages.length) { + console.log( + `Full matches found: ${webDetection.fullMatchingImages.length}` + ); + webDetection.fullMatchingImages.forEach(image => { + console.log(` URL: ${image.url}`); + console.log(` Score: ${image.score}`); + }); + } + + if (webDetection.partialMatchingImages.length) { + console.log( + `Partial matches found: ${webDetection.partialMatchingImages.length}` + ); + webDetection.partialMatchingImages.forEach(image => { + console.log(` URL: ${image.url}`); + console.log(` Score: ${image.score}`); + }); + } - if (webDetection.webEntities.length) { - console.log(`Web entities found: ${webDetection.webEntities.length}`); - webDetection.webEntities.forEach(webEntity => { - console.log(` Description: ${webEntity.description}`); - console.log(` Score: ${webEntity.score}`); - }); - } - - if (webDetection.bestGuessLabels.length) { - console.log( - `Best guess labels found: ${webDetection.bestGuessLabels.length}` - ); - webDetection.bestGuessLabels.forEach(label => { - console.log(` Label: ${label.label}`); - }); - } - }) - .catch(err => { - console.error('ERROR:', err); + if (webDetection.webEntities.length) { + console.log(`Web entities found: ${webDetection.webEntities.length}`); + webDetection.webEntities.forEach(webEntity => { + console.log(` Description: ${webEntity.description}`); + console.log(` Score: ${webEntity.score}`); }); + } + + if (webDetection.bestGuessLabels.length) { + console.log( + `Best guess labels found: ${webDetection.bestGuessLabels.length}` + ); + webDetection.bestGuessLabels.forEach(label => { + console.log(` Label: ${label.label}`); + }); + } // [END vision_web_detection_gcs] } -function detectWebGeo(fileName) { +async function detectWebGeo(fileName) { // [START vision_web_detection_include_geo] // Imports the Google Cloud client library const vision = require('@google-cloud/vision'); @@ -637,23 +527,16 @@ function detectWebGeo(fileName) { }; // Detect similar images on the web to a local file - client - .webDetection(request) - .then(results => { - const webDetection = results[0].webDetection; - - webDetection.webEntities.forEach(entity => { - console.log(`Score: ${entity.score}`); - console.log(`Description: ${entity.description}`); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.webDetection(request); + const webDetection = result.webDetection; + webDetection.webEntities.forEach(entity => { + console.log(`Score: ${entity.score}`); + console.log(`Description: ${entity.description}`); + }); // [END vision_web_detection_include_geo] } -function detectWebGeoGCS(bucketName, fileName) { +async function detectWebGeoGCS(bucketName, fileName) { // [START vision_web_detection_include_geo_gcs] // Imports the Google Cloud client library const vision = require('@google-cloud/vision'); @@ -681,23 +564,16 @@ function detectWebGeoGCS(bucketName, fileName) { }; // Detect similar images on the web to a remote file - client - .webDetection(request) - .then(results => { - const webDetection = results[0].webDetection; - - webDetection.webEntities.forEach(entity => { - console.log(`Score: ${entity.score}`); - console.log(`Description: ${entity.description}`); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.webDetection(request); + const webDetection = result.webDetection; + webDetection.webEntities.forEach(entity => { + console.log(`Score: ${entity.score}`); + console.log(`Description: ${entity.description}`); + }); // [END vision_web_detection_include_geo_gcs] } -function detectFulltext(fileName) { +async function detectFulltext(fileName) { // [START vision_fulltext_detection] // Imports the Google Cloud client library @@ -712,37 +588,30 @@ function detectFulltext(fileName) { // const fileName = 'Local image file, e.g. /path/to/image.png'; // Read a local image as a text document - client - .documentTextDetection(fileName) - .then(results => { - const fullTextAnnotation = results[0].fullTextAnnotation; - console.log(`Full text: ${fullTextAnnotation.text}`); - - fullTextAnnotation.pages.forEach(page => { - page.blocks.forEach(block => { - console.log(`Block confidence: ${block.confidence}`); - block.paragraphs.forEach(paragraph => { - console.log(`Paragraph confidence: ${paragraph.confidence}`); - paragraph.words.forEach(word => { - const wordText = word.symbols.map(s => s.text).join(''); - console.log(`Word text: ${wordText}`); - console.log(`Word confidence: ${word.confidence}`); - word.symbols.forEach(symbol => { - console.log(`Symbol text: ${symbol.text}`); - console.log(`Symbol confidence: ${symbol.confidence}`); - }); - }); + const [result] = await client.documentTextDetection(fileName); + const fullTextAnnotation = result.fullTextAnnotation; + console.log(`Full text: ${fullTextAnnotation.text}`); + fullTextAnnotation.pages.forEach(page => { + page.blocks.forEach(block => { + console.log(`Block confidence: ${block.confidence}`); + block.paragraphs.forEach(paragraph => { + console.log(`Paragraph confidence: ${paragraph.confidence}`); + paragraph.words.forEach(word => { + const wordText = word.symbols.map(s => s.text).join(''); + console.log(`Word text: ${wordText}`); + console.log(`Word confidence: ${word.confidence}`); + word.symbols.forEach(symbol => { + console.log(`Symbol text: ${symbol.text}`); + console.log(`Symbol confidence: ${symbol.confidence}`); }); }); }); - }) - .catch(err => { - console.error('ERROR:', err); }); + }); // [END vision_fulltext_detection] } -function detectFulltextGCS(bucketName, fileName) { +async function detectFulltextGCS(bucketName, fileName) { // [START vision_fulltext_detection_gcs] // Imports the Google Cloud client libraries @@ -758,19 +627,15 @@ function detectFulltextGCS(bucketName, fileName) { // const fileName = 'Path to file within bucket, e.g. path/to/image.png'; // Read a remote image as a text document - client - .documentTextDetection(`gs://${bucketName}/${fileName}`) - .then(results => { - const fullTextAnnotation = results[0].fullTextAnnotation; - console.log(fullTextAnnotation.text); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.documentTextDetection( + `gs://${bucketName}/${fileName}` + ); + const fullTextAnnotation = result.fullTextAnnotation; + console.log(fullTextAnnotation.text); // [END vision_fulltext_detection_gcs] } -function detectPdfText(bucketName, fileName) { +async function detectPdfText(bucketName, fileName) { // [START vision_text_detection_pdf_gcs] // Imports the Google Cloud client libraries @@ -813,25 +678,15 @@ function detectPdfText(bucketName, fileName) { ], }; - client - .asyncBatchAnnotateFiles(request) - .then(results => { - const operation = results[0]; - // Get a Promise representation of the final result of the job - return operation.promise(); - }) - .then(filesResponse => { - const destinationUri = - filesResponse[0].responses[0].outputConfig.gcsDestination.uri; - console.log('Json saved to: ' + destinationUri); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [operation] = await client.asyncBatchAnnotateFiles(request); + const [filesResponse] = await operation.promise(); + const destinationUri = + filesResponse.responses[0].outputConfig.gcsDestination.uri; + console.log('Json saved to: ' + destinationUri); // [END vision_text_detection_pdf_gcs] } -function localizeObjects(fileName) { +async function localizeObjects(fileName) { // [START vision_localize_objects] // Imports the Google Cloud client libraries const vision = require('@google-cloud/vision'); @@ -848,24 +703,18 @@ function localizeObjects(fileName) { image: {content: fs.readFileSync(fileName)}, }; - client - .objectLocalization(request) - .then(results => { - const objects = results[0].localizedObjectAnnotations; - objects.forEach(object => { - console.log(`Name: ${object.name}`); - console.log(`Confidence: ${object.score}`); - const vertices = object.boundingPoly.normalizedVertices; - vertices.forEach(v => console.log(`x: ${v.x}, y:${v.y}`)); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.objectLocalization(request); + const objects = result.localizedObjectAnnotations; + objects.forEach(object => { + console.log(`Name: ${object.name}`); + console.log(`Confidence: ${object.score}`); + const vertices = object.boundingPoly.normalizedVertices; + vertices.forEach(v => console.log(`x: ${v.x}, y:${v.y}`)); + }); // [END vision_localize_objects] } -function localizeObjectsGCS(gcsUri) { +async function localizeObjectsGCS(gcsUri) { // [START vision_localize_objects_gcs] // Imports the Google Cloud client libraries const vision = require('@google-cloud/vision'); @@ -878,20 +727,14 @@ function localizeObjectsGCS(gcsUri) { */ // const gcsUri = `gs://bucket/bucketImage.png`; - client - .objectLocalization(gcsUri) - .then(results => { - const objects = results[0].localizedObjectAnnotations; - objects.forEach(object => { - console.log(`Name: ${object.name}`); - console.log(`Confidence: ${object.score}`); - const veritices = object.boundingPoly.normalizedVertices; - veritices.forEach(v => console.log(`x: ${v.x}, y:${v.y}`)); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.objectLocalization(gcsUri); + const objects = result.localizedObjectAnnotations; + objects.forEach(object => { + console.log(`Name: ${object.name}`); + console.log(`Confidence: ${object.score}`); + const veritices = object.boundingPoly.normalizedVertices; + veritices.forEach(v => console.log(`x: ${v.x}, y:${v.y}`)); + }); // [END vision_localize_objects_gcs] } diff --git a/samples/detect.v1p1beta1.js b/samples/detect.v1p1beta1.js index 86c25057..6f6c647d 100644 --- a/samples/detect.v1p1beta1.js +++ b/samples/detect.v1p1beta1.js @@ -15,7 +15,7 @@ 'use strict'; -function detectFulltext(fileName) { +async function detectFulltext(fileName) { // [START vision_detect_document] // Imports the Google Cloud client libraries const vision = require('@google-cloud/vision').v1p1beta1; @@ -29,45 +29,39 @@ function detectFulltext(fileName) { // const fileName = 'Local image file, e.g. /path/to/image.png'; // Performs label detection on the local file - client - .textDetection(fileName) - .then(results => { - const pages = results[0].fullTextAnnotation.pages; - pages.forEach(page => { - page.blocks.forEach(block => { - const blockWords = []; - block.paragraphs.forEach(paragraph => { - paragraph.words.forEach(word => blockWords.push(word)); - console.log(`Paragraph confidence: ${paragraph.confidence}`); - }); - - let blockText = ''; - const blockSymbols = []; - blockWords.forEach(word => { - word.symbols.forEach(symbol => blockSymbols.push(symbol)); - let wordText = ''; - word.symbols.forEach(symbol => { - wordText = wordText + symbol.text; - console.log(`Symbol text: ${symbol.text}`); - console.log(`Symbol confidence: ${symbol.confidence}`); - }); - console.log(`Word text: ${wordText}`); - console.log(`Word confidence: ${word.confidence}`); - blockText = blockText + ` ${wordText}`; - }); + const [result] = await client.textDetection(fileName); + const pages = result.fullTextAnnotation.pages; + pages.forEach(page => { + page.blocks.forEach(block => { + const blockWords = []; + block.paragraphs.forEach(paragraph => { + paragraph.words.forEach(word => blockWords.push(word)); + console.log(`Paragraph confidence: ${paragraph.confidence}`); + }); - console.log(`Block text: ${blockText}`); - console.log(`Block confidence: ${block.confidence}`); + let blockText = ''; + const blockSymbols = []; + blockWords.forEach(word => { + word.symbols.forEach(symbol => blockSymbols.push(symbol)); + let wordText = ''; + word.symbols.forEach(symbol => { + wordText = wordText + symbol.text; + console.log(`Symbol text: ${symbol.text}`); + console.log(`Symbol confidence: ${symbol.confidence}`); }); + console.log(`Word text: ${wordText}`); + console.log(`Word confidence: ${word.confidence}`); + blockText = blockText + ` ${wordText}`; }); - }) - .catch(err => { - console.error('ERROR:', err); + + console.log(`Block text: ${blockText}`); + console.log(`Block confidence: ${block.confidence}`); }); + }); // [END vision_detect_document] } -function detectSafeSearch(fileName) { +async function detectSafeSearch(fileName) { // [START vision_safe_search_detection] // Imports the Google Cloud client library const vision = require('@google-cloud/vision').v1p1beta1; @@ -81,25 +75,18 @@ function detectSafeSearch(fileName) { // const fileName = 'Local image file, e.g. /path/to/image.png'; // Performs safe search detection on the local file - client - .safeSearchDetection(fileName) - .then(results => { - const detections = results[0].safeSearchAnnotation; - - console.log('Safe search:'); - console.log(`Adult: ${detections.adult}`); - console.log(`Medical: ${detections.medical}`); - console.log(`Spoof: ${detections.spoof}`); - console.log(`Violence: ${detections.violence}`); - console.log(`Racy: ${detections.racy}`); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.safeSearchDetection(fileName); + const detections = result.safeSearchAnnotation; + console.log('Safe search:'); + console.log(`Adult: ${detections.adult}`); + console.log(`Medical: ${detections.medical}`); + console.log(`Spoof: ${detections.spoof}`); + console.log(`Violence: ${detections.violence}`); + console.log(`Racy: ${detections.racy}`); // [END vision_safe_search_detection] } -function detectWeb(fileName) { +async function detectWeb(fileName) { // [START vision_web_detection] // Imports the Google Cloud client library const vision = require('@google-cloud/vision').v1p1beta1; @@ -113,87 +100,78 @@ function detectWeb(fileName) { // const fileName = 'Local image file, e.g. /path/to/image.png'; // Detect similar images on the web to a local file - client - .webDetection(fileName) - .then(results => { - const webDetection = results[0].webDetection; - - if (webDetection.bestGuessLabels.length) { - webDetection.bestGuessLabels.forEach(label => { - console.log(`Best guess label: ${label.label}`); - }); - } - - if (webDetection.pagesWithMatchingImages.length) { - const pages = webDetection.pagesWithMatchingImages; - console.log(`Pages with matching images found: ${pages.length}`); - - pages.forEach(page => { - console.log(`Page url: ${page.url}`); + const [result] = await client.webDetection(fileName); + const webDetection = result.webDetection; + if (webDetection.bestGuessLabels.length) { + webDetection.bestGuessLabels.forEach(label => { + console.log(`Best guess label: ${label.label}`); + }); + } - if (page.fullMatchingImages.length) { - const fullMatchingImages = page.fullMatchingImages; - console.log(`Full Matches found: ${fullMatchingImages.length}`); - fullMatchingImages.forEach(image => { - console.log(`Image url: ${image.url}`); - }); - } + if (webDetection.pagesWithMatchingImages.length) { + const pages = webDetection.pagesWithMatchingImages; + console.log(`Pages with matching images found: ${pages.length}`); - if (page.partialMatchingImages.length) { - const partialMatchingImages = page.partialMatchingImages; - console.log( - `Partial Matches found: ${partialMatchingImages.length}` - ); - partialMatchingImages.forEach(image => { - console.log(`Image url: ${image.url}`); - }); - } - }); - } + pages.forEach(page => { + console.log(`Page url: ${page.url}`); - if (webDetection.fullMatchingImages.length) { - console.log( - `Full matches found: ${webDetection.fullMatchingImages.length}` - ); - webDetection.fullMatchingImages.forEach(image => { - console.log(` Image url: ${image.url}`); + if (page.fullMatchingImages.length) { + const fullMatchingImages = page.fullMatchingImages; + console.log(`Full Matches found: ${fullMatchingImages.length}`); + fullMatchingImages.forEach(image => { + console.log(`Image url: ${image.url}`); }); } - if (webDetection.partialMatchingImages.length) { - console.log( - `Partial matches found: ${webDetection.partialMatchingImages.length}` - ); - webDetection.partialMatchingImages.forEach(image => { - console.log(` Image url: ${image.url}`); - }); - } - - if (webDetection.webEntities.length) { - console.log(`Web entities found: ${webDetection.webEntities.length}`); - webDetection.webEntities.forEach(webEntity => { - console.log(` Score: ${webEntity.score}`); - console.log(` Description: ${webEntity.description}`); + if (page.partialMatchingImages.length) { + const partialMatchingImages = page.partialMatchingImages; + console.log(`Partial Matches found: ${partialMatchingImages.length}`); + partialMatchingImages.forEach(image => { + console.log(`Image url: ${image.url}`); }); } + }); + } + + if (webDetection.fullMatchingImages.length) { + console.log( + `Full matches found: ${webDetection.fullMatchingImages.length}` + ); + webDetection.fullMatchingImages.forEach(image => { + console.log(` Image url: ${image.url}`); + }); + } + + if (webDetection.partialMatchingImages.length) { + console.log( + `Partial matches found: ${webDetection.partialMatchingImages.length}` + ); + webDetection.partialMatchingImages.forEach(image => { + console.log(` Image url: ${image.url}`); + }); + } - if (webDetection.visuallySimilarImages.length) { - const visuallySimilarImages = webDetection.visuallySimilarImages; - console.log( - `Visually similar images found: ${visuallySimilarImages.length}` - ); - visuallySimilarImages.forEach(image => { - console.log(` Image url: ${image.url}`); - }); - } - }) - .catch(err => { - console.error('ERROR:', err); + if (webDetection.webEntities.length) { + console.log(`Web entities found: ${webDetection.webEntities.length}`); + webDetection.webEntities.forEach(webEntity => { + console.log(` Score: ${webEntity.score}`); + console.log(` Description: ${webEntity.description}`); + }); + } + + if (webDetection.visuallySimilarImages.length) { + const visuallySimilarImages = webDetection.visuallySimilarImages; + console.log( + `Visually similar images found: ${visuallySimilarImages.length}` + ); + visuallySimilarImages.forEach(image => { + console.log(` Image url: ${image.url}`); }); + } // [END vision_web_detection] } -function detectWebEntitiesIncludingGeoResults(fileName) { +async function detectWebEntitiesIncludingGeoResults(fileName) { // [START vision_web_entities_include_geo_results] // Imports the Google Cloud client library const vision = require('@google-cloud/vision').v1p1beta1; @@ -220,19 +198,12 @@ function detectWebEntitiesIncludingGeoResults(fileName) { }; // Performs safe search detection on the local file - client - .webDetection(request) - .then(results => { - const webDetection = results[0].webDetection; - - webDetection.webEntities.forEach(entity => { - console.log(`Score: ${entity.score}`); - console.log(`Description: ${entity.description}`); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.webDetection(request); + const webDetection = result.webDetection; + webDetection.webEntities.forEach(entity => { + console.log(`Score: ${entity.score}`); + console.log(`Description: ${entity.description}`); + }); // [END vision_web_entities_include_geo_results] } diff --git a/samples/detect.v1p3beta1.js b/samples/detect.v1p3beta1.js index 45912804..0b07a373 100644 --- a/samples/detect.v1p3beta1.js +++ b/samples/detect.v1p3beta1.js @@ -17,7 +17,7 @@ 'use strict'; -function detectHandwritingOCR(fileName) { +async function detectHandwritingOCR(fileName) { // [START vision_handwritten_ocr_beta] // Imports the Google Cloud client libraries const vision = require('@google-cloud/vision').v1p3beta1; @@ -39,19 +39,14 @@ function detectHandwritingOCR(fileName) { languageHints: ['en-t-i0-handwrit'], }, }; - client - .documentTextDetection(request) - .then(results => { - const fullTextAnnotation = results[0].fullTextAnnotation; - console.log(`Full text: ${fullTextAnnotation.text}`); - }) - .catch(err => { - console.error('ERROR:', err); - }); + + const [result] = await client.documentTextDetection(request); + const fullTextAnnotation = result.fullTextAnnotation; + console.log(`Full text: ${fullTextAnnotation.text}`); // [END vision_handwritten_ocr_beta] } -function detectHandwritingGCS(uri) { +async function detectHandwritingGCS(uri) { // [START vision_handwritten_ocr_gcs_beta] // Imports the Google Cloud client libraries const vision = require('@google-cloud/vision').v1p3beta1; @@ -74,15 +69,9 @@ function detectHandwritingGCS(uri) { }, }; - client - .documentTextDetection(request) - .then(results => { - const fullTextAnnotation = results[0].fullTextAnnotation; - console.log(`Full text: ${fullTextAnnotation.text}`); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.documentTextDetection(request); + const fullTextAnnotation = result.fullTextAnnotation; + console.log(`Full text: ${fullTextAnnotation.text}`); // [END vision_handwritten_ocr_gcs_beta] } diff --git a/samples/package.json b/samples/package.json index a3c4fcca..a11a974d 100644 --- a/samples/package.json +++ b/samples/package.json @@ -8,7 +8,7 @@ "node": ">=8" }, "scripts": { - "test": "ava -T 1m --verbose system-test/*.test.js" + "test": "mocha system-test/*.test.js --timeout 600000" }, "dependencies": { "@google-cloud/automl": "^0.1.1", @@ -22,9 +22,7 @@ "devDependencies": { "@google-cloud/nodejs-repo-tools": "^3.0.0", "@google-cloud/storage": "^2.0.0", - "ava": "^0.25.0", - "proxyquire": "^2.0.1", - "sinon": "^7.0.0", + "mocha": "^5.0.0", "uuid": "^3.2.1" }, "optionalDependencies": { diff --git a/samples/productSearch/importProductSets.v1p3beta1.js b/samples/productSearch/importProductSets.v1p3beta1.js index 4a8e1205..5e716505 100644 --- a/samples/productSearch/importProductSets.v1p3beta1.js +++ b/samples/productSearch/importProductSets.v1p3beta1.js @@ -15,7 +15,7 @@ 'use strict'; // [START vision_product_search_import_product_images] -function importProductSets(projectId, location, gcsUri) { +async function importProductSets(projectId, location, gcsUri) { // Imports the Google Cloud client library // [START vision_product_search_tutorial_import] const vision = require('@google-cloud/vision').v1p3beta1; @@ -41,39 +41,28 @@ function importProductSets(projectId, location, gcsUri) { }; // Import the product sets from the input URI. - client - .importProductSets({parent: projectLocation, inputConfig: inputConfig}) - .then(responses => { - const response = responses[0]; - const operation = responses[1]; - console.log('Processing operation name: ', operation.name); + const [response, operation] = await client.importProductSets({ + parent: projectLocation, + inputConfig: inputConfig, + }); - // synchronous check of operation status - return response.promise(); - }) - .then(responses => { - console.log('Processing done.'); - console.log('Results of the processing:'); + console.log('Processing operation name: ', operation.name); - for (const i in responses[0].statuses) { - console.log( - 'Status of processing ', - i, - 'of the csv:', - responses[0].statuses[i] - ); + // synchronous check of operation status + const [result] = await response.promise(); + console.log('Processing done.'); + console.log('Results of the processing:'); - // Check the status of reference image - if (responses[0].statuses[i].code === 0) { - console.log(responses[0].referenceImages[i]); - } else { - console.log('No reference image.'); - } - } - }) - .catch(err => { - console.error(err); - }); + for (const i in result.statuses) { + console.log('Status of processing ', i, 'of the csv:', result.statuses[i]); + + // Check the status of reference image + if (result.statuses[i].code === 0) { + console.log(result.referenceImages[i]); + } else { + console.log('No reference image.'); + } + } // [END vision_product_search_import_product_images] } // [END vision_product_search_import_product_set] diff --git a/samples/productSearch/productSearch.v1p3beta1.js b/samples/productSearch/productSearch.v1p3beta1.js index e9528386..2e05d7f6 100644 --- a/samples/productSearch/productSearch.v1p3beta1.js +++ b/samples/productSearch/productSearch.v1p3beta1.js @@ -15,7 +15,12 @@ 'use strict'; -function addProductToProductSet(projectId, location, productId, productSetId) { +async function addProductToProductSet( + projectId, + location, + productId, + productSetId +) { // [START vision_product_search_add_product_to_product_set] const vision = require('@google-cloud/vision').v1p3beta1; @@ -42,18 +47,12 @@ function addProductToProductSet(projectId, location, productId, productSetId) { product: productPath, }; - client - .addProductToProductSet(request) - .then(() => { - console.log(`Product added to product set.`); - }) - .catch(err => { - console.error(err); - }); + await client.addProductToProductSet(request); + console.log(`Product added to product set.`); // [END vision_product_search_add_product_to_product_set] } -function listProductsInProductSet(projectId, location, productSetId) { +async function listProductsInProductSet(projectId, location, productSetId) { // [START vision_product_search_list_products_in_product_set] const vision = require('@google-cloud/vision').v1p3beta1; @@ -75,17 +74,15 @@ function listProductsInProductSet(projectId, location, productSetId) { name: productSetPath, }; - client.listProductsInProductSet(request).then(results => { - const products = results[0]; - products.forEach(product => { - console.log(`Product name: ${product.name}`); - console.log(`Product display name: ${product.displayName}`); - }); + const [products] = await client.listProductsInProductSet(request); + products.forEach(product => { + console.log(`Product name: ${product.name}`); + console.log(`Product display name: ${product.displayName}`); }); // [END vision_product_search_list_products_in_product_set] } -function removeProductFromProductSet( +async function removeProductFromProductSet( projectId, location, productId, @@ -113,14 +110,8 @@ function removeProductFromProductSet( product: productPath, }; - client - .removeProductFromProductSet(request) - .then(() => { - console.log(`Product removed from product set.`); - }) - .catch(err => { - console.error(err); - }); + await client.removeProductFromProductSet(request); + console.log(`Product removed from product set.`); // [END vision_product_search_remove_product_from_product_set] } diff --git a/samples/productSearch/productSets.v1p3beta1.js b/samples/productSearch/productSets.v1p3beta1.js index 809b31ff..4ff17845 100644 --- a/samples/productSearch/productSets.v1p3beta1.js +++ b/samples/productSearch/productSets.v1p3beta1.js @@ -15,7 +15,7 @@ 'use strict'; -function createProductSet( +async function createProductSet( projectId, location, productSetId, @@ -49,20 +49,12 @@ function createProductSet( productSetId: productSetId, }; - client - .createProductSet(request) - .then(results => { - // The response is the product set with the `name` field populated - const createdProductSet = results[0]; - console.log(`Product Set name: ${createdProductSet.name}`); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [createdProductSet] = await client.createProductSet(request); + console.log(`Product Set name: ${createdProductSet.name}`); // [END vision_product_search_create_product_set] } -function getProductSet(projectId, location, productSetId) { +async function getProductSet(projectId, location, productSetId) { // [START vision_product_search_get_product_set] // Imports the Google Cloud client library const vision = require('@google-cloud/vision').v1p3beta1; @@ -84,20 +76,13 @@ function getProductSet(projectId, location, productSetId) { productSetId ); - client - .getProductSet({name: productSetPath}) - .then(results => { - const productSet = results[0]; - console.log(`Product Set name: ${productSet.name}`); - console.log(`Product Set display name: ${productSet.displayName}`); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [productSet] = await client.getProductSet({name: productSetPath}); + console.log(`Product Set name: ${productSet.name}`); + console.log(`Product Set display name: ${productSet.displayName}`); // [END vision_product_search_get_product_set] } -function listProductSets(projectId, location) { +async function listProductSets(projectId, location) { // [START vision_product_search_list_product_sets] // Imports the Google Cloud client library const vision = require('@google-cloud/vision').v1p3beta1; @@ -114,22 +99,15 @@ function listProductSets(projectId, location) { // Resource path that represents Google Cloud Platform location. const locationPath = client.locationPath(projectId, location); - client - .listProductSets({parent: locationPath}) - .then(results => { - const productSets = results[0]; - productSets.forEach(productSet => { - console.log(`Product Set name: ${productSet.name}`); - console.log(`Product Set display name: ${productSet.displayName}`); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [productSets] = await client.listProductSets({parent: locationPath}); + productSets.forEach(productSet => { + console.log(`Product Set name: ${productSet.name}`); + console.log(`Product Set display name: ${productSet.displayName}`); + }); // [END vision_product_search_list_product_sets] } -function deleteProductSet(projectId, location, productSetId) { +async function deleteProductSet(projectId, location, productSetId) { // [START vision_product_search_delete_product_set] // Imports the Google Cloud client library const vision = require('@google-cloud/vision').v1p3beta1; @@ -151,14 +129,8 @@ function deleteProductSet(projectId, location, productSetId) { productSetId ); - client - .deleteProductSet({name: productSetPath}) - .then(() => { - console.log('Product set deleted.'); - }) - .catch(err => { - console.error('ERROR:', err); - }); + await client.deleteProductSet({name: productSetPath}); + console.log('Product set deleted.'); // [END vision_product_search_delete_product_set] } diff --git a/samples/productSearch/products.v1p3beta1.js b/samples/productSearch/products.v1p3beta1.js index e17bcd31..9c51369f 100644 --- a/samples/productSearch/products.v1p3beta1.js +++ b/samples/productSearch/products.v1p3beta1.js @@ -15,7 +15,7 @@ 'use strict'; -function createProduct( +async function createProduct( projectId, location, productId, @@ -52,20 +52,12 @@ function createProduct( productId: productId, }; - client - .createProduct(request) - .then(results => { - // The response is the product with the `name` field populated - const createdProduct = results[0]; - console.log(`Product name: ${createdProduct.name}`); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [createdProduct] = await client.createProduct(request); + console.log(`Product name: ${createdProduct.name}`); // [END vision_product_search_create_product] } -function getProduct(projectId, location, productId) { +async function getProduct(projectId, location, productId) { // [START vision_product_search_get_product] // Imports the Google Cloud client library const vision = require('@google-cloud/vision').v1p3beta1; @@ -83,24 +75,17 @@ function getProduct(projectId, location, productId) { // Resource path that represents Google Cloud Platform location. const productPath = client.productPath(projectId, location, productId); - client - .getProduct({name: productPath}) - .then(results => { - const product = results[0]; - console.log(`Product name: ${product.name}`); - console.log(`Product id: ${product.name.split('/').pop()}`); - console.log(`Product display name: ${product.displayName}`); - console.log(`Product description: ${product.description}`); - console.log(`Product category: ${product.productCategory}`); - console.log(`Product labels: ${product.productLabels}`); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [product] = await client.getProduct({name: productPath}); + console.log(`Product name: ${product.name}`); + console.log(`Product id: ${product.name.split('/').pop()}`); + console.log(`Product display name: ${product.displayName}`); + console.log(`Product description: ${product.description}`); + console.log(`Product category: ${product.productCategory}`); + console.log(`Product labels: ${product.productLabels}`); // [END vision_product_search_get_product] } -function listProducts(projectId, location) { +async function listProducts(projectId, location) { // [START vision_product_search_list_products] // Imports the Google Cloud client library const vision = require('@google-cloud/vision').v1p3beta1; @@ -117,31 +102,24 @@ function listProducts(projectId, location) { // Resource path that represents Google Cloud Platform location. const locationPath = client.locationPath(projectId, location); - client - .listProducts({parent: locationPath}) - .then(results => { - const products = results[0]; - products.forEach(product => { - console.log(`Product name: ${product.name}`); - console.log(`Product id: ${product.name.split('/').pop()}`); - console.log(`Product display name: ${product.displayName}`); - console.log(`Product description: ${product.description}`); - console.log(`Product category: ${product.productCategory}`); - if (product.productLabels.length) { - console.log(`Product labels:`); - product.productLabels.forEach(productLabel => { - console.log(`${productLabel.key}: ${productLabel.value}`); - }); - } + const [products] = client.listProducts({parent: locationPath}); + products.forEach(product => { + console.log(`Product name: ${product.name}`); + console.log(`Product id: ${product.name.split('/').pop()}`); + console.log(`Product display name: ${product.displayName}`); + console.log(`Product description: ${product.description}`); + console.log(`Product category: ${product.productCategory}`); + if (product.productLabels.length) { + console.log(`Product labels:`); + product.productLabels.forEach(productLabel => { + console.log(`${productLabel.key}: ${productLabel.value}`); }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + } + }); // [END vision_product_search_list_products] } -function deleteProduct(projectId, location, productId) { +async function deleteProduct(projectId, location, productId) { // [START vision_product_search_delete_product] // Imports the Google Cloud client library const vision = require('@google-cloud/vision').v1p3beta1; @@ -159,18 +137,12 @@ function deleteProduct(projectId, location, productId) { // Resource path that represents full path to the product. const productPath = client.productPath(projectId, location, productId); - client - .deleteProduct({name: productPath}) - .then(() => { - console.log('Product deleted.'); - }) - .catch(err => { - console.error('ERROR:', err); - }); + await client.deleteProduct({name: productPath}); + console.log('Product deleted.'); // [END vision_product_search_delete_product] } -function updateProductLabels(projectId, location, productId, key, value) { +async function updateProductLabels(projectId, location, productId, key, value) { // [START vision_product_search_update_product_labels] // Imports the Google Cloud client library const vision = require('@google-cloud/vision').v1p3beta1; @@ -209,23 +181,16 @@ function updateProductLabels(projectId, location, productId, key, value) { updateMask: updateMask, }; - client - .updateProduct(request) - .then(results => { - const product = results[0]; - console.log(`Product name: ${product.name}`); - console.log(`Product display name: ${product.displayName}`); - console.log(`Product description: ${product.description}`); - console.log(`Product category: ${product.productCategory}`); - console.log( - `Product Labels: ${product.productLabels[0].key}: ${ - product.productLabels[0].value - }` - ); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [updatedProduct] = await client.updateProduct(request); + console.log(`Product name: ${updatedProduct.name}`); + console.log(`Product display name: ${updatedProduct.displayName}`); + console.log(`Product description: ${updatedProduct.description}`); + console.log(`Product category: ${updatedProduct.productCategory}`); + console.log( + `Product Labels: ${updatedProduct.productLabels[0].key}: ${ + updatedProduct.productLabels[0].value + }` + ); // [END vision_product_search_update_product_labels] } diff --git a/samples/productSearch/referenceImages.v1p3beta1.js b/samples/productSearch/referenceImages.v1p3beta1.js index b68c9127..72008093 100644 --- a/samples/productSearch/referenceImages.v1p3beta1.js +++ b/samples/productSearch/referenceImages.v1p3beta1.js @@ -15,7 +15,7 @@ 'use strict'; -function createReferenceImage( +async function createReferenceImage( projectId, location, productId, @@ -49,21 +49,13 @@ function createReferenceImage( referenceImageId: referenceImageId, }; - client - .createReferenceImage(request) - .then(responses => { - const response = responses[0]; - console.log(`response.name: ${response.name}`); - console.log(`response.uri: ${response.uri}`); - }) - .catch(err => { - console.error(err); - }); - + const [response] = await client.createReferenceImage(request); + console.log(`response.name: ${response.name}`); + console.log(`response.uri: ${response.uri}`); // [END vision_product_search_create_reference_image] } -function listReferenceImage(projectId, location, productId) { +async function listReferenceImage(projectId, location, productId) { // [START vision_product_search_list_reference_images] const vision = require('@google-cloud/vision').v1p3beta1; @@ -83,23 +75,20 @@ function listReferenceImage(projectId, location, productId) { parent: formattedParent, }; - client - .listReferenceImages(request) - .then(responses => { - const response = responses[0]; - response.forEach(image => { - console.log(`image.name: ${image.name}`); - console.log(`image.uri: ${image.uri}`); - }); - }) - .catch(err => { - console.log(err); - }); - + const [response] = await client.listReferenceImages(request); + response.forEach(image => { + console.log(`image.name: ${image.name}`); + console.log(`image.uri: ${image.uri}`); + }); // [END vision_product_search_list_reference_images] } -function getReferenceImage(projectId, location, productId, referenceImageId) { +async function getReferenceImage( + projectId, + location, + productId, + referenceImageId +) { // [START vision_product_search_get_reference_image] const vision = require('@google-cloud/vision').v1p3beta1; @@ -125,21 +114,13 @@ function getReferenceImage(projectId, location, productId, referenceImageId) { name: formattedName, }; - client - .getReferenceImage(request) - .then(responses => { - const response = responses[0]; - console.log(`response.name: ${response.name}`); - console.log(`response.uri: ${response.uri}`); - }) - .catch(err => { - console.log(err); - }); - + const response = await client.getReferenceImage(request); + console.log(`response.name: ${response.name}`); + console.log(`response.uri: ${response.uri}`); // [END vision_product_search_get_reference_image] } -function deleteReferenceImage( +async function deleteReferenceImage( projectId, location, productId, @@ -170,15 +151,8 @@ function deleteReferenceImage( name: formattedName, }; - client - .deleteReferenceImage(request) - .then(() => { - console.log(`Reference image deleted from product.`); - }) - .catch(err => { - console.log(err); - }); - + await client.deleteReferenceImage(request); + console.log(`Reference image deleted from product.`); // [END vision_product_search_delete_reference_image] } diff --git a/samples/productSearch/similarProducts.v1p3beta1.js b/samples/productSearch/similarProducts.v1p3beta1.js index c3af6778..939465fd 100644 --- a/samples/productSearch/similarProducts.v1p3beta1.js +++ b/samples/productSearch/similarProducts.v1p3beta1.js @@ -15,7 +15,7 @@ 'use strict'; // [START vision_product_search_get_similar_products] -function getSimilarProductsFile( +async function getSimilarProductsFile( projectId, location, productSetId, @@ -62,31 +62,23 @@ function getSimilarProductsFile( }, }, }; - imageAnnotatorClient - .batchAnnotateImages({requests: [request]}) - .then(responses => { - const response = responses[0]; - - console.log('Search Image:', filePath); - - const results = - response['responses'][0]['productSearchResults']['results']; - console.log('\nSimilar product information:'); - results.forEach(result => { - console.log('Product id:', result['product'].name.split('/').pop(-1)); - console.log('Product display name:', result['product'].displayName); - console.log('Product description:', result['product'].description); - console.log('Product category:', result['product'].productCategory); - }); - }) - .catch(err => { - console.error(err); - }); + const [response] = await imageAnnotatorClient.batchAnnotateImages({ + requests: [request], + }); + console.log('Search Image:', filePath); + const results = response['responses'][0]['productSearchResults']['results']; + console.log('\nSimilar product information:'); + results.forEach(result => { + console.log('Product id:', result['product'].name.split('/').pop(-1)); + console.log('Product display name:', result['product'].displayName); + console.log('Product description:', result['product'].description); + console.log('Product category:', result['product'].productCategory); + }); } // [END vision_product_search_get_similar_products] // [START vision_product_search_get_similar_products_gcs] -function getSimilarProductsGcs( +async function getSimilarProductsGcs( projectId, location, productSetId, @@ -133,24 +125,20 @@ function getSimilarProductsGcs( }, }; console.log(request.image); - imageAnnotatorClient - .batchAnnotateImages({requests: [request]}) - .then(responses => { - const response = responses[0]; - console.log('Search Image:', filePath); - console.log('\nSimilar product information:'); - const results = - response['responses'][0]['productSearchResults']['results']; - results.forEach(result => { - console.log('Product id:', result['product'].name.split('/').pop(-1)); - console.log('Product display name:', result['product'].displayName); - console.log('Product description:', result['product'].description); - console.log('Product category:', result['product'].productCategory); - }); - }) - .catch(err => { - console.error(err); - }); + + const [response] = await imageAnnotatorClient.batchAnnotateImages({ + requests: [request], + }); + console.log('Search Image:', filePath); + console.log('\nSimilar product information:'); + + const results = response['responses'][0]['productSearchResults']['results']; + results.forEach(result => { + console.log('Product id:', result['product'].name.split('/').pop(-1)); + console.log('Product display name:', result['product'].displayName); + console.log('Product description:', result['product'].description); + console.log('Product category:', result['product'].productCategory); + }); } // [END vision_product_search_get_similar_products_gcs] require(`yargs`) // eslint-disable-line diff --git a/samples/productSearch/system-test/.eslintrc.yml b/samples/productSearch/system-test/.eslintrc.yml index 8e078abb..0ab526f5 100644 --- a/samples/productSearch/system-test/.eslintrc.yml +++ b/samples/productSearch/system-test/.eslintrc.yml @@ -1,4 +1,6 @@ --- +env: + mocha: true rules: node/no-unpublished-require: off no-empty: off diff --git a/samples/productSearch/system-test/importProductSets.v1p3beta1.test.js b/samples/productSearch/system-test/importProductSets.v1p3beta1.test.js index 40f3adaa..9938c437 100644 --- a/samples/productSearch/system-test/importProductSets.v1p3beta1.test.js +++ b/samples/productSearch/system-test/importProductSets.v1p3beta1.test.js @@ -16,7 +16,7 @@ 'use strict'; const path = require(`path`); -const test = require(`ava`); +const assert = require('assert'); const tools = require(`@google-cloud/nodejs-repo-tools`); const cmd = `node importProductSets.v1p3beta1.js`; const cwd = path.join(__dirname, `..`); @@ -27,12 +27,15 @@ const testImportProductSets = { location: 'us-west1', gcsUri: 'gs://nodejs-docs-samples/product-search/product_sets.csv', }; -test(`Should import a Product Set`, async t => { - const output = await tools.runAsync( - `${cmd} importProductSets "${testImportProductSets.projectId}" "${ - testImportProductSets.location - }" "${testImportProductSets.gcsUri}"`, - cwd - ); - t.true(output.includes(`Processing done.`)); + +describe(`import product sets`, () => { + it(`Should import a Product Set`, async () => { + const output = await tools.runAsync( + `${cmd} importProductSets "${testImportProductSets.projectId}" "${ + testImportProductSets.location + }" "${testImportProductSets.gcsUri}"`, + cwd + ); + assert.ok(output.includes(`Processing done.`)); + }); }); diff --git a/samples/productSearch/system-test/productSearch.v1p3beta1.test.js b/samples/productSearch/system-test/productSearch.v1p3beta1.test.js index 2eaaece4..e9f48b95 100644 --- a/samples/productSearch/system-test/productSearch.v1p3beta1.test.js +++ b/samples/productSearch/system-test/productSearch.v1p3beta1.test.js @@ -18,7 +18,7 @@ const path = require(`path`); const vision = require('@google-cloud/vision').v1p3beta1; const productSearchClient = new vision.ProductSearchClient(); -const test = require(`ava`); +const assert = require('assert'); const tools = require(`@google-cloud/nodejs-repo-tools`); const cmd = `node productSearch.v1p3beta1.js`; const cwd = path.join(__dirname, `..`); @@ -42,74 +42,76 @@ testProductSet.productSetPath = productSearchClient.productSetPath( testProductSet.createdProductPaths = []; testProductSet.createdProductSetPaths = []; -test.before(tools.checkCredentials); +describe(`product search`, () => { + before(tools.checkCredentials); -test.before(async () => { - // Create a test product set for each test - try { - await productSearchClient.createProduct({ - parent: productSearchClient.locationPath( - testProductSet.projectId, - testProductSet.location - ), - productId: testProductSet.productId, - product: { - displayName: testProductSet.productDisplayName, - productCategory: testProductSet.productCategory, - }, - }); - testProductSet.createdProductPaths.push(testProductSet.productPath); - } catch (err) {} // ignore error - - try { - await productSearchClient.createProductSet({ - parent: productSearchClient.locationPath( - testProductSet.projectId, - testProductSet.location - ), - productSetId: testProductSet.productSetId, - productSet: { - displayName: testProductSet.productSetDisplayName, - }, - }); - testProductSet.createdProductSetPaths.push( - testProductSet.createdProductSetPaths - ); - } catch (err) {} // ignore error -}); + before(async () => { + // Create a test product set for each test + try { + await productSearchClient.createProduct({ + parent: productSearchClient.locationPath( + testProductSet.projectId, + testProductSet.location + ), + productId: testProductSet.productId, + product: { + displayName: testProductSet.productDisplayName, + productCategory: testProductSet.productCategory, + }, + }); + testProductSet.createdProductPaths.push(testProductSet.productPath); + } catch (err) {} // ignore error -test.after(async () => { - // Delete products sets after each test - testProductSet.createdProductSetPaths.forEach(async path => { try { - await productSearchClient.deleteProductSet({name: path}); - await productSearchClient.deleteProduct({name: path}); + await productSearchClient.createProductSet({ + parent: productSearchClient.locationPath( + testProductSet.projectId, + testProductSet.location + ), + productSetId: testProductSet.productSetId, + productSet: { + displayName: testProductSet.productSetDisplayName, + }, + }); + testProductSet.createdProductSetPaths.push( + testProductSet.createdProductSetPaths + ); } catch (err) {} // ignore error }); -}); -test(`should add product to product set`, async t => { - const output = await tools.runAsync( - `${cmd} addProductToProductSet "${testProductSet.projectId}" "${ - testProductSet.location - }" "${testProductSet.productId}" "${testProductSet.productSetId}"`, - cwd - ); + after(async () => { + // Delete products sets after each test + testProductSet.createdProductSetPaths.forEach(async path => { + try { + await productSearchClient.deleteProductSet({name: path}); + await productSearchClient.deleteProduct({name: path}); + } catch (err) {} // ignore error + }); + }); - t.true(output.includes(`Product added to product set.`)); -}); + it(`should add product to product set`, async () => { + const output = await tools.runAsync( + `${cmd} addProductToProductSet "${testProductSet.projectId}" "${ + testProductSet.location + }" "${testProductSet.productId}" "${testProductSet.productSetId}"`, + cwd + ); -test(`remove a product from a product set`, async t => { - const output = await tools.runAsync( - `${cmd} removeProductFromProductSet "${testProductSet.projectId}" "${ - testProductSet.location - }" "${testProductSet.productId}" "${testProductSet.productSetId}"`, - cwd - ); + assert.ok(output.includes(`Product added to product set.`)); + }); - console.log('---------------'); - console.log(output); - console.log('---------------'); + test(`remove a product from a product set`, async () => { + const output = await tools.runAsync( + `${cmd} removeProductFromProductSet "${testProductSet.projectId}" "${ + testProductSet.location + }" "${testProductSet.productId}" "${testProductSet.productSetId}"`, + cwd + ); - t.true(output.includes(`Product removed from product set.`)); + console.log('---------------'); + console.log(output); + console.log('---------------'); + + assert.ok(output.includes(`Product removed from product set.`)); + }); }); diff --git a/samples/productSearch/system-test/productSets.v1p3beta1.test.js b/samples/productSearch/system-test/productSets.v1p3beta1.test.js index 9309d61d..836ff56f 100644 --- a/samples/productSearch/system-test/productSets.v1p3beta1.test.js +++ b/samples/productSearch/system-test/productSets.v1p3beta1.test.js @@ -19,7 +19,7 @@ const path = require(`path`); const uuid = require(`uuid`); const vision = require('@google-cloud/vision').v1p3beta1; const productSearch = new vision.ProductSearchClient(); -const test = require(`ava`); +const assert = require('assert'); const tools = require(`@google-cloud/nodejs-repo-tools`); const cmd = `node productSets.v1p3beta1.js`; const cwd = path.join(__dirname, `..`); @@ -52,109 +52,119 @@ async function getProductSetOrFalse(productSetPath) { } } -test.before(tools.checkCredentials); -test.before(async () => { - // Create a test product set for each test - try { - await productSearch.createProductSet({ - parent: productSearch.locationPath( - testProductSet.projectId, - testProductSet.location - ), - productSetId: testProductSet.productSetId, - productSet: { - displayName: testProductSet.productSetDisplayName, - }, - }); - testProductSet.createdProductSetPaths.push( - testProductSet.createdProductSetPaths - ); - } catch (err) {} // ignore error -}); -test.after(async () => { - // Delete products sets after each test - testProductSet.createdProductSetPaths.forEach(async path => { +describe(`product sets`, () => { + before(tools.checkCredentials); + + before(async () => { + // Create a test product set for each test try { - await productSearch.deleteProductSet({name: path}); + await productSearch.createProductSet({ + parent: productSearch.locationPath( + testProductSet.projectId, + testProductSet.location + ), + productSetId: testProductSet.productSetId, + productSet: { + displayName: testProductSet.productSetDisplayName, + }, + }); + testProductSet.createdProductSetPaths.push( + testProductSet.createdProductSetPaths + ); } catch (err) {} // ignore error }); -}); -test(`should create product set`, async t => { - const newProductSetId = `ProductSetId${uuid.v4()}`; - const newProductSetPath = productSearch.productSetPath( - testProductSet.projectId, - testProductSet.location, - newProductSetId - ); - t.falsy(await getProductSetOrFalse(newProductSetPath)); - testProductSet.createdProductSetPaths.push(newProductSetPath); - - const output = await tools.runAsync( - `${cmd} createProductSet "${testProductSet.projectId}" "${ - testProductSet.location - }" "${newProductSetId}" "${testProductSet.productSetDisplayName}"`, - cwd - ); - - t.true(output.includes(`Product Set name: ${newProductSetPath}`)); - - const newProductSet = await getProductSetOrFalse(newProductSetPath); - t.true(newProductSet.displayName === testProductSet.productSetDisplayName); -}); + after(async () => { + // Delete products sets after each test + testProductSet.createdProductSetPaths.forEach(async path => { + try { + await productSearch.deleteProductSet({name: path}); + } catch (err) {} // ignore error + }); + }); -test(`should get product set`, async t => { - const output = await tools.runAsync( - `${cmd} getProductSet "${testProductSet.projectId}" "${ - testProductSet.location - }" "${testProductSet.productSetId}"`, - cwd - ); - - t.true(output.includes(`Product Set name: ${testProductSet.productSetPath}`)); - t.true( - output.includes( - `Product Set display name: ${testProductSet.productSetDisplayName}` - ) - ); -}); + it(`should create product set`, async () => { + const newProductSetId = `ProductSetId${uuid.v4()}`; + const newProductSetPath = productSearch.productSetPath( + testProductSet.projectId, + testProductSet.location, + newProductSetId + ); + assert.strictEqual(await getProductSetOrFalse(newProductSetPath), false); + testProductSet.createdProductSetPaths.push(newProductSetPath); -test(`should list product sets`, async t => { - const output = await tools.runAsync( - `${cmd} listProductSets "${testProductSet.projectId}" "${ - testProductSet.location - }"`, - cwd - ); - - t.true(output.includes(`Product Set name: ${testProductSet.productSetPath}`)); - t.true( - output.includes( - `Product Set display name: ${testProductSet.productSetDisplayName}` - ) - ); -}); + const output = await tools.runAsync( + `${cmd} createProductSet "${testProductSet.projectId}" "${ + testProductSet.location + }" "${newProductSetId}" "${testProductSet.productSetDisplayName}"`, + cwd + ); -test(`should delete product sets`, async t => { - const productSet = await productSearch.getProductSet({ - name: `${testProductSet.productSetPath}`, + assert.ok(output.includes(`Product Set name: ${newProductSetPath}`)); + + const newProductSet = await getProductSetOrFalse(newProductSetPath); + assert.ok( + newProductSet.displayName === testProductSet.productSetDisplayName + ); }); - t.truthy(productSet); - const output = await tools.runAsync( - `${cmd} deleteProductSet "${testProductSet.projectId}" "${ - testProductSet.location - }" "${testProductSet.productSetId}"`, - cwd - ); + it(`should get product set`, async () => { + const output = await tools.runAsync( + `${cmd} getProductSet "${testProductSet.projectId}" "${ + testProductSet.location + }" "${testProductSet.productSetId}"`, + cwd + ); - t.true(output.includes('deleted')); - try { - await productSearch.getProductSet({ + assert.ok( + output.includes(`Product Set name: ${testProductSet.productSetPath}`) + ); + assert.ok( + output.includes( + `Product Set display name: ${testProductSet.productSetDisplayName}` + ) + ); + }); + + it(`should list product sets`, async () => { + const output = await tools.runAsync( + `${cmd} listProductSets "${testProductSet.projectId}" "${ + testProductSet.location + }"`, + cwd + ); + + assert.ok( + output.includes(`Product Set name: ${testProductSet.productSetPath}`) + ); + assert.ok( + output.includes( + `Product Set display name: ${testProductSet.productSetDisplayName}` + ) + ); + }); + + it(`should delete product sets`, async () => { + const productSet = await productSearch.getProductSet({ name: `${testProductSet.productSetPath}`, }); - t.fail('Product set was not deleted'); - } catch (err) { - t.true(err.message.includes('Not found')); - } + assert.ok(productSet); + + const output = await tools.runAsync( + `${cmd} deleteProductSet "${testProductSet.projectId}" "${ + testProductSet.location + }" "${testProductSet.productSetId}"`, + cwd + ); + + assert.ok(output.includes('deleted')); + try { + await productSearch.getProductSet({ + name: `${testProductSet.productSetPath}`, + }); + assert.fail('Product set was not deleted'); + } catch (err) { + assert.ok(err.message.includes('Not found')); + } + }); }); diff --git a/samples/productSearch/system-test/products.v1p3beta1.test.js b/samples/productSearch/system-test/products.v1p3beta1.test.js index 48f12a14..4c318312 100644 --- a/samples/productSearch/system-test/products.v1p3beta1.test.js +++ b/samples/productSearch/system-test/products.v1p3beta1.test.js @@ -19,7 +19,7 @@ const path = require(`path`); const uuid = require(`uuid`); const vision = require('@google-cloud/vision').v1p3beta1; const productSearch = new vision.ProductSearchClient(); -const test = require(`ava`); +const assert = require('assert'); const tools = require(`@google-cloud/nodejs-repo-tools`); const cmd = `node products.v1p3beta1.js`; const cwd = path.join(__dirname, `..`); @@ -55,10 +55,11 @@ async function getProductOrFalse(productPath) { } } -test.before(tools.checkCredentials); -test.before(async () => { - // Create a test product for each test - try { +describe(`products`, () => { + before(tools.checkCredentials); + + before(async () => { + // Create a test product for each test await productSearch.createProduct({ parent: productSearch.locationPath( testProduct.projectId, @@ -71,115 +72,124 @@ test.before(async () => { }, }); testProduct.createdProductPaths.push(testProduct.productPath); - } catch (err) {} // ignore error -}); -test.after(async () => { - // Delete products after each test - testProduct.createdProductPaths.forEach(async path => { - try { - await productSearch.deleteProduct({name: path}); - } catch (err) {} // ignore error }); -}); -test(`should create product`, async t => { - const newProductId = `ProductId${uuid.v4()}`; - const newProductPath = productSearch.productPath( - testProduct.projectId, - testProduct.location, - newProductId - ); - t.falsy(await getProductOrFalse(newProductPath)); - testProduct.createdProductPaths.push(newProductPath); - - const output = await tools.runAsync( - `${cmd} createProduct "${testProduct.projectId}" "${ - testProduct.location - }" "${newProductId}" "${testProduct.productDisplayName}" "${ - testProduct.productCategory - }"`, - cwd - ); - - t.true(output.includes(`Product name: ${newProductPath}`)); - - const newProduct = await getProductOrFalse(newProductPath); - t.true(newProduct.displayName === testProduct.productDisplayName); - t.true(newProduct.productCategory === testProduct.productCategory); -}); + after(async () => { + // Delete products after each test + testProduct.createdProductPaths.forEach(async path => { + try { + await productSearch.deleteProduct({name: path}); + } catch (err) {} // ignore error + }); + }); -test(`should get product`, async t => { - const output = await tools.runAsync( - `${cmd} getProduct "${testProduct.projectId}" "${testProduct.location}" "${ - testProduct.productId - }"`, - cwd - ); - - t.true(output.includes(`Product name: ${testProduct.productPath}`)); - t.true(output.includes(`Product id: ${testProduct.productId}`)); - t.true(output.includes(`Product display name:`)); - t.true(output.includes(`Product description:`)); - t.true(output.includes(`Product category: ${testProduct.productCategory}`)); - t.true(output.includes(`Product labels:`)); -}); + it(`should create product`, async () => { + const newProductId = `ProductId${uuid.v4()}`; + const newProductPath = productSearch.productPath( + testProduct.projectId, + testProduct.location, + newProductId + ); + assert.strictEqual(await getProductOrFalse(newProductPath), false); + testProduct.createdProductPaths.push(newProductPath); + + const output = await tools.runAsync( + `${cmd} createProduct "${testProduct.projectId}" "${ + testProduct.location + }" "${newProductId}" "${testProduct.productDisplayName}" "${ + testProduct.productCategory + }"`, + cwd + ); -test(`should list products`, async t => { - const output = await tools.runAsync( - `${cmd} listProducts "${testProduct.projectId}" "${testProduct.location}"`, - cwd - ); - - t.true(output.includes(`Product name: ${testProduct.productPath}`)); - t.true(output.includes(`Product id: ${testProduct.productId}`)); - t.true( - output.includes(`Product display name: ${testProduct.productDisplayName}`) - ); - t.true(output.includes(`Product description:`)); - t.true(output.includes(`Product category: ${testProduct.productCategory}`)); - t.true(output.includes(`Product labels:`)); -}); + assert.ok(output.includes(`Product name: ${newProductPath}`)); -test(`should delete product`, async t => { - const product = await productSearch.getProduct({ - name: `${testProduct.productPath}`, + const newProduct = await getProductOrFalse(newProductPath); + assert.ok(newProduct.displayName === testProduct.productDisplayName); + assert.ok(newProduct.productCategory === testProduct.productCategory); }); - t.truthy(product); - const output = await tools.runAsync( - `${cmd} deleteProduct "${testProduct.projectId}" "${ - testProduct.location - }" "${testProduct.productId}"`, - cwd - ); - t.true(output.includes(`Product deleted.`)); + it(`should get product`, async () => { + const output = await tools.runAsync( + `${cmd} getProduct "${testProduct.projectId}" "${ + testProduct.location + }" "${testProduct.productId}"`, + cwd + ); + + assert.ok(output.includes(`Product name: ${testProduct.productPath}`)); + assert.ok(output.includes(`Product id: ${testProduct.productId}`)); + assert.ok(output.includes(`Product display name:`)); + assert.ok(output.includes(`Product description:`)); + assert.ok( + output.includes(`Product category: ${testProduct.productCategory}`) + ); + assert.ok(output.includes(`Product labels:`)); + }); - try { - await productSearch.getProduct({name: `${testProduct.productPath}`}); - t.fail('Product was not deleted'); - } catch (err) { - t.true(err.message.includes('Not found')); - } -}); + it(`should list products`, async () => { + const output = await tools.runAsync( + `${cmd} listProducts "${testProduct.projectId}" "${ + testProduct.location + }"`, + cwd + ); + + assert.ok(output.includes(`Product name: ${testProduct.productPath}`)); + assert.ok(output.includes(`Product id: ${testProduct.productId}`)); + assert.ok( + output.includes(`Product display name: ${testProduct.productDisplayName}`) + ); + assert.ok(output.includes(`Product description:`)); + assert.ok( + output.includes(`Product category: ${testProduct.productCategory}`) + ); + assert.ok(output.includes(`Product labels:`)); + }); + + it(`should delete product`, async () => { + const product = await productSearch.getProduct({ + name: `${testProduct.productPath}`, + }); + assert.ok(product); + + const output = await tools.runAsync( + `${cmd} deleteProduct "${testProduct.projectId}" "${ + testProduct.location + }" "${testProduct.productId}"`, + cwd + ); + assert.ok(output.includes(`Product deleted.`)); -test(`should update product label`, async t => { - const output = await tools.runAsync( - `${cmd} updateProductLabels "${testProduct.projectId}" "${ - testProduct.location - }" "${testProduct.productId}" "${testProduct.productKey}" "${ - testProduct.productValue - }"`, - cwd - ); - - t.true( - output.includes( - `Product Labels: ${testProduct.productKey}: ${testProduct.productValue}` - ) - ); - t.true( - output.includes(`Product display name: ${testProduct.productDisplayName}`) - ); - t.true(output.includes(`Product description:`)); - t.true(output.includes(`Product category: ${testProduct.productCategory}`)); + try { + await productSearch.getProduct({name: `${testProduct.productPath}`}); + assert.fail('Product was not deleted'); + } catch (err) { + assert.ok(err.message.includes('Not found')); + } + }); + + it(`should update product label`, async () => { + const output = await tools.runAsync( + `${cmd} updateProductLabels "${testProduct.projectId}" "${ + testProduct.location + }" "${testProduct.productId}" "${testProduct.productKey}" "${ + testProduct.productValue + }"`, + cwd + ); + + assert.ok( + output.includes( + `Product Labels: ${testProduct.productKey}: ${testProduct.productValue}` + ) + ); + assert.ok( + output.includes(`Product display name: ${testProduct.productDisplayName}`) + ); + assert.ok(output.includes(`Product description:`)); + assert.ok( + output.includes(`Product category: ${testProduct.productCategory}`) + ); + }); }); diff --git a/samples/productSearch/system-test/referenceImages.v1p3beta1.test.js b/samples/productSearch/system-test/referenceImages.v1p3beta1.test.js index 863a2e0d..614be56d 100644 --- a/samples/productSearch/system-test/referenceImages.v1p3beta1.test.js +++ b/samples/productSearch/system-test/referenceImages.v1p3beta1.test.js @@ -19,7 +19,7 @@ const path = require(`path`); const uuid = require(`uuid`); const vision = require('@google-cloud/vision').v1p3beta1; const productSearchClient = new vision.ProductSearchClient(); -const test = require(`ava`); +const assert = require('assert'); const tools = require(`@google-cloud/nodejs-repo-tools`); const cmd = `node referenceImages.v1p3beta1.js`; const cwd = path.join(__dirname, `..`); @@ -41,55 +41,57 @@ testProduct.productPath = productSearchClient.productPath( ); testProduct.createdProductPaths = []; -test.before(tools.checkCredentials); +describe(`reference images`, () => { + before(tools.checkCredentials); -test.before(async () => { - // Create a test product for each test - try { - await productSearchClient.createProduct({ - parent: productSearchClient.locationPath( - testProduct.projectId, - testProduct.location - ), - productId: testProduct.productId, - product: { - displayName: testProduct.productDisplayName, - productCategory: testProduct.productCategory, - }, - }); - testProduct.createdProductPaths.push(testProduct.productPath); - } catch (err) {} // ignore error -}); - -test.after(async () => { - // Delete products after each test - testProduct.createdProductPaths.forEach(async path => { + before(async () => { + // Create a test product for each test try { - await productSearchClient.deleteProduct({name: path}); + await productSearchClient.createProduct({ + parent: productSearchClient.locationPath( + testProduct.projectId, + testProduct.location + ), + productId: testProduct.productId, + product: { + displayName: testProduct.productDisplayName, + productCategory: testProduct.productCategory, + }, + }); + testProduct.createdProductPaths.push(testProduct.productPath); } catch (err) {} // ignore error }); -}); -test(`should create reference image`, async t => { - const output = await tools.runAsync( - `${cmd} createReferenceImage "${testProduct.projectId}" "${ - testProduct.location - }" "${testProduct.productId}" "${testProduct.productReferenceImageId}" "${ - testProduct.productImageUri - }"`, - cwd - ); + after(async () => { + // Delete products after each test + testProduct.createdProductPaths.forEach(async path => { + try { + await productSearchClient.deleteProduct({name: path}); + } catch (err) {} // ignore error + }); + }); - t.true(output.includes(`response.uri: gs://`)); -}); + it(`should create reference image`, async () => { + const output = await tools.runAsync( + `${cmd} createReferenceImage "${testProduct.projectId}" "${ + testProduct.location + }" "${testProduct.productId}" "${testProduct.productReferenceImageId}" "${ + testProduct.productImageUri + }"`, + cwd + ); + + assert.ok(output.includes(`response.uri: gs://`)); + }); -test(`should delete reference image`, async t => { - const output = await tools.runAsync( - `${cmd} deleteReferenceImage "${testProduct.projectId}" "${ - testProduct.location - }" "${testProduct.productId}" "${testProduct.productReferenceImageId}"`, - cwd - ); + it(`should delete reference image`, async () => { + const output = await tools.runAsync( + `${cmd} deleteReferenceImage "${testProduct.projectId}" "${ + testProduct.location + }" "${testProduct.productId}" "${testProduct.productReferenceImageId}"`, + cwd + ); - t.true(output.includes(`Reference image deleted from product.`)); + assert.ok(output.includes(`Reference image deleted from product.`)); + }); }); diff --git a/samples/productSearch/system-test/similarProducts.v1p3beta1.test.js b/samples/productSearch/system-test/similarProducts.v1p3beta1.test.js index 53827b11..5b81e98c 100644 --- a/samples/productSearch/system-test/similarProducts.v1p3beta1.test.js +++ b/samples/productSearch/system-test/similarProducts.v1p3beta1.test.js @@ -18,7 +18,7 @@ const path = require(`path`); const vision = require('@google-cloud/vision').v1p3beta1; const productSearch = new vision.ProductSearchClient(); -const test = require(`ava`); +const assert = require('assert'); const tools = require(`@google-cloud/nodejs-repo-tools`); const cmd = `node similarProducts.v1p3beta1.js`; const cwd = path.join(__dirname, `..`); @@ -38,72 +38,83 @@ testSimilarProducts.productPath = productSearch.productSetPath( testSimilarProducts.location, testSimilarProducts.productSetId ); -test(`should check if similar product exists to one provided in local file with no filter`, async t => { - const output = await tools.runAsync( - `${cmd} getSimilarProductsFile "${testSimilarProducts.projectId}" "${ - testSimilarProducts.location - }" "${testSimilarProducts.productSetId}" "${ - testSimilarProducts.productCategory - }" "${localPath}" "${filter[0]}"`, - cwd - ); - t.true(output.includes(`Similar product information:`)); - t.true( - output.includes(`Product category: ${testSimilarProducts.productCategory}`) - ); - t.true(output.includes(`Product id: indexed_product_id_for_testing_1`)); - t.true(output.includes(`Product id: indexed_product_id_for_testing_2`)); -}); +describe(`similar products`, () => { + it(`should check if similar product exists to one provided in local file with no filter`, async () => { + const output = await tools.runAsync( + `${cmd} getSimilarProductsFile "${testSimilarProducts.projectId}" "${ + testSimilarProducts.location + }" "${testSimilarProducts.productSetId}" "${ + testSimilarProducts.productCategory + }" "${localPath}" "${filter[0]}"`, + cwd + ); -test(`should check if similar product exists to one provided in local file with filter`, async t => { - const output = await tools.runAsync( - `${cmd} getSimilarProductsFile "${testSimilarProducts.projectId}" "${ - testSimilarProducts.location - }" "${testSimilarProducts.productSetId}" "${ - testSimilarProducts.productCategory - }" "${localPath}" "${filter[1]}"`, - cwd - ); + assert.ok(output.includes(`Similar product information:`)); + assert.ok( + output.includes( + `Product category: ${testSimilarProducts.productCategory}` + ) + ); + assert.ok(output.includes(`Product id: indexed_product_id_for_testing_1`)); + assert.ok(output.includes(`Product id: indexed_product_id_for_testing_2`)); + }); - t.true(output.includes(`Similar product information:`)); - t.true( - output.includes(`Product category: ${testSimilarProducts.productCategory}`) - ); - t.true(output.includes(`Product id: indexed_product_id_for_testing_1`)); -}); + it(`should check if similar product exists to one provided in local file with filter`, async () => { + const output = await tools.runAsync( + `${cmd} getSimilarProductsFile "${testSimilarProducts.projectId}" "${ + testSimilarProducts.location + }" "${testSimilarProducts.productSetId}" "${ + testSimilarProducts.productCategory + }" "${localPath}" "${filter[1]}"`, + cwd + ); -test(`should check if similar product exists to one provided in GCS file with no filter`, async t => { - const output = await tools.runAsync( - `${cmd} getSimilarProductsGcs "${testSimilarProducts.projectId}" "${ - testSimilarProducts.location - }" "${testSimilarProducts.productSetId}" "${ - testSimilarProducts.productCategory - }" "${gcsUri}" "${filter[0]}"`, - cwd - ); + assert.ok(output.includes(`Similar product information:`)); + assert.ok( + output.includes( + `Product category: ${testSimilarProducts.productCategory}` + ) + ); + assert.ok(output.includes(`Product id: indexed_product_id_for_testing_1`)); + }); - t.true(output.includes(`Similar product information:`)); - t.true( - output.includes(`Product category: ${testSimilarProducts.productCategory}`) - ); - t.true(output.includes(`Product id: indexed_product_id_for_testing_1`)); - t.true(output.includes(`Product id: indexed_product_id_for_testing_2`)); -}); + it(`should check if similar product exists to one provided in GCS file with no filter`, async () => { + const output = await tools.runAsync( + `${cmd} getSimilarProductsGcs "${testSimilarProducts.projectId}" "${ + testSimilarProducts.location + }" "${testSimilarProducts.productSetId}" "${ + testSimilarProducts.productCategory + }" "${gcsUri}" "${filter[0]}"`, + cwd + ); + + assert.ok(output.includes(`Similar product information:`)); + assert.ok( + output.includes( + `Product category: ${testSimilarProducts.productCategory}` + ) + ); + assert.ok(output.includes(`Product id: indexed_product_id_for_testing_1`)); + assert.ok(output.includes(`Product id: indexed_product_id_for_testing_2`)); + }); -test(`should check if similar product exists to one provided in GCS file with filter`, async t => { - const output = await tools.runAsync( - `${cmd} getSimilarProductsGcs "${testSimilarProducts.projectId}" "${ - testSimilarProducts.location - }" "${testSimilarProducts.productSetId}" "${ - testSimilarProducts.productCategory - }" "${gcsUri}" "${filter[1]}"`, - cwd - ); + it(`should check if similar product exists to one provided in GCS file with filter`, async () => { + const output = await tools.runAsync( + `${cmd} getSimilarProductsGcs "${testSimilarProducts.projectId}" "${ + testSimilarProducts.location + }" "${testSimilarProducts.productSetId}" "${ + testSimilarProducts.productCategory + }" "${gcsUri}" "${filter[1]}"`, + cwd + ); - t.true(output.includes(`Similar product information:`)); - t.true( - output.includes(`Product category: ${testSimilarProducts.productCategory}`) - ); - t.true(output.includes(`Product id: indexed_product_id_for_testing_1`)); + assert.ok(output.includes(`Similar product information:`)); + assert.ok( + output.includes( + `Product category: ${testSimilarProducts.productCategory}` + ) + ); + assert.ok(output.includes(`Product id: indexed_product_id_for_testing_1`)); + }); }); diff --git a/samples/quickstart.js b/samples/quickstart.js index 9afcff3d..5613b0f6 100644 --- a/samples/quickstart.js +++ b/samples/quickstart.js @@ -23,15 +23,13 @@ const vision = require('@google-cloud/vision'); const client = new vision.ImageAnnotatorClient(); // Performs label detection on the image file -client - .labelDetection('./resources/wakeupcat.jpg') - .then(results => { - const labels = results[0].labelAnnotations; - - console.log('Labels:'); - labels.forEach(label => console.log(label.description)); - }) - .catch(err => { - console.error('ERROR:', err); - }); +async function main() { + const [result] = await client.labelDetection('./resources/wakeupcat.jpg'); + const labels = result.labelAnnotations; + console.log('Labels:'); + labels.forEach(label => console.log(label.description)); +} +main().catch(err => { + console.error('ERROR:', err); +}); // [END vision_quickstart] diff --git a/samples/system-test/.eslintrc.yml b/samples/system-test/.eslintrc.yml index 8e078abb..0ab526f5 100644 --- a/samples/system-test/.eslintrc.yml +++ b/samples/system-test/.eslintrc.yml @@ -1,4 +1,6 @@ --- +env: + mocha: true rules: node/no-unpublished-require: off no-empty: off diff --git a/samples/system-test/detect.test.js b/samples/system-test/detect.test.js index 20b8f7a3..1e7eff86 100644 --- a/samples/system-test/detect.test.js +++ b/samples/system-test/detect.test.js @@ -17,9 +17,9 @@ const path = require(`path`); const {Storage} = require(`@google-cloud/storage`); -const test = require(`ava`); const tools = require(`@google-cloud/nodejs-repo-tools`); const uuid = require(`uuid`); +const assert = require('assert'); const vision = require('@google-cloud/vision'); const client = new vision.ImageAnnotatorClient(); @@ -45,280 +45,284 @@ const files = [ }; }); -test.before(tools.checkCredentials); -test.before(async () => { - const [bucket] = await storage.createBucket(bucketName); - await Promise.all(files.map(file => bucket.upload(file.localPath))); -}); - -test.after.always(async () => { - const bucket = storage.bucket(bucketName); - await bucket.deleteFiles({force: true}); - await bucket.deleteFiles({force: true}); // Try a second time... - await bucket.delete(); -}); - -test(`should detect faces in a local file`, async t => { - const output = await tools.runAsync( - `${cmd} faces ${files[0].localPath}`, - cwd - ); - t.true(output.includes(`Faces:`)); - t.true(output.includes(`Face #1:`)); -}); - -test(`should detect faces in a remote file`, async t => { - const output = await tools.runAsync( - `${cmd} faces-gcs ${bucketName} ${files[0].name}`, - cwd - ); - t.true(output.includes(`Faces:`)); - t.true(output.includes(`Face #1:`)); -}); - -test(`should detect labels in a local file`, async t => { - const output = await tools.runAsync( - `${cmd} labels ${files[4].localPath}`, - cwd - ); - t.true(output.includes(`Labels:`)); - t.true(output.includes(`cat`)); -}); - -test(`should detect labels in a remote file`, async t => { - const output = await tools.runAsync( - `${cmd} labels-gcs ${bucketName} ${files[4].name}`, - cwd - ); - t.true(output.includes(`Labels:`)); - t.true(output.includes(`cat`)); -}); - -test(`should detect landmarks in a local file`, async t => { - const output = await tools.runAsync( - `${cmd} landmarks ${files[1].localPath}`, - cwd - ); - t.true(output.includes(`Landmarks:`)); - t.true(output.includes(`Palace of Fine Arts`)); -}); - -test(`should detect landmarks in a remote file`, async t => { - const output = await tools.runAsync( - `${cmd} landmarks-gcs ${bucketName} ${files[1].name}`, - cwd - ); - t.true(output.includes(`Landmarks:`)); - t.true(output.includes(`Palace of Fine Arts`)); -}); - -test(`should detect text in a local file`, async t => { - const output = await tools.runAsync(`${cmd} text ${files[3].localPath}`, cwd); - t.true(output.includes(`Text:`)); - t.true(output.includes(`System Software Update`)); -}); - -test(`should detect text in a remote file`, async t => { - const output = await tools.runAsync( - `${cmd} text-gcs ${bucketName} ${files[3].name}`, - cwd - ); - t.true(output.includes(`Text:`)); - t.true(output.includes(`System Software Update`)); -}); - -test(`should detect logos in a local file`, async t => { - const output = await tools.runAsync( - `${cmd} logos ${files[2].localPath}`, - cwd - ); - t.true(output.includes(`Logos:`)); - t.true(output.includes(`Google`)); -}); - -test(`should detect logos in a remote file`, async t => { - const output = await tools.runAsync( - `${cmd} logos-gcs ${bucketName} ${files[2].name}`, - cwd - ); - t.true(output.includes(`Logos:`)); - t.true(output.includes(`Google`)); -}); - -test(`should detect properties in a local file`, async t => { - const output = await tools.runAsync( - `${cmd} properties ${files[1].localPath}`, - cwd - ); - t.true(output.includes(`{ color: { red: 69, green: 42, blue: 27`)); - t.true(output.split(`\n`).length > 4, `Multiple colors were detected.`); -}); - -test(`should detect properties in a remote file`, async t => { - const output = await tools.runAsync( - `${cmd} properties-gcs ${bucketName} ${files[1].name}`, - cwd - ); - t.true(output.includes(`{ color: { red: 69, green: 42, blue: 27`)); - t.true(output.split(`\n`).length > 4, `Multiple colors were detected.`); -}); - -test(`should detect safe-search in a local file`, async t => { - const output = await tools.runAsync( - `${cmd} safe-search ${files[4].localPath}`, - cwd - ); - t.true(output.includes('VERY_LIKELY')); - t.true(output.includes('Racy:')); -}); - -test(`should detect safe-search in a remote file`, async t => { - const output = await tools.runAsync( - `${cmd} safe-search-gcs ${bucketName} ${files[4].name}`, - cwd - ); - t.true(output.includes(`Medical:`)); -}); - -test(`should detect crop hints in a local file`, async t => { - const output = await tools.runAsync( - `${cmd} crops ${files[2].localPath}`, - cwd - ); - t.true(output.includes(`Crop Hint 0:`)); - t.true(output.includes(`Bound 2: (280, 43)`)); -}); - -test(`should detect crop hints in a remote file`, async t => { - const output = await tools.runAsync( - `${cmd} crops-gcs ${bucketName} ${files[2].name}`, - cwd - ); - t.true(output.includes(`Crop Hint 0:`)); - t.true(output.includes(`Bound 2: (280, 43)`)); -}); - -test(`should detect similar web images in a local file`, async t => { - const output = await tools.runAsync(`${cmd} web ${files[5].localPath}`, cwd); - - const [results] = await client.webDetection(files[5].localPath); - const webDetection = results.webDetection; - - if (webDetection.fullMatchingImages.length) { - t.true(output.includes('Full matches found:')); - } - - if (webDetection.partialMatchingImages.length) { - t.true(output.includes('Partial matches found:')); - } - - if (webDetection.webEntities.length) { - t.true(output.includes('Web entities found:')); - t.true(output.includes('Description: Google Cloud Platform')); - } - - if (webDetection.bestGuessLabels.length) { - t.true(output.includes('Best guess labels found')); - t.true(output.includes('Label:')); - } -}); - -test(`should detect similar web images in a remote file`, async t => { - const output = await tools.runAsync( - `${cmd} web-gcs ${bucketName} ${files[5].name}`, - cwd - ); - - const [results] = await client.webDetection( - `gs://${bucketName}/${files[5].name}` - ); - const webDetection = results.webDetection; - - if (webDetection.fullMatchingImages.length) { - t.true(output.includes('Full matches found:')); - } - - if (webDetection.partialMatchingImages.length) { - t.true(output.includes('Partial matches found:')); - } - - if (webDetection.webEntities.length) { - t.true(output.includes('Web entities found:')); - t.true(output.includes('Description: Google Cloud Platform')); - } - - if (webDetection.bestGuessLabels.length) { - t.true(output.includes('Best guess labels found')); - t.true(output.includes('Label:')); - } -}); - -test(`should detect web entities with geo metadata in local file`, async t => { - const output = await tools.runAsync( - `${cmd} web-geo ${files[1].localPath}`, - cwd - ); - t.true(output.includes('Description:')); - t.true(output.includes('Score:')); - t.true(output.includes('Rome')); -}); - -test(`should detect web entities with geo metadata in remote file`, async t => { - const output = await tools.runAsync( - `${cmd} web-geo-gcs ${bucketName} ${files[1].name}`, - cwd - ); - t.true(output.includes('Description:')); - t.true(output.includes('Score:')); - t.true(output.includes('Rome')); -}); - -test(`should read a document from a local file`, async t => { - const output = await tools.runAsync( - `${cmd} fulltext ${files[2].localPath}`, - cwd - ); - t.true(output.includes('Google Cloud Platform')); - t.true(output.includes('Word text: Cloud')); - t.true(output.includes('Word confidence: 0.9')); -}); - -test(`should read a document from a remote file`, async t => { - const output = await tools.runAsync( - `${cmd} fulltext-gcs ${bucketName} ${files[2].name}`, - cwd - ); - t.true(output.includes('Google Cloud Platform')); -}); - -test(`should extract text from pdf file`, async t => { - const output = await tools.runAsync( - `${cmd} pdf ${bucketName} ${files[7].name}`, - cwd - ); - t.true(output.includes('pdf-ocr.pdf.json')); -}); - -test(`should detect objects in a local file`, async t => { - const output = await tools.runAsync( - `${cmd} localize-objects ${files[8].localPath}`, - cwd - ); - t.true( - output.includes(`Name: Bird`) && - output.includes(`Name: Duck`) && - output.includes(`Name: Toy`) - ); -}); - -test(`should detect objects in a remote file`, async t => { - const output = await tools.runAsync( - `${cmd} localize-objects-gcs gs://${bucketName}/${files[8].name}`, - cwd - ); - t.true( - output.includes(`Name: Bird`) && - output.includes(`Name: Duck`) && - output.includes(`Name: Toy`) - ); +describe(`detect`, () => { + before(async () => { + tools.checkCredentials; + const [bucket] = await storage.createBucket(bucketName); + await Promise.all(files.map(file => bucket.upload(file.localPath))); + }); + + after(async () => { + const bucket = storage.bucket(bucketName); + await bucket.deleteFiles({force: true}); + await bucket.deleteFiles({force: true}); // Try a second time... + await bucket.delete(); + }); + + it(`should detect faces in a local file`, async () => { + const output = await tools.runAsync( + `${cmd} faces ${files[0].localPath}`, + cwd + ); + assert.ok(output.includes(`Faces:`)); + assert.ok(output.includes(`Face #1:`)); + }); + + it(`should detect faces in a remote file`, async () => { + const output = await tools.runAsync( + `${cmd} faces-gcs ${bucketName} ${files[0].name}`, + cwd + ); + assert.ok(output.includes(`Faces:`)); + assert.ok(output.includes(`Face #1:`)); + }); + + it(`should detect labels in a local file`, async () => { + const output = await tools.runAsync( + `${cmd} labels ${files[4].localPath}`, + cwd + ); + assert.ok(output.includes(`Labels:`)); + assert.ok(output.includes(`cat`)); + }); + + it(`should detect labels in a remote file`, async () => { + const output = await tools.runAsync( + `${cmd} labels-gcs ${bucketName} ${files[4].name}`, + cwd + ); + assert.ok(output.includes(`Labels:`)); + assert.ok(output.includes(`cat`)); + }); + + it(`should detect landmarks in a local file`, async () => { + const output = await tools.runAsync( + `${cmd} landmarks ${files[1].localPath}`, + cwd + ); + assert.ok(output.includes(`Landmarks:`)); + assert.ok(output.includes(`Palace of Fine Arts`)); + }); + + it(`should detect landmarks in a remote file`, async () => { + const output = await tools.runAsync( + `${cmd} landmarks-gcs ${bucketName} ${files[1].name}`, + cwd + ); + assert.ok(output.includes(`Landmarks:`)); + assert.ok(output.includes(`Palace of Fine Arts`)); + }); + + it(`should detect text in a local file`, async () => { + const output = await tools.runAsync( + `${cmd} text ${files[3].localPath}`, + cwd + ); + assert.ok(output.includes(`Text:`)); + assert.ok(output.includes(`System Software Update`)); + }); + + it(`should detect text in a remote file`, async () => { + const output = await tools.runAsync( + `${cmd} text-gcs ${bucketName} ${files[3].name}`, + cwd + ); + assert.ok(output.includes(`Text:`)); + assert.ok(output.includes(`System Software Update`)); + }); + + it(`should detect logos in a local file`, async () => { + const output = await tools.runAsync( + `${cmd} logos ${files[2].localPath}`, + cwd + ); + assert.ok(output.includes(`Logos:`)); + assert.ok(output.includes(`Google`)); + }); + + it(`should detect logos in a remote file`, async () => { + const output = await tools.runAsync( + `${cmd} logos-gcs ${bucketName} ${files[2].name}`, + cwd + ); + assert.ok(output.includes(`Logos:`)); + assert.ok(output.includes(`Google`)); + }); + + it(`should detect properties in a local file`, async () => { + const output = await tools.runAsync( + `${cmd} properties ${files[1].localPath}`, + cwd + ); + assert.ok(output.includes(`{ color: { red: 69, green: 42, blue: 27`)); + assert.ok(output.split(`\n`).length > 4, `Multiple colors were detected.`); + }); + + it(`should detect properties in a remote file`, async () => { + const output = await tools.runAsync( + `${cmd} properties-gcs ${bucketName} ${files[1].name}`, + cwd + ); + assert.ok(output.includes(`{ color: { red: 69, green: 42, blue: 27`)); + assert.ok(output.split(`\n`).length > 4, `Multiple colors were detected.`); + }); + + it(`should detect safe-search in a local file`, async () => { + const output = await tools.runAsync( + `${cmd} safe-search ${files[4].localPath}`, + cwd + ); + assert.ok(output.includes(`VERY_LIKELY`)); + assert.ok(output.includes(`Racy:`)); + }); + + it(`should detect safe-search in a remote file`, async () => { + const output = await tools.runAsync( + `${cmd} safe-search-gcs ${bucketName} ${files[4].name}`, + cwd + ); + assert.ok(output.includes(`Medical:`)); + }); + + it(`should detect crop hints in a local file`, async () => { + const output = await tools.runAsync( + `${cmd} crops ${files[2].localPath}`, + cwd + ); + assert.ok(output.includes(`Crop Hint 0:`)); + assert.ok(output.includes(`Bound 2: (280, 43)`)); + }); + + it(`should detect crop hints in a remote file`, async () => { + const output = await tools.runAsync( + `${cmd} crops-gcs ${bucketName} ${files[2].name}`, + cwd + ); + assert.ok(output.includes(`Crop Hint 0:`)); + assert.ok(output.includes(`Bound 2: (280, 43)`)); + }); + + it(`should detect similar web images in a local file`, async () => { + const output = await tools.runAsync( + `${cmd} web ${files[5].localPath}`, + cwd + ); + + const [results] = await client.webDetection(files[5].localPath); + const webDetection = results.webDetection; + + if (webDetection.fullMatchingImages.length) { + assert.ok(output.includes(`Full matches found:`)); + } + + if (webDetection.partialMatchingImages.length) { + assert.ok(output.includes(`Partial matches found:`)); + } + + if (webDetection.webEntities.length) { + assert.ok(output.includes(`Web entities found:`)); + assert.ok(output.includes(`Description: Google Cloud Platform`)); + } + + if (webDetection.bestGuessLabels.length) { + assert.ok(output.includes(`Best guess labels found`)); + assert.ok(output.includes(`Label:`)); + } + }); + + it(`should detect similar web images in a remote file`, async () => { + const output = await tools.runAsync( + `${cmd} web-gcs ${bucketName} ${files[5].name}`, + cwd + ); + + const [results] = await client.webDetection( + `gs://${bucketName}/${files[5].name}` + ); + const webDetection = results.webDetection; + + if (webDetection.fullMatchingImages.length) { + assert.ok(output.includes(`Full matches found:`)); + } + + if (webDetection.partialMatchingImages.length) { + assert.ok(output.includes(`Partial matches found:`)); + } + + if (webDetection.webEntities.length) { + assert.ok(output.includes(`Web entities found:`)); + assert.ok(output.includes(`Description: Google Cloud Platform`)); + } + + if (webDetection.bestGuessLabels.length) { + assert.ok(output.includes(`Best guess labels found`)); + assert.ok(output.includes(`Label:`)); + } + }); + + it(`should detect web entities with geo metadata in local file`, async () => { + const output = await tools.runAsync( + `${cmd} web-geo ${files[1].localPath}`, + cwd + ); + assert.ok(output.includes(`Description:`)); + assert.ok(output.includes(`Score:`)); + assert.ok(output.includes(`Rome`)); + }); + + it(`should detect web entities with geo metadata in remote file`, async () => { + const output = await tools.runAsync( + `${cmd} web-geo-gcs ${bucketName} ${files[1].name}`, + cwd + ); + assert.ok(output.includes(`Description:`)); + assert.ok(output.includes(`Score:`)); + assert.ok(output.includes(`Rome`)); + }); + + it(`should read a document from a local file`, async () => { + const output = await tools.runAsync( + `${cmd} fulltext ${files[2].localPath}`, + cwd + ); + assert.ok(output.includes(`Google Cloud Platform`)); + assert.ok(output.includes(`Word text: Cloud`)); + assert.ok(output.includes(`Word confidence: 0.9`)); + }); + + it(`should read a document from a remote file`, async () => { + const output = await tools.runAsync( + `${cmd} fulltext-gcs ${bucketName} ${files[2].name}`, + cwd + ); + assert.ok(output.includes(`Google Cloud Platform`)); + }); + + it(`should extract text from pdf file`, async () => { + const output = await tools.runAsync( + `${cmd} pdf ${bucketName} ${files[7].name}`, + cwd + ); + assert.ok(output.includes(`pdf-ocr.pdf.json`)); + }); + + it(`should detect objects in a local file`, async () => { + const output = await tools.runAsync( + `${cmd} localize-objects ${files[8].localPath}`, + cwd + ); + assert.ok(output.includes(`Name: Bird`)); + assert.ok(output.includes(`Name: Duck`)); + assert.ok(output.includes(`Name: Toy`)); + }); + + it(`should detect objects in a remote file`, async () => { + const output = await tools.runAsync( + `${cmd} localize-objects-gcs gs://${bucketName}/${files[8].name}`, + cwd + ); + assert.ok(output.includes(`Name: Bird`)); + assert.ok(output.includes(`Name: Duck`)); + assert.ok(output.includes(`Name: Toy`)); + }); }); diff --git a/samples/system-test/detect.v1p1beta1.test.js b/samples/system-test/detect.v1p1beta1.test.js index f3147a38..6fe8438a 100644 --- a/samples/system-test/detect.v1p1beta1.test.js +++ b/samples/system-test/detect.v1p1beta1.test.js @@ -16,8 +16,8 @@ 'use strict'; const path = require(`path`); -const test = require(`ava`); const tools = require(`@google-cloud/nodejs-repo-tools`); +const assert = require('assert'); const cmd = `node detect.v1p1beta1.js`; const cwd = path.join(__dirname, `..`); @@ -30,36 +30,43 @@ const files = [`text.jpg`, `wakeupcat.jpg`, `landmark.jpg`, `city.jpg`].map( } ); -test.before(tools.checkCredentials); +describe(`detect v1 p1 beta1`, () => { + before(async () => { + tools.checkCredentials; + }); -test(`should extract text from image file and print confidence`, async t => { - const output = await tools.runAsync( - `${cmd} fulltext ${files[0].localPath}`, - cwd - ); - t.true(output.includes('Word text: class')); - t.true(output.includes('Word confidence:')); -}); + it(`should extract text from image file and print confidence`, async () => { + const output = await tools.runAsync( + `${cmd} fulltext ${files[0].localPath}`, + cwd + ); + assert.ok(output.includes(`Word text: class`)); + assert.ok(output.includes(`Word confidence:`)); + }); -test(`should detect safe search properties from image file`, async t => { - const output = await tools.runAsync( - `${cmd} safe-search ${files[1].localPath}`, - cwd - ); - t.true(output.includes('VERY_LIKELY')); - t.true(output.includes('Racy:')); -}); + it(`should detect safe search properties from image file`, async () => { + const output = await tools.runAsync( + `${cmd} safe-search ${files[1].localPath}`, + cwd + ); + assert.ok(output.includes(`VERY_LIKELY`)); + assert.ok(output.includes(`Racy:`)); + }); -test(`should detect web entities including best guess labels`, async t => { - const output = await tools.runAsync(`${cmd} web ${files[2].localPath}`, cwd); - t.true(output.includes('Description: Palace of Fine Arts Theatre')); - t.true(output.includes('Best guess label: palace of fine arts')); -}); + it(`should detect web entities including best guess labels`, async () => { + const output = await tools.runAsync( + `${cmd} web ${files[2].localPath}`, + cwd + ); + assert.ok(output.includes(`Description: Palace of Fine Arts Theatre`)); + assert.ok(output.includes(`Best guess label: palace of fine arts`)); + }); -test(`should detect web entities using geographical metadata`, async t => { - const output = await tools.runAsync( - `${cmd} web-entities-geo ${files[3].localPath}`, - cwd - ); - t.true(output.includes('Electra')); + it(`should detect web entities using geographical metadata`, async () => { + const output = await tools.runAsync( + `${cmd} web-entities-geo ${files[3].localPath}`, + cwd + ); + assert.ok(output.includes(`Electra`)); + }); }); diff --git a/samples/system-test/detect.v1p3beta1.test.js b/samples/system-test/detect.v1p3beta1.test.js index 8c5c97cc..35a3180c 100644 --- a/samples/system-test/detect.v1p3beta1.test.js +++ b/samples/system-test/detect.v1p3beta1.test.js @@ -17,8 +17,8 @@ const path = require(`path`); const {Storage} = require(`@google-cloud/storage`); -const test = require(`ava`); const tools = require(`@google-cloud/nodejs-repo-tools`); +const assert = require('assert'); const uuid = require(`uuid`); const storage = new Storage(); @@ -35,33 +35,33 @@ const files = [`duck_and_truck.jpg`, `handwritten.jpg`, `bicycle.jpg`].map( } ); -test.before(tools.checkCredentials); -test.before(async () => { - const [bucket] = await storage.createBucket(bucketName); - await Promise.all(files.map(file => bucket.upload(file.localPath))); -}); - -test.after.always(async () => { - const bucket = storage.bucket(bucketName); - await bucket.deleteFiles({force: true}); - await bucket.deleteFiles({force: true}); // Try a second time... - await bucket.delete(); -}); +describe(`detect v1 p3 beta1`, () => { + before(async () => { + tools.checkCredentials; + const [bucket] = await storage.createBucket(bucketName); + await Promise.all(files.map(file => bucket.upload(file.localPath))); + }); -test.before(tools.checkCredentials); + after(async () => { + const bucket = storage.bucket(bucketName); + await bucket.deleteFiles({force: true}); + await bucket.deleteFiles({force: true}); // Try a second time... + await bucket.delete(); + }); -test(`should read handwriting in local handwritten.jpg sample`, async t => { - const output = await tools.runAsync( - `${cmd} detectHandwriting ${files[1]}`, - cwd - ); - t.true(output.includes(`hand written message`)); -}); + it(`should read handwriting in local handwritten.jpg sample`, async () => { + const output = await tools.runAsync( + `${cmd} detectHandwriting ${files[1]}`, + cwd + ); + assert.strictEqual(output.includes(`hand written message`), true); + }); -test(`should read handwriting from handwritten.jpg in GCS bucket`, async t => { - const output = await tools.runAsync( - `${cmd} detectHandwritingGCS gs://${bucketName}/${files[1].name}`, - cwd - ); - t.true(output.includes(`hand written message`)); + it(`should read handwriting from handwritten.jpg in GCS bucket`, async () => { + const output = await tools.runAsync( + `${cmd} detectHandwritingGCS gs://${bucketName}/${files[1].name}`, + cwd + ); + assert.strictEqual(output.includes(`hand written message`), true); + }); }); diff --git a/samples/system-test/faceDetection.test.js b/samples/system-test/faceDetection.test.js index 811e7f62..e6edabc4 100644 --- a/samples/system-test/faceDetection.test.js +++ b/samples/system-test/faceDetection.test.js @@ -17,7 +17,7 @@ const fs = require(`fs`); const path = require(`path`); -const test = require(`ava`); +const assert = require('assert'); const tools = require(`@google-cloud/nodejs-repo-tools`); class MockCanvas { @@ -53,28 +53,36 @@ const faceDetectionExample = require(`../faceDetection`); const inputFile = path.join(__dirname, `../resources`, `face.png`); const outputFile = path.join(__dirname, `../../vision`, `out.png`); -test.before(tools.checkCredentials); -test.before(tools.stubConsole); -test.after.always(tools.restoreConsole); +describe(`face detection`, () => { + before(tools.checkCredentials); + before(tools.stubConsole); -test.cb(`should detect faces`, t => { - let done = false; - const timeout = setTimeout(() => { - if (!done) { - console.warn('Face detection timed out!'); - t.end(); - } - }, 30); - faceDetectionExample.main(inputFile, outputFile, MockCanvas, (err, faces) => { - t.ifError(err); - t.is(faces.length, 1); - const image = fs.readFileSync(outputFile); - t.is(image.toString(`utf8`), `testfoobar`); - t.true(console.log.calledWith(`Found 1 face`)); - t.true(console.log.calledWith(`Highlighting...`)); - t.true(console.log.calledWith(`Finished!`)); - done = true; - clearTimeout(timeout); - t.end(); + after(tools.restoreConsole); + + it(`should detect faces`, async () => { + let done = false; + const timeout = setTimeout(() => { + if (!done) { + console.warn('Face detection timed out!'); + } + }, 60); + + faceDetectionExample.main( + inputFile, + outputFile, + MockCanvas, + (err, faces) => { + assert.ifError(err); + assert.strictEqual(faces.length, 1); + + const image = fs.readFileSync(outputFile); + assert.strictEqual(image.toString(`utf8`), `testfoobar`); + assert.ok(console.log.calledWith(`Found 1 face`)); + assert.ok(console.log.calledWith(`Highlighting...`)); + assert.ok(console.log.calledWith(`Finished!`)); + done = true; + clearTimeout(timeout); + } + ); }); }); diff --git a/samples/system-test/quickstart.test.js b/samples/system-test/quickstart.test.js index f4850c23..d15b0906 100644 --- a/samples/system-test/quickstart.test.js +++ b/samples/system-test/quickstart.test.js @@ -16,17 +16,19 @@ 'use strict'; const path = require(`path`); -const test = require(`ava`); +const assert = require('assert'); const tools = require(`@google-cloud/nodejs-repo-tools`); const cmd = `node quickstart.js`; const cwd = path.join(__dirname, `..`); -test.before(tools.stubConsole); -test.after.always(tools.restoreConsole); +describe(`quickstart`, () => { + before(tools.stubConsole); + after(tools.restoreConsole); -test(`should detect labels in a remote file`, async t => { - const output = await tools.runAsync(`${cmd}`, cwd); - t.true(output.includes(`Labels:`)); - t.true(output.includes(`cat`)); + it(`should detect labels in a remote file`, async () => { + const output = await tools.runAsync(`${cmd}`, cwd); + assert.ok(output.includes(`Labels:`)); + assert.ok(output.includes(`cat`)); + }); }); diff --git a/samples/system-test/textDetection.test.js b/samples/system-test/textDetection.test.js index 67d5333a..a19be9ab 100644 --- a/samples/system-test/textDetection.test.js +++ b/samples/system-test/textDetection.test.js @@ -16,37 +16,50 @@ 'use strict'; const path = require(`path`); -const test = require(`ava`); +const assert = require('assert'); const tools = require(`@google-cloud/nodejs-repo-tools`); -test.before(tools.checkCredentials); +describe(`Text Detection`, () => { + before(async () => { + tools.checkCredentials; + }); -test.cb(`should detect texts`, t => { - const redis = require('redis'); - const client = redis.createClient(); - client - .on('error', err => { - if (err && err.code === 'ECONNREFUSED') { - console.error( - 'Redis is unavailable. Skipping vision textDetection test.' - ); - t.end(); - } else { - t.end(err); - } - }) - .on('ready', () => { - const inputDir = path.join(__dirname, `../resources`); - const textDetectionSample = require(`../textDetection`); - textDetectionSample.main(inputDir, (err, textResponse) => { - t.ifError(err); - t.true(Object.keys(textResponse).length > 0); - textDetectionSample.lookup(['the', 'sunbeams', 'in'], (err, hits) => { - t.ifError(err); - t.true(hits.length > 0); - t.true(hits[0].length > 0); - t.end(); - }); + it(`should detect texts`, done => { + const redis = require('redis'); + const client = redis.createClient(); + + client + .on('error', err => { + if (err && err.code === 'ECONNREFUSED') { + console.error( + 'Redis is unavailable. Skipping vision textDetection test.' + ); + client.end(true); + done(); + } else { + client.end(true); + done(err); + } + }) + .on('ready', async () => { + const inputDir = path.join(__dirname, `../resources`); + const textDetectionSample = require(`../textDetection`); + + const textResponse = await textDetectionSample + .main(inputDir) + .catch(err => { + console.log(`Error at 46: ${err}`); + }); + assert.ok(Object.keys(textResponse).length > 0); + + const hits = await textDetectionSample + .lookup(['the', 'sunbeams', 'in']) + .catch(err => { + console.log(`Error at 51: ${err}`); + }); + assert.ok(hits.length > 0); + assert.ok(hits.length > 0); + assert.ok(hits[0].length > 0); }); - }); + }); }); diff --git a/samples/textDetection.js b/samples/textDetection.js index 18dfffcc..d7465197 100644 --- a/samples/textDetection.js +++ b/samples/textDetection.js @@ -113,17 +113,19 @@ Index.prototype.setContainsNoText = function(filename, callback) { this.docsClient.set(filename, '', callback); }; -function lookup(words, callback) { - const index = new Index(); - index.lookup(words, function(err, hits) { - index.quit(); - if (err) { - return callback(err); - } - words.forEach(function(word, i) { - console.log('hits for "' + word + '":', hits[i].join(', ')); +function lookup(words) { + return new Promise((resolve, reject) => { + const index = new Index(); + index.lookup(words, function(err, hits) { + index.quit(); + if (err) { + return reject(err); + } + words.forEach(function(word, i) { + console.log('hits for "' + word + '":', hits[i].join(', ')); + }); + resolve(hits); }); - callback(null, hits); }); } @@ -185,74 +187,79 @@ function getTextFromFiles(index, inputFiles, callback) { } // Run the example -function main(inputDir, callback) { - const index = new Index(); +function main(inputDir) { + return new Promise((resolve, reject) => { + const index = new Index(); - async.waterfall( - [ - // Scan the specified directory for files - function(cb) { - fs.readdir(inputDir, cb); - }, - // Separate directories from files - function(files, cb) { - async.parallel( - files.map(function(file) { - const filename = path.join(inputDir, file); - return function(cb) { - fs.stat(filename, function(err, stats) { - if (err) { - return cb(err); - } - if (!stats.isDirectory()) { - return cb(null, filename); - } - cb(); - }); - }; - }), - cb - ); - }, - // Figure out which files have already been processed - function(allImageFiles, cb) { - const tasks = allImageFiles - .filter(function(filename) { + async.waterfall( + [ + // Scan the specified directory for files + function(cb) { + fs.readdir(inputDir, cb); + }, + // Separate directories from files + function(files, cb) { + async.parallel( + files.map(function(file) { + const filename = path.join(inputDir, file); + return function(cb) { + fs.stat(filename, function(err, stats) { + if (err) { + return cb(err); + } + if (!stats.isDirectory()) { + return cb(null, filename); + } + cb(); + }); + }; + }), + cb + ); + }, + // Figure out which files have already been processed + function(allImageFiles, cb) { + const tasks = allImageFiles + .filter(function(filename) { + return filename; + }) + .map(function(filename) { + return function(cb) { + index.documentIsProcessed(filename, function(err, processed) { + if (err) { + return cb(err); + } + if (!processed) { + // Forward this filename on for further processing + return cb(null, filename); + } + cb(); + }); + }; + }); + async.parallel(tasks, cb); + }, + // Analyze any remaining unprocessed files + function(imageFilesToProcess, cb) { + imageFilesToProcess = imageFilesToProcess.filter(function(filename) { return filename; - }) - .map(function(filename) { - return function(cb) { - index.documentIsProcessed(filename, function(err, processed) { - if (err) { - return cb(err); - } - if (!processed) { - // Forward this filename on for further processing - return cb(null, filename); - } - cb(); - }); - }; }); - async.parallel(tasks, cb); - }, - // Analyze any remaining unprocessed files - function(imageFilesToProcess, cb) { - imageFilesToProcess = imageFilesToProcess.filter(function(filename) { - return filename; - }); - if (imageFilesToProcess.length) { - return getTextFromFiles(index, imageFilesToProcess, cb); + if (imageFilesToProcess.length) { + return getTextFromFiles(index, imageFilesToProcess, cb); + } + console.log('All files processed!'); + cb(); + }, + ], + function(err, result) { + index.quit(); + if (err) { + return reject(err); } - console.log('All files processed!'); - cb(); - }, - ], - function(err, result) { - index.quit(); - callback(err, result); - } - ); + resolve(result); + } + ); + }); } if (module === require.main) {