Detecção de texto em documentos PDF/TIFF

A API do Vision pode detectar e transcrever texto de arquivos PDF e TIFF armazenados no Google Cloud Storage.

A detecção de texto do documento em PDF e TIFF precisa ser solicitada usando a função asyncBatchAnnotate, que executa uma solicitação assíncrona e fornece seu status usando os recursos de operations.

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

O preço para detecção de texto de documento PDF/TIFF está na taxa DOCUMENT_TEXT_DETECTION. Consulte a página de Preços para ver detalhes.

Limitações

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

Autenticação

Chaves de API não são compatíveis com solicitações 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 intervalo do Cloud Storage especificado para a saída (roles/editor ou roles/storage.objectCreator ou acima).

É 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.

Código de amostra

Protocolo

Para executar a detecção de texto em documentos PDF/TIFF, faça uma solicitação POST e informe o corpo apropriado:

POST https://vision.googleapis.com/v1/files:asyncBatchAnnotate
Authorization: Bearer ACCESS_TOKEN

{
  "requests":[
    {
      "inputConfig": {
        "gcsSource": {
          "uri": "gs://bucket-name-123/vision-api.pdf"
        },
        "mimeType": "application/pdf"
      },
      "features": [
        {
          "type": "DOCUMENT_TEXT_DETECTION"
        }
      ],
      "outputConfig": {
        "gcsDestination": {
          "uri": "gs://your-bucket-name/folder/"
        },
        "batchSize": 2
      }
    }
  ]
}

em que:

  • inputConfig substitui o campo image usado em outras solicitações da API Vision. Ele contém dois campos filhos: gcsSource.uri é o URI do Google Cloud Storage do arquivo PDF ou TIFF, acessível pela conta de usuário ou serviço que faz a solicitação. mimeType é application/pdf ou application/tiff;

  • outputConfig especifica a pasta/intervalo do Cloud Storage para gravar a saída. Ele precisa conter um URI do Google Cloud Storage como valor do campo gcsDestination.uri. O intervalo 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ágina PDF/TIFF incluídos nesse arquivo de saída. Se o arquivo existir, o conteúdo dele será sobrescrito. O campo batchSize especifica quantas páginas de saída precisam ser incluídas em cada arquivo JSON de saída.

Resposta:

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

{
  "name": "operations/1b0390d223f4a5af"
}

Esse nome representa uma operação de longa duração que pode ser consultada com a API v1.operations.

Para recuperar sua resposta de anotação do Vision, envie uma solicitação GET para o ponto de extremidade v1.operations, passando o valor do name no URL.

GET https://vision.googleapis.com/v1/operations/1b0390d223f4a5af?key=YOUR_API_KEY

Se a operação estiver em andamento:

{
  "name": "operations/1b0390d223f4ab8a",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.OperationMetadata",
    "state": "RUNNING",
    "updateTime": "2017-12-07T00:51:22.225232809Z"
  }
}

Depois que a operação for concluída, o state será DONE e seus resultados serão gravados no arquivo do Google Cloud Storage especificado:

{
  "name": "operations/1b0390d223f4ab8a",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.OperationMetadata",
    "state": "DONE",
    "updateTime": "2017-12-07T01:36:08.757594684Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.AsyncBatchAnnotateFilesResponse",
    "outputConfig": {
      "gcsDestination": {
        "uri": "gs://your-bucket-name/folder/"
      }
    }
  }
}

No arquivo de saída, o JSON é semelhante ao arquivo de saída da solicitação de detecção de texto de documento de uma imagem, com a adição de um campo de context mostrando o local do PDF ou TIFF que foi especificado e o número de páginas no arquivo:

...
"context": {
  "uri": "gs://bucket-name-123/vision-api.pdf",
  "pageNumber": 1
}
...

C#

Antes de testar esta amostra, siga as instruções de configuração do C# 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 Vision para C#.

private static object DetectDocument(string gcsSourceUri,
    string gcsDestinationBucketName, string gcsDestinationPrefixName)
{
    var client = ImageAnnotatorClient.Create();

    var asyncRequest = new AsyncAnnotateFileRequest
    {
        InputConfig = new InputConfig
        {
            GcsSource = new GcsSource
            {
                Uri = gcsSourceUri
            },
            // Supported mime_types are: 'application/pdf' and 'image/tiff'
            MimeType = "application/pdf"
        },
        OutputConfig = new OutputConfig
        {
            // How many pages should be grouped into each json output file.
            BatchSize = 2,
            GcsDestination = new GcsDestination
            {
                Uri = $"gs://{gcsDestinationBucketName}/{gcsDestinationPrefixName}"
            }
        }
    };

    asyncRequest.Features.Add(new Feature
    {
        Type = Feature.Types.Type.DocumentTextDetection
    });

    List<AsyncAnnotateFileRequest> requests =
        new List<AsyncAnnotateFileRequest>();
    requests.Add(asyncRequest);

    var operation = client.AsyncBatchAnnotateFiles(requests);

    Console.WriteLine("Waiting for the operation to finish");

    operation.PollUntilCompleted();

    // Once the rquest has completed and the output has been
    // written to GCS, we can list all the output files.
    var storageClient = StorageClient.Create();

    // List objects with the given prefix.
    var blobList = storageClient.ListObjects(gcsDestinationBucketName,
        gcsDestinationPrefixName);
    Console.WriteLine("Output files:");
    foreach (var blob in blobList)
    {
        Console.WriteLine(blob.Name);
    }

    // Process the first output file from GCS.
    // Select the first JSON file from the objects in the list.
    var output = blobList.Where(x => x.Name.Contains(".json")).First();

    var jsonString = "";
    using (var stream = new MemoryStream())
    {
        storageClient.DownloadObject(output, stream);
        jsonString = System.Text.Encoding.UTF8.GetString(stream.ToArray());
    }

    var response = JsonParser.Default
                .Parse<AnnotateFileResponse>(jsonString);

    // The actual response for the first page of the input file.
    var firstPageResponses = response.Responses[0];
    var annotation = firstPageResponses.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
    Console.WriteLine($"Full text: \n {annotation.Text}");

    return 0;
}

Go

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


// detectAsyncDocument 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
}

Java

Antes de testar esta amostra, siga as instruções de configuração do Java no Guia de início rápido da 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 {
  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 output with the batch size.
    // The batch size sets how many pages should be grouped into each json 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 output has been
    // written to GCS, we can list all the 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 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");
    }
  }
}

Node.js

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


// 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);

Python

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

def async_detect_document(gcs_source_uri, gcs_destination_uri):
    """OCR with PDF/TIFF as source files on GCS"""
    from google.cloud import vision
    from google.cloud import storage
    from google.protobuf import json_format
    # 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.types.Feature(
        type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION)

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

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

    async_request = vision.types.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=180)

    # 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=bucket_name)

    # List objects with the given prefix.
    blob_list = list(bucket.list_blobs(prefix=prefix))
    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_string()
    response = json_format.Parse(
        json_string, vision.types.AnnotateFileResponse())

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

    # 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(u'Full text:\n{}'.format(
        annotation.text))

PHP

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

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Vision\V1\AnnotateFileResponse;
use Google\Cloud\Vision\V1\AsyncAnnotateFileRequest;
use Google\Cloud\Vision\V1\Feature;
use Google\Cloud\Vision\V1\Feature\Type;
use Google\Cloud\Vision\V1\GcsDestination;
use Google\Cloud\Vision\V1\GcsSource;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
use Google\Cloud\Vision\V1\InputConfig;
use Google\Cloud\Vision\V1\OutputConfig;

// $path = 'gs://path/to/your/document.pdf'

function detect_pdf_gcs($path, $output)
{
    # select ocr feature
    $feature = (new Feature())
        ->setType(Type::DOCUMENT_TEXT_DETECTION);

    # set $path (file to OCR) as source
    $gcsSource = (new GcsSource())
        ->setUri($path);
    # supported mime_types are: 'application/pdf' and 'image/tiff'
    $mimeType = 'application/pdf';
    $inputConfig = (new InputConfig())
        ->setGcsSource($gcsSource)
        ->setMimeType($mimeType);

    # set $output as destination
    $gcsDestination = (new GcsDestination())
        ->setUri($output);
    # how many pages should be grouped into each json output file.
    $batchSize = 2;
    $outputConfig = (new OutputConfig())
        ->setGcsDestination($gcsDestination)
        ->setBatchSize($batchSize);

    # prepare request using configs set above
    $request = (new AsyncAnnotateFileRequest())
        ->setFeatures([$feature])
        ->setInputConfig($inputConfig)
        ->setOutputConfig($outputConfig);
    $requests = [$request];

    # make request
    $imageAnnotator = new ImageAnnotatorClient();
    $operation = $imageAnnotator->asyncBatchAnnotateFiles($requests);
    print('Waiting for operation to finish.' . PHP_EOL);
    $operation->pollUntilComplete();

    # once the request has completed and the output has been
    # written to GCS, we can list all the output files.
    preg_match('/^gs:\/\/([a-z0-9\._\-]+)\/(\S+)$/', $output, $match);
    $bucketName = $match[1];
    $prefix = $match[2];

    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $options = ['prefix' => $prefix];
    $objects = $bucket->objects($options);

    # save first object for sample below
    $objects->next();
    $firstObject = $objects->current();

    # list objects with the given prefix.
    print('Output files:' . PHP_EOL);
    foreach ($objects as $object) {
        print($object->name() . PHP_EOL);
    }

    # 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.
    $jsonString = $firstObject->downloadAsString();
    $firstBatch = new AnnotateFileResponse();
    $firstBatch->mergeFromJsonString($jsonString);

    # get annotation and print text
    foreach ($firstBatch->getResponses() as $response) {
        $annotation = $response->getFullTextAnnotation();
        print($annotation->getText());
    }

    $imageAnnotator->close();
}

Ruby

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

# gcs_source_uri = "Google Cloud Storage URI, eg. 'gs://my-bucket/example.pdf'"
# gcs_destination_uri = "Google Cloud Storage URI, eg. 'gs://my-bucket/prefix_'"

require "google/cloud/vision"
require "google/cloud/storage"

image_annotator = Google::Cloud::Vision::ImageAnnotator.new

operation = image_annotator.document_text_detection(
  image: gcs_source_uri,
  mime_type: "application/pdf",
  batch_size: 2,
  destination: gcs_destination_uri,
  async: true
)

puts "Waiting for the operation to finish."
operation.wait_until_done!

# Once the request has completed and the output has been
# written to GCS, we can list all the output files.
storage = Google::Cloud::Storage.new

bucket_name, prefix = gcs_destination_uri.match("gs://([^/]+)/(.+)").captures
bucket              = storage.bucket bucket_name

# List objects with the given prefix.
puts "Output files:"
blob_list = bucket.files prefix: prefix
blob_list.each do |file|
  puts file.name
end

# Process the first output file from GCS.
# Since we specified a batch_size of 2, the first response contains
# the first two pages of the input file.
output      = blob_list[0]
json_string = output.download
response    = JSON.parse(json_string.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
puts "Full text:\n#{annotation['text']}"

Esta página foi útil? Conte sua opinião sobre:

Enviar comentários sobre…

Documentação da API Cloud Vision
Precisa de ajuda? Acesse nossa página de suporte.