ファイルに非同期で一括アノテーションを付ける(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 サンプル ブラウザをご覧ください。