异步批量注释文件 (v1p4beta1)

异步检测存储在 Cloud Storage 中的 PDF 文件中的文本,并将注解结果保存到 Cloud Storage。

代码示例

Node.js

试用此示例之前,请按照《Vision 快速入门:使用客户端库》中的 Node.js 设置说明进行操作。 如需了解详情,请参阅 Vision Node.js API 参考文档。

如需向 Vision 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为本地开发环境设置身份验证。

'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 };

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅Google Cloud 示例浏览器。