Annotate a batch of local files while online.

## Explore further


For detailed documentation that includes this code sample, see the following:

- [Annotate a batch of local files](https://docs.cloud.google.com/vision/docs/samples/vision-batch-annotate-files)
- [Small batch file annotation online](https://docs.cloud.google.com/vision/docs/file-small-batch)

## Code sample

### Java


To learn how to install and use the client library for Vision API Product Search, see
[Vision API Product Search client libraries](https://docs.cloud.google.com/vision/product-search/docs/libraries).


For more information, see the
[Vision API Product Search Java API
reference documentation](https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/overview).


To authenticate to Vision API Product Search, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AnnotateFileRequest.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AnnotateImageResponse.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.BatchAnnotateFilesRequest.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.BatchAnnotateFilesResponse.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Block.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Feature.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.ImageAnnotatorClient.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.InputConfig.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Page.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Paragraph.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Symbol.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Word.html;
    import com.google.protobuf.https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;

    public class BatchAnnotateFiles {

      public static void batchAnnotateFiles() throws IOException {
        String filePath = "path/to/your/file.pdf";
        batchAnnotateFiles(filePath);
      }

      public static void batchAnnotateFiles(String filePath) throws IOException {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests. After completing all of your requests, call
        // the "close" method on the client to safely clean up any remaining background resources.
        try (https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.ImageAnnotatorClient.html imageAnnotatorClient = https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.ImageAnnotatorClient.html.create()) {
          // You can send multiple files to be annotated, this sample demonstrates how to do this with
          // one file. If you want to use multiple files, you have to create a `AnnotateImageRequest`
          // object for each file that you want annotated.
          // First read the files contents
          Path path = Paths.get(filePath);
          byte[] data = Files.readAllBytes(path);
          https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html content = https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html.https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html#com_google_protobuf_ByteString_copyFrom_byte___(data);

          // Specify the input config with the file's contents and its type.
          // Supported mime_type: application/pdf, image/tiff, image/gif
          // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#inputconfig
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.InputConfig.html inputConfig =
              https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.InputConfig.html.newBuilder().https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.InputConfig.Builder.html#com_google_cloud_vision_v1_InputConfig_Builder_setMimeType_java_lang_String_("application/pdf").setContent(content).build();

          // Set the type of annotation you want to perform on the file
          // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.Feature.Type
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Feature.html feature = https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Feature.html.newBuilder().setType(https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Feature.html.Type.DOCUMENT_TEXT_DETECTION).build();

          // Build the request object for that one file. Note: for additional file you have to create
          // additional `AnnotateFileRequest` objects and store them in a list to be used below.
          // Since we are sending a file of type `application/pdf`, we can use the `pages` field to
          // specify which pages to process. The service can process up to 5 pages per document file.
          // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.AnnotateFileRequest
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AnnotateFileRequest.html fileRequest =
              https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AnnotateFileRequest.html.newBuilder()
                  .setInputConfig(inputConfig)
                  .addFeatures(feature)
                  .addPages(1) // Process the first page
                  .addPages(2) // Process the second page
                  .addPages(-1) // Process the last page
                  .build();

          // Add each `AnnotateFileRequest` object to the batch request.
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.BatchAnnotateFilesRequest.html request =
              https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.BatchAnnotateFilesRequest.html.newBuilder().addRequests(fileRequest).build();

          // Make the synchronous batch request.
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.BatchAnnotateFilesResponse.html response = imageAnnotatorClient.batchAnnotateFiles(request);

          // Process the results, just get the first result, since only one file was sent in this
          // sample.
          for (https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AnnotateImageResponse.html imageResponse :
              response.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.BatchAnnotateFilesResponse.html#com_google_cloud_vision_v1_BatchAnnotateFilesResponse_getResponsesList__().get(0).getResponsesList()) {
            System.out.format("Full text: %s%n", imageResponse.getFullTextAnnotation().getText());
            for (https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Page.html page : imageResponse.getFullTextAnnotation().getPagesList()) {
              for (https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Block.html block : page.getBlocksList()) {
                System.out.format("%nBlock confidence: %s%n", block.getConfidence());
                for (https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Paragraph.html par : block.getParagraphsList()) {
                  System.out.format("\tParagraph confidence: %s%n", par.getConfidence());
                  for (https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Word.html word : par.getWordsList()) {
                    System.out.format("\t\tWord confidence: %s%n", word.getConfidence());
                    for (https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Symbol.html symbol : word.getSymbolsList()) {
                      System.out.format(
                          "\t\t\tSymbol: %s, (confidence: %s)%n",
                          symbol.getText(), symbol.getConfidence());
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

### Node.js


To learn how to install and use the client library for Vision API Product Search, see
[Vision API Product Search client libraries](https://docs.cloud.google.com/vision/product-search/docs/libraries).


For more information, see the
[Vision API Product Search Node.js API
reference documentation](https://googleapis.dev/nodejs/vision/latest).


To authenticate to Vision API Product Search, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const fileName = 'path/to/your/file.pdf';

    // Imports the Google Cloud client libraries
    const {ImageAnnotatorClient} = require('https://docs.cloud.google.com/nodejs/docs/reference/vision/latest/overview.html').v1;
    const fs = require('fs').promises;

    // Instantiates a client
    const client = new https://docs.cloud.google.com/nodejs/docs/reference/vision/latest/overview.html();

    // You can send multiple files to be annotated, this sample demonstrates how to do this with
    // one file. If you want to use multiple files, you have to create a request object for each file that you want annotated.
    async function batchAnnotateFiles() {
      // First Specify the input config with the file's path and its type.
      // Supported mime_type: application/pdf, image/tiff, image/gif
      // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#inputconfig
      const inputConfig = {
        mimeType: 'application/pdf',
        content: await fs.readFile(fileName),
      };

      // Set the type of annotation you want to perform on the file
      // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.Feature.Type
      const features = [{type: 'DOCUMENT_TEXT_DETECTION'}];

      // Build the request object for that one file. Note: for additional files you have to create
      // additional file request objects and store them in a list to be used below.
      // Since we are sending a file of type `application/pdf`, we can use the `pages` field to
      // specify which pages to process. The service can process up to 5 pages per document file.
      // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.AnnotateFileRequest
      const fileRequest = {
        inputConfig: inputConfig,
        features: features,
        // Annotate the first two pages and the last one (max 5 pages)
        // First page starts at 1, and not 0. Last page is -1.
        pages: [1, 2, -1],
      };

      // Add each `AnnotateFileRequest` object to the batch request.
      const request = {
        requests: [fileRequest],
      };

      // Make the synchronous batch request.
      const [result] = await client.batchAnnotateFiles(request);

      // Process the results, just get the first result, since only one file was sent in this
      // sample.
      const responses = https://docs.cloud.google.com/nodejs/docs/reference/vision/latest/vision/protos.google.longrunning.operation.html.responses[0].responses;

      for (const response of responses) {
        console.log(`Full text: ${response.fullTextAnnotation.text}`);
        for (const page of response.fullTextAnnotation.pages) {
          for (const block of page.blocks) {
            console.log(`Block confidence: ${block.confidence}`);
            for (const paragraph of block.paragraphs) {
              console.log(` Paragraph confidence: ${paragraph.confidence}`);
              for (const word of paragraph.words) {
                const symbol_texts = word.symbols.map(symbol => symbol.text);
                const word_text = symbol_texts.join('');
                console.log(
                  `  Word text: ${word_text} (confidence: ${word.confidence})`
                );
                for (const symbol of word.symbols) {
                  console.log(
                    `   Symbol: ${symbol.text} (confidence: ${symbol.confidence})`
                  );
                }
              }
            }
          }
        }
      }
    }

    batchAnnotateFiles();

### Python


To learn how to install and use the client library for Vision API Product Search, see
[Vision API Product Search client libraries](https://docs.cloud.google.com/vision/product-search/docs/libraries).


For more information, see the
[Vision API Product Search Python API
reference documentation](https://docs.cloud.google.com/python/docs/reference/vision/latest).


To authenticate to Vision API Product Search, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).



    from google.cloud import https://docs.cloud.google.com/python/docs/reference/vision/latest


    def sample_batch_annotate_files(file_path="path/to/your/document.pdf"):
        """Perform batch file annotation."""
        client = https://docs.cloud.google.com/python/docs/reference/vision/latest.https://docs.cloud.google.com/python/docs/reference/vision/latest/google.cloud.vision_v1.services.image_annotator.ImageAnnotatorClient.html()

        # Supported mime_type: application/pdf, image/tiff, image/gif
        mime_type = "application/pdf"
        with open(file_path, "rb") as f:
            content = f.read()
        input_config = {"mime_type": mime_type, "content": content}
        features = [{"type_": https://docs.cloud.google.com/python/docs/reference/vision/latest.https://docs.cloud.google.com/python/docs/reference/vision/latest/google.cloud.vision_v1.types.Feature.html.Type.DOCUMENT_TEXT_DETECTION}]

        # The service can process up to 5 pages per document file. Here we specify
        # the first, second, and last page of the document to be processed.
        pages = [1, 2, -1]
        requests = [{"input_config": input_config, "features": features, "pages": pages}]

        response = client.https://docs.cloud.google.com/python/docs/reference/vision/latest/google.cloud.vision_v1.services.image_annotator.ImageAnnotatorClient.html#google_cloud_vision_v1_services_image_annotator_ImageAnnotatorClient_batch_annotate_files(requests=requests)
        for image_response in response.responses[0].responses:
            print(f"Full text: {image_response.full_text_annotation.text}")
            for page in image_response.full_text_annotation.pages:
                for block in page.blocks:
                    print(f"\nBlock confidence: {block.confidence}")
                    for par in block.paragraphs:
                        print(f"\tParagraph confidence: {par.confidence}")
                        for word in par.words:
                            print(f"\t\tWord confidence: {word.confidence}")
                            for symbol in word.symbols:
                                print(
                                    "\t\t\tSymbol: {}, (confidence: {})".format(
                                        symbol.text, symbol.confidence
                                    )
                                )

## What's next


To search and filter code samples for other Google Cloud products, see the
[Google Cloud sample browser](https://docs.cloud.google.com/docs/samples?product=cloudvision).