批次註解檔案 (v1p4beta1)

使用批次檔案註解,同步偵測儲存在 Cloud Storage 的 PDF 檔案中的文件文字。

程式碼範例

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 Vision 快速入門導覽課程」中的 Java 設定說明操作。詳情請參閱 Vision Java API 參考文件。

如要向 Vision 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

import com.google.cloud.vision.v1p4beta1.AnnotateFileRequest;
import com.google.cloud.vision.v1p4beta1.AnnotateFileResponse;
import com.google.cloud.vision.v1p4beta1.AnnotateImageResponse;
import com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesResponse;
import com.google.cloud.vision.v1p4beta1.Feature;
import com.google.cloud.vision.v1p4beta1.GcsSource;
import com.google.cloud.vision.v1p4beta1.ImageAnnotatorClient;
import com.google.cloud.vision.v1p4beta1.InputConfig;
import java.util.Collections;
import java.util.List;

public class BatchAnnotateFiles {

  public static void main(String[] args) throws Exception {
    batchAnnotateFiles();
  }

  public static void batchAnnotateFiles() throws Exception {
    // Initialize the client with Application Default Credentials
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
      GcsSource gcsSource =
          GcsSource.newBuilder()
              .setUri("gs://cloud-samples-data/vision/document_understanding/kafka.pdf")
              .build();

      InputConfig inputConfig =
          InputConfig.newBuilder()
              .setMimeType("application/pdf")
              .setGcsSource(gcsSource)
              .build();

      Feature feature =
          Feature.newBuilder()
              .setType(Feature.Type.DOCUMENT_TEXT_DETECTION)
              .build();

      AnnotateFileRequest fileRequest =
          AnnotateFileRequest.newBuilder()
              .setInputConfig(inputConfig)
              .addFeatures(feature)
              .addPages(1)
              .build();

      // The API accepts a single AnnotateFileRequest in the batch
      List<AnnotateFileRequest> requests = Collections.singletonList(fileRequest);

      BatchAnnotateFilesResponse response = client.batchAnnotateFiles(requests);
      for (AnnotateFileResponse fileResponse : response.getResponsesList()) {
        System.out.printf("Total pages: %d%n", fileResponse.getTotalPages());
        for (AnnotateImageResponse pageResponse : fileResponse.getResponsesList()) {
          System.out.printf("Page full text: %s%n", pageResponse.getFullTextAnnotation().getText());
        }
      }
    }
  }
}

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽工具。