以非同步方式批次註解檔案 (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 範例瀏覽工具。