Detectar texto em arquivos (PDF/TIFF)

Com a API Vision, é possível detectar e transcrever textos de arquivos PDF e TIFF armazenados no Cloud Storage.

Solicite a detecção de texto em documentos de PDF e TIFF usando a função files:asyncBatchAnnotate, que executa uma solicitação off-line (assíncrona) e fornece o status usando recursos operations.

A saída de uma solicitação em PDF/TIFF é gravada em um arquivo JSON criado no bucket do Cloud Storage especificado.

Limitações

A API do Vision aceita arquivos PDF/TIFF de até 2.000 páginas. Arquivos maiores retornarão um erro.

Autenticação

As chaves de API não são compatíveis com solicitações files:asyncBatchAnnotate. Consulte Como usar uma conta de serviço para receber instruções sobre a autenticação com uma conta de serviço.

A conta usada para autenticação precisa ter acesso ao bucket do Cloud Storage especificado para a saída (roles/editor, roles/storage.objectCreator ou superior).

É possível usar uma chave de API para consultar o status da operação. Para ver instruções, consulte Como usar uma chave de API.

Solicitações de detecção de texto em documento

No momento, a detecção de documentos em PDF/TIFF está disponível apenas para arquivos armazenados em buckets do Cloud Storage. Os arquivos JSON de resposta são salvos de maneira semelhante em um bucket do Cloud Storage.

Página com o PDF do censo de 2010 dos EUA
gs://cloud-samples-data/vision/pdf_tiff/census2010.pdf, Fonte:: United States Census Bureau (link em inglês).

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • CLOUD_STORAGE_BUCKET: um bucket/diretório do Cloud Storage para salvar arquivos de saída, expresso no seguinte formato:
    • gs://bucket/directory/
    O usuário solicitante precisa ter permissão de gravação no bucket.
  • CLOUD_STORAGE_FILE_URI: o caminho para um arquivo válido (PDF/TIFF) em um bucket do Cloud Storage. Você precisa ter, pelo menos, privilégios de leitura para o arquivo. Exemplo:
    • gs://cloud-samples-data/vision/pdf_tiff/census2010.pdf
  • FEATURE_TYPE: um tipo de recurso válido. Para solicitações files:asyncBatchAnnotate, use os seguintes tipos de recursos:
    • DOCUMENT_TEXT_DETECTION
    • TEXT_DETECTION
  • PROJECT_ID: o ID do Google Cloud projeto.

Considerações específicas de campo:

  • inputConfig: substitui o campo image usado em outras solicitações da API do Vision. Contém dois campos filhos:
    • gcsSource.uri: o URI do Google Cloud Storage do arquivo PDF ou TIFF (acessível ao usuário ou à conta de serviço que faz a solicitação).
    • mimeType: um dos tipos de arquivo aceitos (application/pdf ou image/tiff)
  • outputConfig: especifica os detalhes de saída. Contém dois campos filhos:
    • gcsDestination.uri - um URI válido do Google Cloud Storage. O bucket precisa ser gravável pelo usuário ou pela conta de serviço que faz a solicitação. O nome do arquivo será output-x-to-y, em que x e y representam os números de páginas em PDF/TIFF incluídos nesse arquivo de saída. Se o arquivo existir, o conteúdo dele será sobrescrito.
    • batchSize: especifica quantas páginas de saída precisam ser incluídas em cada arquivo JSON de saída.

Método HTTP e URL:

POST https://vision.googleapis.com/v1/files:asyncBatchAnnotate

Corpo JSON da solicitação:

{
  "requests":[
    {
      "inputConfig": {
        "gcsSource": {
          "uri": "CLOUD_STORAGE_FILE_URI"
        },
        "mimeType": "application/pdf"
      },
      "features": [
        {
          "type": "FEATURE_TYPE"
        }
      ],
      "outputConfig": {
        "gcsDestination": {
          "uri": "CLOUD_STORAGE_BUCKET"
        },
        "batchSize": 1
      }
    }
  ]
}

Para enviar a solicitação, escolha uma destas opções:

Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_ID" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://vision.googleapis.com/v1/files:asyncBatchAnnotate"

Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_ID" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/files:asyncBatchAnnotate" | Select-Object -Expand Content
Resposta:

Uma solicitação asyncBatchAnnotate bem-sucedida retorna uma resposta com um único campo de nome:

{
  "name": "projects/usable-auth-library/operations/1efec2285bd442df"
}

Esse nome representa uma operação de longa duração com um ID associado (por exemplo, 1efec2285bd442df), que pode ser consultado usando a API v1.operations.

Para recuperar a resposta de anotação do Vision, envie uma solicitação GET para o endpoint v1.operations, transmitindo o ID da operação no URL.

GET https://vision.googleapis.com/v1/operations/operation-id

Exemplo:

curl -X GET -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/operations/1efec2285bd442df

Se a operação estiver em andamento:

{
  "name": "operations/1efec2285bd442df",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.OperationMetadata",
    "state": "RUNNING",
    "createTime": "2019-05-15T21:10:08.401917049Z",
    "updateTime": "2019-05-15T21:10:33.700763554Z"
  }
}

Quando a operação for concluída, state será exibido como DONE e os resultados serão gravados no arquivo do Google Cloud Storage especificado:

{
  "name": "operations/1efec2285bd442df",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.OperationMetadata",
    "state": "DONE",
    "createTime": "2019-05-15T20:56:30.622473785Z",
    "updateTime": "2019-05-15T20:56:41.666379749Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.AsyncBatchAnnotateFilesResponse",
    "responses": [
      {
        "outputConfig": {
          "gcsDestination": {
            "uri": "gs://your-bucket-name/folder/"
          },
          "batchSize": 1
        }
      }
    ]
  }
}

O JSON no arquivo de saída é semelhante ao de uma imagem [solicitação de detecção de texto do documento](/vision/docs/ocr), com um campo context mostrando o local do PDF ou TIFF especificado e o número de páginas no arquivo:

output-1-to-1.json
        
    {
      "inputConfig": {
        "gcsSource": {
          "uri": "gs://cloud-samples-data/vision/pdf_tiff/census2010.pdf"
        },
        "mimeType": "application/pdf"
      },
      "responses": [
        {
          "fullTextAnnotation": {
            "pages": [
              {
                "property": {
                  "detectedLanguages": [
                    {
                      "languageCode": "en",
                      "confidence": 0.94
                    }
                  ]
                },
                "width": 612,
                "height": 792,
                "blocks": [
                  {
                    "boundingBox": {
                      "normalizedVertices": [
                        {
                          "x": 0.12908497,
                          "y": 0.10479798
                        },
                        ...
                        {
                          "x": 0.12908497,
                          "y": 0.1199495
                        }
                      ]
                    },
                    "paragraphs": [
                      {
                      ...
                        },
                        "words": [
                          {
                            ...
                            },
                            "symbols": [
                              {
                              ...
                                "text": "C",
                                "confidence": 0.99
                              },
                              {
                                "property": {
                                  "detectedLanguages": [
                                    {
                                      "languageCode": "en"
                                    }
                                  ]
                                },
                                "text": "O",
                                "confidence": 0.99
                              },
                 ...
                 }
                ]
              }
            ],
            "text": "CONTENTS\n.\n1-1\nII-1\nIII-1\nList of Statistical Tables...
            \nHow to Use This Census Report ..\nTable Finding Guide .\nUser
            Notes .......\nStatistical Tables.........\nAppendixes
            \nA Geographic Terms and Concepts .........\nB Definitions of
            Subject Characteristics.\nData Collection and Processing Procedures...
            \nQuestionnaire. ........\nE Maps .................\nF Operational
            Overview and accuracy of the Data.......\nG Residence Rule and
            Residence Situations for the \n2010 Census of the United States...
            \nH Acknowledgments .....\nE\n*Appendix may be found in the separate
            volume, CPH-1-A, Summary Population and\nHousing Characteristics,
            Selected Appendixes, on the Internet at
            <www.census.gov\n/prod/cen2010/cph-1-a.pdf>.\nContents\n"
          },
          "context": {
            "uri": "gs://cloud-samples-data/vision/pdf_tiff/census2010.pdf",
            "pageNumber": 1
          }
        }
      ]
    }
        

Antes de testar esta amostra, siga as instruções de configuração do Go no Guia de início rápido do Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API VisionGo.

Para autenticar no Vision, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


// detectAsyncDocumentURI performs Optical Character Recognition (OCR) on a
// PDF file stored in GCS.
func detectAsyncDocumentURI(w io.Writer, gcsSourceURI, gcsDestinationURI string) error {
	ctx := context.Background()

	client, err := vision.NewImageAnnotatorClient(ctx)
	if err != nil {
		return err
	}

	request := &visionpb.AsyncBatchAnnotateFilesRequest{
		Requests: []*visionpb.AsyncAnnotateFileRequest{
			{
				Features: []*visionpb.Feature{
					{
						Type: visionpb.Feature_DOCUMENT_TEXT_DETECTION,
					},
				},
				InputConfig: &visionpb.InputConfig{
					GcsSource: &visionpb.GcsSource{Uri: gcsSourceURI},
					// Supported MimeTypes are: "application/pdf" and "image/tiff".
					MimeType: "application/pdf",
				},
				OutputConfig: &visionpb.OutputConfig{
					GcsDestination: &visionpb.GcsDestination{Uri: gcsDestinationURI},
					// How many pages should be grouped into each json output file.
					BatchSize: 2,
				},
			},
		},
	}

	operation, err := client.AsyncBatchAnnotateFiles(ctx, request)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Waiting for the operation to finish.")

	resp, err := operation.Wait(ctx)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "%v", resp)

	return nil
}

Antes de testar esta amostra, siga as instruções de configuração do Java no Guia de início rápido da API Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para Java.

/**
 * Performs document text OCR with PDF/TIFF as source files on Google Cloud Storage.
 *
 * @param gcsSourcePath The path to the remote file on Google Cloud Storage to detect document
 *     text on.
 * @param gcsDestinationPath The path to the remote file on Google Cloud Storage to store the
 *     results on.
 * @throws Exception on errors while closing the client.
 */
public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinationPath)
    throws Exception {

  // 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 (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
    List<AsyncAnnotateFileRequest> requests = new ArrayList<>();

    // Set the GCS source path for the remote file.
    GcsSource gcsSource = GcsSource.newBuilder().setUri(gcsSourcePath).build();

    // Create the configuration with the specified MIME (Multipurpose Internet Mail Extensions)
    // types
    InputConfig inputConfig =
        InputConfig.newBuilder()
            .setMimeType(
                "application/pdf") // Supported MimeTypes: "application/pdf", "image/tiff"
            .setGcsSource(gcsSource)
            .build();

    // Set the GCS destination path for where to save the results.
    GcsDestination gcsDestination =
        GcsDestination.newBuilder().setUri(gcsDestinationPath).build();

    // Create the configuration for the System.output with the batch size.
    // The batch size sets how many pages should be grouped into each json System.output file.
    OutputConfig outputConfig =
        OutputConfig.newBuilder().setBatchSize(2).setGcsDestination(gcsDestination).build();

    // Select the Feature required by the vision API
    Feature feature = Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build();

    // Build the OCR request
    AsyncAnnotateFileRequest request =
        AsyncAnnotateFileRequest.newBuilder()
            .addFeatures(feature)
            .setInputConfig(inputConfig)
            .setOutputConfig(outputConfig)
            .build();

    requests.add(request);

    // Perform the OCR request
    OperationFuture<AsyncBatchAnnotateFilesResponse, OperationMetadata> response =
        client.asyncBatchAnnotateFilesAsync(requests);

    System.out.println("Waiting for the operation to finish.");

    // Wait for the request to finish. (The result is not used, since the API saves the result to
    // the specified location on GCS.)
    List<AsyncAnnotateFileResponse> result =
        response.get(180, TimeUnit.SECONDS).getResponsesList();

    // Once the request has completed and the System.output has been
    // written to GCS, we can list all the System.output files.
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // Get the destination location from the gcsDestinationPath
    Pattern pattern = Pattern.compile("gs://([^/]+)/(.+)");
    Matcher matcher = pattern.matcher(gcsDestinationPath);

    if (matcher.find()) {
      String bucketName = matcher.group(1);
      String prefix = matcher.group(2);

      // Get the list of objects with the given prefix from the GCS bucket
      Bucket bucket = storage.get(bucketName);
      com.google.api.gax.paging.Page<Blob> pageList = bucket.list(BlobListOption.prefix(prefix));

      Blob firstOutputFile = null;

      // List objects with the given prefix.
      System.out.println("Output files:");
      for (Blob blob : pageList.iterateAll()) {
        System.out.println(blob.getName());

        // Process the first System.output file from GCS.
        // Since we specified batch size = 2, the first response contains
        // the first two pages of the input file.
        if (firstOutputFile == null) {
          firstOutputFile = blob;
        }
      }

      // Get the contents of the file and convert the JSON contents to an AnnotateFileResponse
      // object. If the Blob is small read all its content in one request
      // (Note: the file is a .json file)
      // Storage guide: https://cloud.google.com/storage/docs/downloading-objects
      String jsonContents = new String(firstOutputFile.getContent());
      Builder builder = AnnotateFileResponse.newBuilder();
      JsonFormat.parser().merge(jsonContents, builder);

      // Build the AnnotateFileResponse object
      AnnotateFileResponse annotateFileResponse = builder.build();

      // Parse through the object to get the actual response for the first page of the input file.
      AnnotateImageResponse annotateImageResponse = annotateFileResponse.getResponses(0);

      // Here we print the full text from the first page.
      // The response contains more information:
      // annotation/pages/blocks/paragraphs/words/symbols
      // including confidence score and bounding boxes
      System.out.format("%nText: %s%n", annotateImageResponse.getFullTextAnnotation().getText());
    } else {
      System.out.println("No MATCH");
    }
  }
}

Antes de testar esta amostra, siga as instruções de configuração do Node.js no Guia de início rápido do Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API VisionNode.js.

Para autenticar no Vision, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


// Imports the Google Cloud client libraries
const vision = require('@google-cloud/vision').v1;

// Creates a client
const client = new vision.ImageAnnotatorClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// Bucket where the file resides
// const bucketName = 'my-bucket';
// Path to PDF file within bucket
// const fileName = 'path/to/document.pdf';
// The folder to store the results
// const outputPrefix = 'results'

const gcsSourceUri = `gs://${bucketName}/${fileName}`;
const gcsDestinationUri = `gs://${bucketName}/${outputPrefix}/`;

const inputConfig = {
  // Supported mime_types are: 'application/pdf' and 'image/tiff'
  mimeType: 'application/pdf',
  gcsSource: {
    uri: gcsSourceUri,
  },
};
const outputConfig = {
  gcsDestination: {
    uri: gcsDestinationUri,
  },
};
const features = [{type: 'DOCUMENT_TEXT_DETECTION'}];
const request = {
  requests: [
    {
      inputConfig: inputConfig,
      features: features,
      outputConfig: outputConfig,
    },
  ],
};

const [operation] = await client.asyncBatchAnnotateFiles(request);
const [filesResponse] = await operation.promise();
const destinationUri =
  filesResponse.responses[0].outputConfig.gcsDestination.uri;
console.log('Json saved to: ' + destinationUri);

Antes de testar esta amostra, siga as instruções de configuração do Python no Guia de início rápido do Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API VisionPython.

Para autenticar no Vision, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

def async_detect_document(gcs_source_uri, gcs_destination_uri):
    """OCR with PDF/TIFF as source files on GCS"""
    import json
    import re
    from google.cloud import vision
    from google.cloud import storage

    # Supported mime_types are: 'application/pdf' and 'image/tiff'
    mime_type = "application/pdf"

    # How many pages should be grouped into each json output file.
    batch_size = 2

    client = vision.ImageAnnotatorClient()

    feature = vision.Feature(type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION)

    gcs_source = vision.GcsSource(uri=gcs_source_uri)
    input_config = vision.InputConfig(gcs_source=gcs_source, mime_type=mime_type)

    gcs_destination = vision.GcsDestination(uri=gcs_destination_uri)
    output_config = vision.OutputConfig(
        gcs_destination=gcs_destination, batch_size=batch_size
    )

    async_request = vision.AsyncAnnotateFileRequest(
        features=[feature], input_config=input_config, output_config=output_config
    )

    operation = client.async_batch_annotate_files(requests=[async_request])

    print("Waiting for the operation to finish.")
    operation.result(timeout=420)

    # Once the request has completed and the output has been
    # written to GCS, we can list all the output files.
    storage_client = storage.Client()

    match = re.match(r"gs://([^/]+)/(.+)", gcs_destination_uri)
    bucket_name = match.group(1)
    prefix = match.group(2)

    bucket = storage_client.get_bucket(bucket_name)

    # List objects with the given prefix, filtering out folders.
    blob_list = [
        blob
        for blob in list(bucket.list_blobs(prefix=prefix))
        if not blob.name.endswith("/")
    ]
    print("Output files:")
    for blob in blob_list:
        print(blob.name)

    # Process the first output file from GCS.
    # Since we specified batch_size=2, the first response contains
    # the first two pages of the input file.
    output = blob_list[0]

    json_string = output.download_as_bytes().decode("utf-8")
    response = json.loads(json_string)

    # The actual response for the first page of the input file.
    first_page_response = response["responses"][0]
    annotation = first_page_response["fullTextAnnotation"]

    # Here we print the full text from the first page.
    # The response contains more information:
    # annotation/pages/blocks/paragraphs/words/symbols
    # including confidence scores and bounding boxes
    print("Full text:\n")
    print(annotation["text"])

O comando gcloud que você usa depende do tipo de arquivo.

  • Para realizar a detecção de texto em PDF, use o comando gcloud ml vision detect-text-pdf como mostrado no exemplo a seguir:

    gcloud ml vision detect-text-pdf gs://my_bucket/input_file  gs://my_bucket/out_put_prefix
    
  • Para executar a detecção de texto em TIFF, use o comando gcloud ml vision detect-text-tiff como mostrado no exemplo a seguir:

    gcloud ml vision detect-text-tiff gs://my_bucket/input_file  gs://my_bucket/out_put_prefix
    

C#: Siga as Instruções de configuração do C# na página das bibliotecas de cliente e acesse a Documentação de referência do Vision para .NET.

PHP: Siga as Instruções de configuração do PHP na página das bibliotecas de cliente e acesse a Documentação de referência do Vision para PHP.

Ruby Siga estas instruções:Instruções de configuração do Ruby na página das bibliotecas de cliente e, em seguida, visite oDocumentação de referência do Vision para Ruby.

Suporte multirregional

Já é possível especificar o armazenamento de dados e o processamento de OCR em nível de continente. Estas regiões são compatíveis:

  • us: somente nos EUA
  • eu: União Europeia

Locais

O Cloud Vision oferece controle sobre onde os recursos do projeto são armazenados e processados. Especificamente, é possível configurar o Cloud Vision para armazenar e processar os dados somente na União Europeia.

Por padrão, o Cloud Vision armazena e processa recursos em um local global, o que significa que o Cloud Vision não garante que os recursos permanecerão em um determinado local ou região. Se você escolher a União Europeia como local, o Google armazenará os dados e os processará somente na União Europeia. Você e seus usuários podem acessar os dados de qualquer local.

Como definir o local usando a API

A API Vision aceita um endpoint de API global (vision.googleapis.com), bem como dois endpoints baseados em região: um endpoint da União Europeia (eu-vision.googleapis.com) e um endpoint dos Estados Unidos (us-vision.googleapis.com). Use esses endpoints para processamento específico da região. Por exemplo, para armazenar e processar os dados somente na União Europeia, use o URI eu-vision.googleapis.com no lugar de vision.googleapis.com para as chamadas da API REST:

  • https://eu-vision.googleapis.com/v1/projects/PROJECT_ID/locations/eu/images:annotate
  • https://eu-vision.googleapis.com/v1/projects/PROJECT_ID/locations/eu/images:asyncBatchAnnotate
  • https://eu-vision.googleapis.com/v1/projects/PROJECT_ID/locations/eu/files:annotate
  • https://eu-vision.googleapis.com/v1/projects/PROJECT_ID/locations/eu/files:asyncBatchAnnotate

Para armazenar e processar seus dados somente nos Estados Unidos, use o endpoint dos EUA (us-vision.googleapis.com) com os métodos anteriores.

Como definir o local usando as bibliotecas de cliente

Por padrão, as bibliotecas cliente da API Vision acessam o endpoint global da API (vision.googleapis.com). Para armazenar e processar os dados somente na União Europeia, você precisa definir explicitamente o endpoint (eu-vision.googleapis.com). Os exemplos de código abaixo mostram como definir essa configuração.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • REGION_ID: um dos identificadores de local regionais válidos:
    • us: somente nos EUA
    • eu: União Europeia
  • CLOUD_STORAGE_IMAGE_URI: o caminho para um arquivo de imagem válido em um bucket do Cloud Storage. Você precisa ter, pelo menos, privilégios de leitura para o arquivo. Exemplo:
    • gs://cloud-samples-data/vision/pdf_tiff/census2010.pdf
  • CLOUD_STORAGE_BUCKET: um bucket/diretório do Cloud Storage para salvar arquivos de saída, expresso no seguinte formato:
    • gs://bucket/directory/
    O usuário solicitante precisa ter permissão de gravação no bucket.
  • FEATURE_TYPE: um tipo de recurso válido. Para solicitações files:asyncBatchAnnotate, use os seguintes tipos de recursos:
    • DOCUMENT_TEXT_DETECTION
    • TEXT_DETECTION
  • PROJECT_ID: o ID do Google Cloud projeto.

Considerações específicas de campo:

  • inputConfig: substitui o campo image usado em outras solicitações da API do Vision. Contém dois campos filhos:
    • gcsSource.uri: o URI do Google Cloud Storage do arquivo PDF ou TIFF (acessível ao usuário ou à conta de serviço que faz a solicitação).
    • mimeType: um dos tipos de arquivo aceitos (application/pdf ou image/tiff)
  • outputConfig: especifica os detalhes de saída. Contém dois campos filhos:
    • gcsDestination.uri - um URI válido do Google Cloud Storage. O bucket precisa ser gravável pelo usuário ou pela conta de serviço que faz a solicitação. O nome do arquivo será output-x-to-y, em que x e y representam os números de páginas em PDF/TIFF incluídos nesse arquivo de saída. Se o arquivo existir, o conteúdo dele será sobrescrito.
    • batchSize: especifica quantas páginas de saída precisam ser incluídas em cada arquivo JSON de saída.

Método HTTP e URL:

POST https://REGION_ID-vision.googleapis.com/v1/projects/PROJECT_ID/locations/REGION_ID/files:asyncBatchAnnotate

Corpo JSON da solicitação:

{
  "requests":[
    {
      "inputConfig": {
        "gcsSource": {
          "uri": "CLOUD_STORAGE_IMAGE_URI"
        },
        "mimeType": "application/pdf"
      },
      "features": [
        {
          "type": "FEATURE_TYPE"
        }
      ],
      "outputConfig": {
        "gcsDestination": {
          "uri": "CLOUD_STORAGE_BUCKET"
        },
        "batchSize": 1
      }
    }
  ]
}

Para enviar a solicitação, escolha uma destas opções:

Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_ID" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://REGION_ID-vision.googleapis.com/v1/projects/PROJECT_ID/locations/REGION_ID/files:asyncBatchAnnotate"

Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_ID" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://REGION_ID-vision.googleapis.com/v1/projects/PROJECT_ID/locations/REGION_ID/files:asyncBatchAnnotate" | Select-Object -Expand Content
Resposta:

Uma solicitação asyncBatchAnnotate bem-sucedida retorna uma resposta com um único campo de nome:

{
  "name": "projects/usable-auth-library/operations/1efec2285bd442df"
}

Esse nome representa uma operação de longa duração com um ID associado (por exemplo, 1efec2285bd442df), que pode ser consultado usando a API v1.operations.

Para recuperar a resposta de anotação do Vision, envie uma solicitação GET para o endpoint v1.operations, transmitindo o ID da operação no URL.

GET https://vision.googleapis.com/v1/operations/operation-id

Exemplo:

curl -X GET -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/operations/1efec2285bd442df

Se a operação estiver em andamento:

{
  "name": "operations/1efec2285bd442df",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.OperationMetadata",
    "state": "RUNNING",
    "createTime": "2019-05-15T21:10:08.401917049Z",
    "updateTime": "2019-05-15T21:10:33.700763554Z"
  }
}

Quando a operação for concluída, state será exibido como DONE e os resultados serão gravados no arquivo do Google Cloud Storage especificado:

{
  "name": "operations/1efec2285bd442df",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.OperationMetadata",
    "state": "DONE",
    "createTime": "2019-05-15T20:56:30.622473785Z",
    "updateTime": "2019-05-15T20:56:41.666379749Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.AsyncBatchAnnotateFilesResponse",
    "responses": [
      {
        "outputConfig": {
          "gcsDestination": {
            "uri": "gs://your-bucket-name/folder/"
          },
          "batchSize": 1
        }
      }
    ]
  }
}

O JSON no arquivo de saída é semelhante ao da resposta de detecção de texto do documento da imagem se você usou o recurso DOCUMENT_TEXT_DETECTION ou a resposta de detecção de texto se você usou o recurso TEXT_DETECTION. A saída terá um campo context extra que mostra o local do PDF ou TIFF especificado e o número de páginas no arquivo:

output-1-to-1.json
        
    {
      "inputConfig": {
        "gcsSource": {
          "uri": "gs://cloud-samples-data/vision/pdf_tiff/census2010.pdf"
        },
        "mimeType": "application/pdf"
      },
      "responses": [
        {
          "fullTextAnnotation": {
            "pages": [
              {
                "property": {
                  "detectedLanguages": [
                    {
                      "languageCode": "en",
                      "confidence": 0.94
                    }
                  ]
                },
                "width": 612,
                "height": 792,
                "blocks": [
                  {
                    "boundingBox": {
                      "normalizedVertices": [
                        {
                          "x": 0.12908497,
                          "y": 0.10479798
                        },
                        ...
                        {
                          "x": 0.12908497,
                          "y": 0.1199495
                        }
                      ]
                    },
                    "paragraphs": [
                      {
                      ...
                        },
                        "words": [
                          {
                            ...
                            },
                            "symbols": [
                              {
                              ...
                                "text": "C",
                                "confidence": 0.99
                              },
                              {
                                "property": {
                                  "detectedLanguages": [
                                    {
                                      "languageCode": "en"
                                    }
                                  ]
                                },
                                "text": "O",
                                "confidence": 0.99
                              },
                 ...
                 }
                ]
              }
            ],
            "text": "CONTENTS\n.\n1-1\nII-1\nIII-1\nList of Statistical Tables...
            \nHow to Use This Census Report ..\nTable Finding Guide .\nUser
            Notes .......\nStatistical Tables.........\nAppendixes
            \nA Geographic Terms and Concepts .........\nB Definitions of
            Subject Characteristics.\nData Collection and Processing Procedures...
            \nQuestionnaire. ........\nE Maps .................\nF Operational
            Overview and accuracy of the Data.......\nG Residence Rule and
            Residence Situations for the \n2010 Census of the United States...
            \nH Acknowledgments .....\nE\n*Appendix may be found in the separate
            volume, CPH-1-A, Summary Population and\nHousing Characteristics,
            Selected Appendixes, on the Internet at
            <www.census.gov\n/prod/cen2010/cph-1-a.pdf>.\nContents\n"
          },
          "context": {
            "uri": "gs://cloud-samples-data/vision/pdf_tiff/census2010.pdf",
            "pageNumber": 1
          }
        }
      ]
    }
        

Antes de testar esta amostra, siga as instruções de configuração do Go no Guia de início rápido do Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API VisionGo.

Para autenticar no Vision, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import (
	"context"
	"fmt"

	vision "cloud.google.com/go/vision/apiv1"
	"google.golang.org/api/option"
)

// setEndpoint changes your endpoint.
func setEndpoint(endpoint string) error {
	// endpoint := "eu-vision.googleapis.com:443"

	ctx := context.Background()
	client, err := vision.NewImageAnnotatorClient(ctx, option.WithEndpoint(endpoint))
	if err != nil {
		return fmt.Errorf("NewImageAnnotatorClient: %w", err)
	}
	defer client.Close()

	return nil
}

Antes de testar esta amostra, siga as instruções de configuração do Java no Guia de início rápido da API Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para Java.

ImageAnnotatorSettings settings =
    ImageAnnotatorSettings.newBuilder().setEndpoint("eu-vision.googleapis.com:443").build();

// 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.
ImageAnnotatorClient client = ImageAnnotatorClient.create(settings);

Antes de testar esta amostra, siga as instruções de configuração do Node.js no Guia de início rápido do Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API VisionNode.js.

Para autenticar no Vision, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');

async function setEndpoint() {
  // Specifies the location of the api endpoint
  const clientOptions = {apiEndpoint: 'eu-vision.googleapis.com'};

  // Creates a client
  const client = new vision.ImageAnnotatorClient(clientOptions);

  // Performs text detection on the image file
  const [result] = await client.textDetection('./resources/wakeupcat.jpg');
  const labels = result.textAnnotations;
  console.log('Text:');
  labels.forEach(label => console.log(label.description));
}
setEndpoint();

Antes de testar esta amostra, siga as instruções de configuração do Python no Guia de início rápido do Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API VisionPython.

Para autenticar no Vision, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

from google.cloud import vision

client_options = {"api_endpoint": "eu-vision.googleapis.com"}

client = vision.ImageAnnotatorClient(client_options=client_options)

Faça um teste

Se você começou a usar o Google Cloud agora, crie uma conta para avaliar o desempenho da API Cloud Vision em situações reais. Clientes novos também recebem US$ 300 em créditos para executar, testar e implantar cargas de trabalho.

Faça uma avaliação gratuita da API Cloud Vision