Batch annotate files asynchronously (v1p4beta1)

Asynchronously detect text in a PDF file stored in Cloud Storage and save the annotation results to Cloud Storage.

Code sample

Node.js

Before trying this sample, follow the Node.js setup instructions in the Vision quickstart using client libraries. For more information, see the Vision Node.js API reference documentation.

To authenticate to Vision, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

'use strict';

const {ImageAnnotatorClient} = require('@google-cloud/vision');
const {status} = require('@grpc/grpc-js');

const client = new ImageAnnotatorClient();

/**
 * Use the asyncBatchAnnotateFiles method
 *
 * @param {string} gcsSourceUri - Google Cloud Storage URI of the input file (for example, 'gs://example-bucket/example.pdf').
 * @param {string} gcsDestinationUri - Google Cloud Storage URI prefix where annotation results will be stored (for example, 'gs://example-bucket/output/').
 */
async function asyncBatchAnnotateFiles(gcsSourceUri, gcsDestinationUri) {
  try {
    const inputConfig = {
      gcsSource: {
        uri: gcsSourceUri,
      },
      mimeType: 'application/pdf',
    };

    const features = [
      {
        type: 'DOCUMENT_TEXT_DETECTION',
      },
    ];

    const outputConfig = {
      gcsDestination: {
        uri: gcsDestinationUri,
      },
    };

    const requests = [
      {
        inputConfig,
        features,
        outputConfig,
      },
    ];

    const [operation] = await client.asyncBatchAnnotateFiles({requests});
    console.log('Waiting for the batch file annotation operation to complete...');

    const [filesResponse] = await operation.promise();

    console.log('Batch file annotation completed successfully.');
    if (filesResponse.responses) {
      for (const response of filesResponse.responses) {
        if (response.outputConfig && response.outputConfig.gcsDestination) {
          console.log(`Results saved to: ${response.outputConfig.gcsDestination.uri}`);
        }
      }
    }
  } catch (err) {
    if (err.code !== undefined && Object.values(status).includes(err.code)) {
      console.error(`Google API error (${err.code}):`, err.message);
    } else {
      throw err;
    }
  }
}

module.exports = { asyncBatchAnnotateFiles };

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.