批量为文件添加注释 (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 示例浏览器。